之前所有内容都是线性回归,即预测分布是一个连续分布的值;而分类,则不同,输出为多个标签的分类结果。
实现步骤
1. 利用 placeholder 为输入(xs)和输出(ys)占位(注意参数)
# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 784]) # 28x28,784像素点
ys = tf.placeholder(tf.float32, [None, 10]) #10为图像的标签数量,为类别数
2. 定义神经网络层,损失函数
# add output layer
prediction = add_layer(xs, 784, 10, activation_function=tf.nn.softmax)
#softmax一般用于图像分类
# the error between prediction and real data
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
reduction_indices=[1])) # loss
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
sess = tf.Session()
3. 提取部分的xs与ys用于训练,提高效率
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100) #提取部分的xs与ys,提高学习速度
sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys})
if i % 50 == 0:
print(compute_accuracy(
mnist.test.images, mnist.test.labels)) #输出正确率
4. 定义正确率计算函数
def compute_accuracy(v_xs, v_ys):
global prediction
y_pre = sess.run(prediction, feed_dict={xs: v_xs}) #生成预测值,是一个概率
correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
#判断预测概率最大值的位置是否等于真实的位置,返回true或者false
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#tf.cast()数据类型转换,cast(x, dtype, name=None)
# 第一个参数 x: 待转换的数据(张量)
# 第二个参数 dtype: 目标数据类型
# 第三个参数 name: 可选参数,定义操作的名称
#tf.reduce_mean() 在tensor的某一维度上求平均值的函数
result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})
return result
5. 运行程序,查看结果。
注:以上代码源自网络,只是对其分析解读。