TensorFlow 入门教程(五) Classification分类学习——以mnist手写数字识别为例

之前所有内容都是线性回归,即预测分布是一个连续分布的值;而分类,则不同,输出为多个标签的分类结果。

实现步骤

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. 运行程序,查看结果。

注:以上代码源自网络,只是对其分析解读。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值