前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >TensorFlow实践——Multilayer Perceptron

TensorFlow实践——Multilayer Perceptron

作者头像
felixzhao
发布2019-01-31 16:15:04
4710
发布2019-01-31 16:15:04
举报
文章被收录于专栏:null的专栏

本文是在Softmax Regression的基础上增加了一个隐含层,实现了Multilayer Perceptron的一个模型,Multilayer Perceptron是深度学习模型的基础,对于Softmax Regression的TensorFlow实现,可以参见博文“TensorFlow实践——Softmax Regression”。对于Multilayer Perceptron的基本原理,可以参见以下的文章:

下面的代码是利用TensorFlow的基本API实现的Softmax Regression:

代码语言:javascript
复制
'''
@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})

上述实现的运行结果如下所示:

参考文献

  1. [03]tensorflow实现softmax回归(softmax regression)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018年04月26日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 参考文献
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档