TensorFlow-多层感知机(MLP)
TensorFlow训练神经网络的4个步骤:
1、定义算法公式,即训练神经网络的forward时的计算
2、定义损失函数和选择优化器来优化loss
3、训练步骤
4、对模型进行准确率评测
附Multi-Layer Perceptron代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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}))