TensorFlow实践——Softmax Regression

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/google19890102/article/details/77450071

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

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

'''
@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)

猜你喜欢

转载自blog.csdn.net/google19890102/article/details/77450071
今日推荐