搭建一個簡單的神經網路(向前傳播)
阿新 • • 發佈:2018-11-02
程式碼實現1:
#兩層簡單神經網路(全連線) import tensorflow as tf #定義輸入和引數 x=tf.constant([[0.7,0.5]])#一組X,表示體積和重量 w1=tf.Variable(tf.random_normal([2,3],stddev=1,seed=1))#兩行三列的正態分佈隨機陣列成的矩陣 w2=tf.Variable(tf.random_normal([3,1],stddev=1,seed=1)) #定義向前傳播過程 a=tf.matmul(x,w1) y=tf.matmul(a,w2) #用會話計算結果 with tf.Session() as sess: init_op=tf.global_variables_initializer() sess.run(init_op) print("y is :",sess.run(y))
輸出結果:
RESTART: C:/Users/lenovo/AppData/Local/Programs/Python/Python36/simplenn.py
y is : [[3.0904665]]
程式碼實現2:
#兩層簡單神經網路 import tensorflow as tf #定義輸入和引數 #用placeholder實現輸入定義(sess.run中喂一組資料) x=tf.placeholder(tf.float32,shape=(1,2))#一組X,表示體積和重量 w1=tf.Variable(tf.random_normal([2,3],stddev=1,seed=1))#兩行三列的正態分佈隨機陣列成的矩陣 w2=tf.Variable(tf.random_normal([3,1],stddev=1,seed=1)) #定義向前傳播過程 a=tf.matmul(x,w1) y=tf.matmul(a,w2) #用會話計算結果 with tf.Session() as sess: init_op=tf.global_variables_initializer() sess.run(init_op) print("y is :",sess.run(y,feed_dict={x:[[0.7,0.5]]}))
輸出結果:
RESTART: C:/Users/lenovo/AppData/Local/Programs/Python/Python36/simplenn2.py
y is : [[3.0904665]]
程式碼實現3:
#兩層簡單神經網路(全連線) import tensorflow as tf #定義輸入和引數 x=tf.placeholder(tf.float32,shape=(None,2)) w1=tf.Variable(tf.random_normal([2,3],stddev=1,seed=1))#兩行三列的正態分佈隨機陣列成的矩陣 w2=tf.Variable(tf.random_normal([3,1],stddev=1,seed=1)) #定義向前傳播過程 a=tf.matmul(x,w1) y=tf.matmul(a,w2) #用會話計算結果 with tf.Session() as sess: init_op=tf.global_variables_initializer() sess.run(init_op) print("y is :",sess.run(y,feed_dict={x:[[0.7,0.5],[0.2,0.3],[0.3,0.4],[0.4,0.5]]}))
輸出結果:
RESTART: C:/Users/lenovo/AppData/Local/Programs/Python/Python36/simplenn3.py
y is : [[3.0904665]
[1.2236414]
[1.7270732]
[2.2305048]]