1. 程式人生 > >tensorflow基礎知識學習

tensorflow基礎知識學習

一:基礎單位
張量:多維陣列(列表) 階:表示張量的維度
標量:0階陣列 例子:s=1,2,3
向量:1階陣列 例子:v=[1,2,3]
矩陣:2階陣列 例子:m=[[1,2,3],[4,5,6],[7,8,9]]
張量:n階陣列 例子:t=[[…n個

二:定義陣列
1.常量
tf.constant([3,2,1]) #直接給定陣列[3,2,1]
tf.zeros([2,3],int32)#給定int32型別2行3列全為0的陣列
tf.ones([2,3],int32)#給定int32型別2行3列全為1的陣列
tf.fill([2,3],6) #給定2行3列全為6的陣列
2.變數
#定義一個2行3列,滿足方差為2,均值為0,隨機種子為1高斯分佈的變數
tf.variable(tf.randon_normal([2,3],stddev=2,mean=0,seed=1))
其中tf.randon_normal也可以用tf.trucated_normal(去掉過大偏離點的正態分佈),tf.random_uniform(均勻分佈)代替
3.需輸入變數
#效果等同於定義了一個虛參(個人感覺),在會話中呼叫它需要賦值
tf.placeholder(tf.float32,shape=(2,3))

三:簡單的實現程式碼

import tensorflow as tf

x = tf.constant([[1.0,2.0]])
w = tf.constant([[3.0],[4.0]])

result = tf.matmul(x,w)
print(result)
Tensor("MatMul:0", shape=(1, 1), dtype=float32)

result是MatMul:0的張量,是一維長度為1的陣列,資料型別是float32
值得注意的是這裡並沒有輸出result的值,而只是返回了result的型別,也就是說計算圖只描述運算過程,但未計算運算結果(只搭建網路,不運算)
返回的是x1*w1+x2*w2這個形式,但不計算具體值


那麼如何才能計算出輸出結果呢?這裡需要引入session會話:

import tensorflow as tf

x = tf.constant([[1.0,2.0]])
w = tf.constant([[3.0],[4.0]])

result = tf.matmul(x,w)
print(result)

with tf.Session() as sess:
    print(sess.run(result))
Tensor("MatMul:0", shape=(1, 1), dtype=float32)
[[11.]]