1. 程式人生 > 實用技巧 >tensorflow學習筆記1

tensorflow學習筆記1

tensorflow處理的是圖形影象,圖形圖形都是二維平面,所以資料都用矩陣來表示。

定義w,x,注意定義方式,進行矩陣相乘matmul()函式時,w,x必須是一行一列的表示方式,否則會報錯。

import tensorflow as tf

#定義w,x,y
w = tf.Variable([[0.5,1.0]]) #一行 分別是0.5 1.0
x = tf.Variable([[2.0],[1.0]]) #兩行
y = tf.matmul(w,x)

#定義一種操作是把全部變數初始化
init_op = tf.compat.v1.global_variables_initializer()
#這些操作必須在Session裡面跑
with tf.compat.v1.Session() as sess: sess.run(init_op) #輸出y的值要呼叫eval()函式輸出 print(y.eval())

另一種寫法:先用placeholder進行佔位,再在Session()中喂資料

#另一種寫法
input1 = tf.compat.v1.placeholder(tf.float32,shape=[2,1])
input2 = tf.compat.v1.placeholder(tf.float32,shape=[1,2])
output = tf.matmul(input1,input2)

with tf.compat.v1.Session() as sess:
    sess.run([output],feed_dict
={input1:[[0.5,1.0]],input2:[[2.0],[1.0]]}) print(output.eval())

注:該段程式碼有誤。

遇到的問題:喂入的資料是二維的時候,placeholder的shape出現了問題,我認為我寫的是正確的,但會報錯,還沒找到錯誤原因,如有大佬請指正!

Traceback (most recent call last):
File "F:/python/learn/03.py", line 23, in <module>
sess.run([output],feed_dict={input1:[[0.5,1.0]],input2:[[2.0],[1.0]]})
File "D:\Ananconda\lib\site-packages\tensorflow\python\client\session.py", line 950, in run
run_metadata_ptr)
File "D:\Ananconda\lib\site-packages\tensorflow\python\client\session.py", line 1149, in _run
str(subfeed_t.get_shape())))
ValueError: Cannot feed value of shape (1, 2) for Tensor 'Placeholder:0', which has shape '(2, 1)'