Tensor的數據類型
張量的創建
數據類型:
1.int32
2. float32
3. float64 對應 tf.double
4. bool
5. string
使用tf.constant()可以創建一個Tensor
tf.constant(1)
tf.constant(1.)
tf.constant(2.2,dtyoe=tf.double)
tf.constant([True,False])
tf.constant('helllo world')
相關屬性
我們假設有一個tensor a
1.a.device
顯示該張量所處於的設備,實在gpu:x或者cpu上
張量的相關操作必須在同一個設備上
2.a.gpu()
把張量a轉移到gpu上
3.a.cpu()
把張量轉換到cpu上
4.a.shape
返回一個list,展示一個tensor的shape
5.a.ndim或a.rank
返回一個tensor,表示這個tensor的緯度
[1,1,1,1] ---->返回tensor[1]
6.檢查tensor的數據類型
常規的python方法 isinstance
檢查a是否爲tf.Tensor的子類
isinstance(a,tf.Tensor)
用tf2.0自有的api檢查
api:tf.is_tensor()
tf.is_tensor(a)
7.獲取Tensor的數據類型
a.dtype ==tf.float32
a.dtype ==tf.string
上面的代碼展示瞭如何獲取數據類型,並作出判斷
類型轉換
1.numpy轉爲tensor
api:tf.conver_to_tensor
a=np.arange(5)
tensor_a=tf.conver_to_tensor(a)
tensor_a=tf.conver_to_tensor(a,dtype=tf.int32)
2.tensor的類型互相轉換
api:tf.cast()
tf.cast(aa,dtype=tf.double)
#把aa轉化爲float64類型
把aa轉化爲dtype類型
對於int和bool類型互相轉化,可以讓1 0和True False互相轉化
3.把tensor轉化爲numpy
同時在gpu上的數據會自動返回到cpu上
a.numpy()
tf.Variable
把tensor進行一個修飾,讓其具有梯度屬性
內部屬性:
1.name
tensor的名字
2.trainable
布爾值,tensor是否可訓練
注意
:要判斷一個變量是否爲variable時,需要使用tf.is_tensor,使用python內部的isinstance會產生錯誤的結果。
Tensor的創建
從numpy和list創建一個tensor
從numpy
1.tf.convert_to_tensor(np.ones([2,3]))
從list
2.tf.conver_to_tensor([1,2])
從api創建
1.tf.zeros()
括號內部的參數爲shape
創建標量0 ------->tf.zeros([ ])
2.tf.zeros_like()
內部的參數爲一個tensor,表示創建一個和括號內部變量相同shape的tensor
相當於複製了,參數tensor的緯度的一個全0張量
3.tf.fill()
兩個參數,參數1爲shape,參數2爲要填充的值
4.Normal用正態分佈初始化
tf.random.normal([2,2],mean=1,std=1)
默認爲0 1分佈
tf.random.trucated_normal()
截斷型正態分佈
tf.random.uniform([2,2],minval=0,maxval=1)
均分分佈,從0到1之間
5.隨機化shuffle( Random permutation )
idx=tf.range(10)
idx=tf.random.shuffle(idx)
a=tf.random.normal([10,784])
lable=tf.random.uniform([10],minval=0.maxval=10,dtype=tf.int32)
a=tf.gather(a,idx)
lables=tf.gather(label.idx)
6.tf.constant類似於tf.conver_to_tensor
接受scalar和list