1. 程式人生 > >TensorFlow-多層感知機(MLP)

TensorFlow-多層感知機(MLP)

訓練 感知 set equal () closed batch BE lac

TensorFlow訓練神經網絡的4個步驟:

1、定義算法公式,即訓練神經網絡的forward時的計算

2、定義損失函數和選擇優化器來優化loss

3、訓練步驟

4、對模型進行準確率評測

附Multi-Layer Perceptron代碼:

技術分享圖片
 1 from tensorflow.examples.tutorials.mnist import input_data
 2 import tensorflow as tf
 3 
 4 mnist=input_data.read_data_sets("MNiST_data/",one_hot=True)
 5 sess=tf.InteractiveSession()
6 7 in_units=784 8 h1_units=300 9 w1=tf.Variaable(tf.truncated_normal([in_units,h1_units],stddev=0.1)) 10 b1=tf.Variable(tf.zeros([h1_units])) 11 w2=tf.Variable(tf.zeros([h1_units,10])) 12 b2=tf.Variable(tf.zeros([10])) 13 14 x=tf.placeholder(tf.float32,[None,in_units]) 15 keep_prob=tf.placeholder(tf.float32)
16 17 hidden1=tf.nn.relu(tf.matmul(x,w1)+b1) 18 hidden1_drop=tf.nn.dropout(hidden1,keep_prob) 19 y=tf.nn.softmax(tf.matmul(hidden1_drop,w2)+b2) 20 21 y_=tf.placeholder(tf.float32,[None,10]) 22 cross_entropy=tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1])) 23 train_step=tf.train.AdagradOptimizer(0.3).minimize(cross_entropy)
24 25 tf.initialize_all_variables().run() 26 for i in range(3000): 27 batch_xs,batch_ys=mnist.train.next_batch(100) 28 train_step.run({x:batch_xs,y_:batch_ys,keep_prob:0.75}) 29 30 correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(y_,1)) 31 accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) 32 print(accuracy.eval({x:mnist.test.images,y_:mnist.test.labels,keep_prob:1.0}))
View Code

TensorFlow-多層感知機(MLP)