编写简单的单层网络实现MNIST数据集分类(代码如下)
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 载入数据
"""one_hot参数把标签转化到0-1之间
"""
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
# 每个批次大小(每次放入训练图像数量)
batch_size = 100
# 批次数量
num_batch = mnist.train.num_examples // batch_size
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])
w = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.random_normal([10]))
prediction = tf.nn.softmax(tf.matmul(x, w) + b) # 概率值转化: softmax()
# loss = tf.reduce_mean(tf.square(y - prediction)) # 二次代价函数
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y, logits=prediction)) # 交叉熵代价函数
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
init = tf.global_variables_initializer()
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1)) # argmax()返回一维张量中最大值所在的位置
# 计算准确率
"""cast()将correct_prediction列表变量中的值转换成float32 --> true=1.0,false=0.0
"""
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # cast()相当于类型转换函数
with tf.Session() as sess:
sess.run(init)
for epoch in range(21):
for batch in range(num_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys})
acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})
print('iter' + str(epoch) + ', testing accuracy:' + str(acc))