TensorFlow实现 Softmax Regression 识别手写数字

#1.进入python环境
#python

#2.加载数据集
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)

#3.打印数据集的信息
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)

#4.创建一个新的InteractiveSession
import tensorflow as tf
sess = tf.InteractiveSession()

#5.创建一个placeholder,即输入数据的地方
x = tf.placeholder(tf.float32,[None,784])

#6.给模型中的Softmax Regression模型中的weights和biases创建Variable对象
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))

#7.实现Softmax Regression算法
y = tf.nn.softmax(tf.matmul(x, W) + b)

#8.使用cross-entropy作为损失函数
y_ = tf.placeholder(tf.float32,[None,10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),reduction_indices=[1]))

#9.定义优化算法(使用随机梯度下降SGD),设置学习率为0.5,优化目标设定为cross-entropy
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

#10.全局参数初始化并执行
tf.global_variables_initializer().run()

#11.迭代地执行训练操作
for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    train_step.run({x: batch_xs, y_: batch_ys})

#12.准确率验证
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels}))

猜你喜欢

转载自blog.csdn.net/wfx18765903641/article/details/86636381
今日推荐