tensorflow实现mnist手写数字识别

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

# 载入数据
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

# 定义tensorflow结构
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y_ = tf.placeholder(tf.float32, [None, 10])

"""激励函数softmax和loss函数交叉熵"""
y = tf.nn.softmax(tf.matmul(x, W) + b)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), axis=1))

"""或者用tf内置的loss函数,注意tf.nn.softmax_cross_entropy_with_logits已内置softmax变换"""
# y_l = tf.matmul(x,W) + b
# cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_l))

"""用梯度下降提升"""
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

"""初始化全部变量"""
init = tf.global_variables_initializer()

# 训练
sess = tf.Session()
sess.run(init)

"""进行600次更新,SGD每批次输入100个样本"""
for i in range(600):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
# 评估模型,每20步打印准确率
if i % 20 == 0:
"""tf.argmax返回最大值的index,tf.equal比较是否相等"""
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
"""转换为数字并求平均,如[True,False,False,True]转化为[1,0,0,1],平均值为0.5"""
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
"""用测试数据计算,并打印准确率"""
print(i, sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

sess.close()

“tensorflow实现mnist手写数字识别”的2个回复

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注