Tensor數據類型
- list: [1,1.2,'hello'] ,存儲圖片占用內存非常大
- np.array,存成一個靜態數組,但是numpy在深度學習之前就出現了,所以不適合深度學習
- tf.Tensor,為了彌補numpy的缺點,更多的是為了深度學習而生
- tensor:
- scalar:標量,1.1
- vector:向量,[1.1],[1.1,2.2,...]
- matrix: 矩陣,[[1.1,2.2],[3.3,4.4]]
- tensor:rank>2
- 數據類型:
- Int, float, double
- bool
- string
- 定義tensor
tf.constant(1) # 定義常量,普通的tensor
tf.constant(1.) # 定義常量,普通的tensor
tf.constant([True, False]) # 定義常量,普通的tensor
tf.constant('hello nick')
屬性
with tf.device('cpu'):
a = tf.constant([1])
with tf.device('gpu'):
b = tf.constant([1])
a.device # 設備屬性
a.gpu() # cpu轉gpu
a.numpy() # 獲取numpy數據類型
a.shape # 獲取a的屬性
a.ndim # 獲取維度
tf.rank(a) # 獲取維度
a.name # 1.+歷史遺留問題
數據類型判斷
instance(a,tf.Tensor) # 判斷是否為tensor
tf.is_tensor(a) # 判斷是否為tensor
a.dtype,b.dtype,c.dtype # 判斷數據類型
數據類型轉換
a = np.arange(5)
aa = tf.convert_to_tensor(a,dtype=tf.int32) # numpy轉tensor
tf.cast(aa,dtype=tf.float32) # tensor之間數據類型轉換
# int --》 bool
b = tf.constant([0,1])
tf.cast(b,dtype=tf.bool) # int --》bool
# tf.Variable
a = tf.range(5)
b = tf.Variable(a) # tensor轉為Variable后具有求導的特性,即自動記錄a的梯度相關信息
b.name # Variable:0
b = tf.Variable(a, name='input_data')
b.name # input_data:0
b.trainable # True
isinstance(b,tf.Tensor) # False
isinstance(b,tf.Variable) # True
tf.is_tensor(b) # True # 推薦使用
tensor轉numpy
a= tf.range(5)
a.numpy()
# a必須是scalar
a = tf.ones([])
a.numpy()
int(a)
float(a)