在tensorflow2.0版本以前,1.x版本的tensorflow的基本數據類型有計算圖(Computation Graph)和張量(Tensor)兩種,但tensorflow2.0以後的版本取消了Graph和Session的概念。今天簡單記錄一下Tensor的相關內容。api
從Tensorflow的命名就不難看出,Tensor(張量)在整個tensorflow的框架體系中都是一個重要的概念,它能夠稱爲Tensorflow的數據模型,由於Tensor是tensorflow管理數據的形式,換句話說,在tensorflow中,全部的數據均可以藉助張量的形式來表示。在張量出現以前,咱們比較熟悉這樣兩種數據類型:list和np.array。list就很少說了,對於大量數據list的表現並非很好,假設有一個維度[64,24,24,3]的數據,它在深度學習中實際上是一個比較小的數據,可是對於list來講倒是一個很龐大的數據,佔用的內存空間更是沒法估量。而爲了解決大數據的吞吐,對於相同類型的數據載體,np.numpy有很好的表現,可是numpy是在tensorflow以前出現的一個科學計算庫,對GPU並不支持,也不支持自動求導,爲了更好的解決深度學習中的問題,tensorflow開始出現。網絡
在數學中,一個0維的數據(dim=0),即1.1,2.2等等被稱爲一個標量(scalar),一個一維的數據(dim=1),即[1.1],[2.2,3.3,……]等被稱做向量(vector),一個維度大於2的數據,如[[1,2],[3,4]]被稱爲矩陣(matrix),而Tensor通常是指維度大於2的向量(矩陣),可是在tensorflow中,以上全部的類型均可以被稱爲tensor。框架
建立不一樣類型的數據:dom
# int型 a = tf.constant(1) # float型 b = tf.constant(1.) # double型 c = tf.constant(2.,dtype=tf.float64) # bool型 d = tf.constant([True,False]) # string型 e = tf.constant('hello world')
獲得結果以下:函數
經常使用屬性以下:學習
# 使用numpy聲明一個數據 a=np.arange(5) # 將其轉化爲tensor aa=tf.convert_to_tensor(a) # 強制類型轉換 int——float bb=tf.cast(aa,dtype=tf.float32) # .numpy()將tensor返回numpy顯示數據 print(aa.numpy())
獲得大數據
如何建立一個tensor:編碼
# 經過numpy建立數據轉換 a = tf.convert_to_tensor(np.ones([2,3])) # list轉換 b = tf.convert_to_tensor([1,2]) # 初始化全爲0的tensor(tf.ones()用法同tf.zeros()) c = tf.zeros([2,2]) # 以指定tensor的shape爲基礎建立新的tensor(同tf.zeros(c.shape)) d = tf.zeros_like(c) # 填充任意元素 e = tf.fill([2,2],9) # 隨機化初始化: # 正態分佈,mean指定均值,stddev指定方差 f = tf.random.normal([2,2],mean=1,stddev=1) # 截斷正態分佈 g = tf.random.truncated_normal([2,2],mean=1,stddev=1) # 均勻分佈 h = tf.random.uniform([2,2],minval=0,maxval=1)
捎帶提一點打亂順序函數的用法:spa
# 隨機打散 i = tf.range(10) i = tf.random.shuffle(i) x = tf.random.uniform([10],maxval=10,dtype=tf.int32) y = tf.random.uniform([10],maxval=10,dtype=tf.int32) print(i.numpy()) print("x:",x.numpy()) print("y:",y.numpy()) # .gather指定按照某一索引序列取值 x = tf.gather(x,i) y = tf.gather(y,i) print("x:",x.numpy()) print("y:",y.numpy())
能夠看到按照同一打亂序列取值後,x和y仍然是一一對應的關係scala
tensor中scalar最經常使用的部分:loss和accuracy
損失(loss)和精度(accuracy)在前面迴歸和mnist實戰都已經提過,這裏再也不解釋其概念,簡單說明一下loss的求值方法
# 生成一組數據用來模擬四張圖片的網絡輸出 out = tf.random.uniform([4,10]) print(out) # 模擬四張圖片對應的label y = tf.range(4) print(y) # 使用one_hot對label進行編碼 y = tf.one_hot(y,depth=10) print(y) # 調用keras的api來計算損失(MSE均方偏差) loss = tf.keras.losses.mse(y,out) print(loss) # 求loss的均值 loss = tf.reduce_mean(loss) print(loss)