TensorFlow(三)——MNIST分类

import input_data
import tensorflow as tf

mnist = input_data.read_data_sets('data/', one_hot=True)

#定义回归模型
x = tf.placeholder(tf.float32, [None, 784])
w = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, w) + b

#定义损失函数和优化器
y_ = tf.placeholder(tf.float32, [None, 10])
#用tf.nn.softmax_cross_entropy_with_logits计算预测值y和真值y_的差值,并取均值
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y, labels=y_))
#采用SGD作为优化器
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

#使用InteractiveSession()创建交互式上下文的TensorFlow会话,可以先定义会话再定义操作
sess = tf.InteractiveSession()

tf.global_variables_initializer().run()

#Train
for _ in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={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))
#计算在测试集上的准确率
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

结果:
 

0.9154

猜你喜欢

转载自blog.csdn.net/MRxjh/article/details/82633394