(Tensorflow之二)張量、會話、向前傳播

一、張量
張量本身只是一個計算的過程,不會存儲結果;例如:
a = tf.constant(30)
b = tf.constant(20)
c = a + b
print(c)
結果:Tensor(“add:0”, shape=(), dtype=int32)

二、會 話(session)
前面所說的張量只是一個過程,若要獲得計算結果,則需創建會話,運行張量的流程:
sess = tf.Session()
d = sess.run(c)
print(d)
結果:50

三、向前傳播

import tensorflowas tf

#輸入層(設有3個輸入變量1x3)
in_layer = tf.random_normal([1,3],mean=-1, stddev=4)

#設定輸入層到隱含層隨機權重(設隱含層有3個神經元3x3)
in_to_hd_w1 = tf.Variable(tf.random_normal([3,3],mean=-1, stddev=4))

#隱含層3個神經元的值(1x3)
hd_layer = tf.matmul(in_layer,in_to_hd_w1)

#隱含層到輸出層隨機權重(3x1)
hd_to_out_w2 = tf.Variable(tf.random_normal([3,1],mean=-1, stddev=4))

#僅有一個輸出值(1x1)
out_layer = tf.matmul(hd_layer,hd_to_out_w2)

sess = tf.Session()

#注:變量必須要有初始值,in_to_hd_w1與in_to_hd_w2需初始話
sess.run(in_to_hd_w1.initializer);
sess.run(hd_to_out_w2.initializer);

#輸出值
print(sess.run(out_layer))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章