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

TensorFlow实践——Softmax Regression

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

Softmax Regression是Logistic回归在多分类上的推广,对于Logistic回归以及Softmax Regression的详细介绍可以参见:

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

代码语言:javascript
复制
'''
@author:zhaozhiyong
@date:20170822
Softmax Regression
'''

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.01
training_epochs = 1000
batch_size = 100
display_step = 50

n_input = 784
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_classes]))
b1 = tf.Variable(tf.random_normal([n_classes]))

pred = tf.add(tf.matmul(x, w1), b1)

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月18日,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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