1. 程式人生 > >搭建神經網絡構建八股

搭建神經網絡構建八股

batch odi bubuko bat tst 源碼 體積 color 目標

學習目標:通過例子,搭建神經網絡的八股

一、流程

1. 導入模塊,生成模擬數據集;
  import
  常量定義
  生成數據集
2. 前向傳播: 定義輸入、參數和輸出(搭建模型)
  x     y_
  w1   w2
  a    y
3. 反向傳播:定義損失函數、反向傳播方法(用於訓練模型參數)
  loss=
  train_step=
4. 生成會話,訓練 STEPS 輪

二、例程

例:隨機產生 32 組生產出的零件的體積和重量,訓練 3000 輪,每 500 輪輸出一次損失函數。

源碼:

 1 #coding :utf-8
 2 
 3 #--1-- 
 4 import tensorflow as tf
5 import numpy as np 6 7 BATCH_SIZE=8 8 seed=23455 9 10 rng=np.random.RandomState(seed) 11 X=rng.rand(32,2) #生成32行2列的列表(矩陣) 12 13 Y=[[int(x0+x1<1)]for (x0,x1) in X] #對於X中的每一個(x0,x1),判斷x0+x1<1成立,Y為1,否則為0,Y為32行2列的2唯張量 14 print "X:\n",X 15 print "Y:\n",Y 16 17 #--2--相當於提前定義,聲明變量, 前向傳播,搭建計算模型 18
x=tf.placeholder(tf.float32,shape=(None,2)) 19 y_=tf.placeholder(tf.float32,shape=(None,1)) 20 21 w1=tf.Variable(tf.random_normal([2,3],stddev=1,seed=1)) 22 w2=tf.Variable(tf.random_normal([3,1],stddev=1,seed=1)) 23 24 a=tf.matmul(x,w1) 25 y=tf.matmul(a,w2) 26 27 #--3--反向傳播 定義損失函數和優化方法 28 loss=tf.reduce_mean(tf.square(y-y_))
29 train_step=tf.train.GradientDescentOptimizer(0.001).minimize(loss) 30 31 #--4-- 32 with tf.Session() as sees: 33 init_op=tf.initialize_all_variables() 34 sees.run(init_op) 35 print "w1\n",sees.run(w1)#打印初始的w1和w2 36 print "w2\n",sees.run(w2) 37 38 STEPS=3000#叠代執行3000次,訓練 39 for i in range(STEPS): 40 start=(i*BATCH_SIZE)%32 #每一次取8組餵給NN,進行優化訓練 41 end=start+BATCH_SIZE 42 sees.run(train_step,feed_dict={x:X[start:end],y_:Y[start:end]}) 43 if i%500==0: 44 total_loss=sees.run(loss,feed_dict={x:X,y_:Y}) #打印損失函數的結果 45 46 #-----print------ 47 print "\n" 48 print "w1:\n",sees.run(w1) 49 print "w2:\n",sees.run(w2)

結果:

1)# source activate tensorflow 進入tensorflow環境

2)執行# python NN_1.py

技術分享圖片

搭建神經網絡構建八股