TensorFlow实战Chp3-实现Softmax Regression识别手写数字

  • TensorFlow实战Chp3-实现Softmax Regression识别手写数字
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 13 19:28:21 2018

@author: muli
"""

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

print(mnist.train.images.shape, mnist.train.labels.shape)
print(mnist.test.images.shape, mnist.test.labels.shape)
print(mnist.validation.images.shape, mnist.validation.labels.shape)


#tf.InteractiveSession.close()
sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32, [None, 784])

W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

# softmax的使用
y = tf.nn.softmax(tf.matmul(x, W) + b)

# 标签
y_ = tf.placeholder(tf.float32, [None, 10])

# 损失函数:交叉熵
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))

# 随机梯度下降
# 学习率为a为0.5,优化目标为cross_entropy
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

# 全局参数初始化器
tf.global_variables_initializer().run()

# 迭代训练
for i in range(1000):
    # 随机抽样
    batch_xs, batch_ys = mnist.train.next_batch(100)
    # 训练
    train_step.run({x: batch_xs, y_: batch_ys})

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# 评测流程accuracy 
# 在测试集上进行预测
print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels}))

猜你喜欢

转载自blog.csdn.net/mr_muli/article/details/81208870