在TensorFlow中所有的數據都通過張量的形式表示,從功能上看張量可以被簡單的理解為多維數據,其中零階張量表示標量(一個數),第一階張量為向量(一個一維數組),第n階向量可以理解為一個n維數組。
但是TensorFlow中實現並不是直接采用數組的形式,它只是對TensorFlow中運算結果的引用。在張量中並沒有保存真正的數字,它保存的是如何得到這些數字的計算過程。
import tensorflow as tf # tf.constant是一個計算,這個計算的結果是一個張量保存在變量a中 a = tf.constant([1.0, 2.0], name="a") b = tf.constant([3.0, 4.0], name="b") c = tf.constant([1.0, 1.0, 1.0], name="c") result = tf.add(a, b, name="add") print(result) print(a) print(c) """ Tensor("add:0", shape=(2,), dtype=float32) Tensor("a:0", shape=(2,), dtype=float32) Tensor("c:0", shape=(3,), dtype=float32) """
從輸出結果可以看出TensorFlow中的張量和NumPy中的數組不同,TensorFlow計算的結果不是一個具體的數字,而是一個張量結構,一個張量(tensor)中主要保存了三個屬性:名字(name), 維度(shape),類型(type)
name屬性是一個張量的唯一標識符,同樣也給出了這個張量是如何計算出來的
shape屬性是張量的維度,描述了張量的維度信息(程序中a變量的維度為2, c的為3)
type屬性表示出一個張量只有一個唯一的類型
如果不指定type,TensorFlow會給出默認類型。不帶小數點的默認int32,帶小數點的默認float32。由於使用默認類型可能會帶來類型不匹配的問題,一般會通過dtype來明確指出變量或常量的類型。
TensorFlow支持14種數據類型,主要包括:實數(tf.float32, tf.float64),整數(tf.int8, tf.int16, tf.int32, tf.int64, tf.uint8),布爾型(tf.bool), 復數(tf.complex64, tf.complex128)
張量的使用主要分為兩類:一,對中間計算結果的引用;二,計算圖構造完成后可以用來獲取計算結果(數字)
# 使用張量計算中間結果 a = tf.constant([1.0, 2.0], name="a") b = tf.constant([3.0, 4.0], name="b") result = tf.add(a, b, name="add") # 獲取張量的維度信息 print(result.get_shape) # tf.Session().run(result)可得到計算結果 print(tf.Session().run(result)) """ 輸出 <bound method Tensor.get_shape of <tf.Tensor 'add:0' shape=(2,) dtype=float32>> [4. 6.] """