TensorFlow实践——Multilayer Perceptron
本文是在Softmax Regression的基础上增加了一个隐含层,实现了Multilayer Perceptron的一个模型,Multilayer Perceptron是深度学习模型的基础,对于Softmax Regression的TensorFlow实现,可以参见博文“TensorFlow实践——Softmax Regression”。对于Multilayer Perceptron的基本原理
·
本文是在Softmax Regression的基础上增加了一个隐含层,实现了Multilayer Perceptron的一个模型,Multilayer Perceptron是深度学习模型的基础,对于Softmax Regression的TensorFlow实现,可以参见博文“TensorFlow实践——Softmax Regression”。对于Multilayer Perceptron的基本原理,可以参见以下的文章:
下面的代码是利用TensorFlow的基本API实现的Softmax Regression:
'''
@author:zhaozhiyong
@date:20170821
Multilayer Perceptron
'''
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./MNIST_data", one_hot=True)
learning_rate = 0.05
training_epochs = 1000
batch_size = 100
display_step = 50
n_input = 784
n_hidden = 256
n_classes = 10
x = tf.placeholder("float", [None, n_input])
y = tf.placeholder("float", [None, n_classes])
w1 = tf.Variable(tf.random_normal([n_input, n_hidden]))
b1 = tf.Variable(tf.random_normal([n_hidden]))
hidden = tf.add(tf.matmul(x, w1), b1)
hidden = tf.nn.relu(hidden)
#hidden = tf.nn.sigmoid(hidden)
w2 = tf.Variable(tf.random_normal([n_hidden, n_classes]))
b2 = tf.Variable(tf.random_normal([n_classes]))
pred = tf.add(tf.matmul(hidden, w2), b2)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for epoch in range(training_epochs):
avg_cost = 0
total_batch = int(mnist.train.num_examples/batch_size)
for i in range(total_batch):
batch_x, batch_y = mnist.train.next_batch(batch_size)
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y})
avg_cost += c / total_batch
if epoch % display_step == 0:
print "Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost)
print "Optimization Finished!"
print "Get test data:"
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print "Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})
上述实现的运行结果如下所示:
参考文献
更多推荐
所有评论(0)