笔记 - tensorflow小案例:Softmax多分类(mnist手写体数据集识别)

57 篇文章 1 订阅
22 篇文章 0 订阅

通用步骤

  • 准备参数
  • 定义损失函数
  • 定义优化器
  • 正式训练
"""
tf的mnist(手写数字)数据集
tf.nn下实现的softmax算法

定义输入数据
定义参数
编写交叉熵损失参数
梯度下降优化器处理
统计预测的准确率

正式训练
"""

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

n_epochs = 1000
learning_rate = 0.001
batch_size = 100

data = input_data.read_data_sets("MNIST_data_bak/", one_hot=True)  # 下载的mnist数据集存储的位置
X = tf.placeholder(dtype=tf.float32, shape=(None, 784))
y = tf.placeholder(dtype=tf.float32, shape=(None, 10))
W = tf.Variable(tf.zeros((784, 10)))
b = tf.Variable(tf.zeros([10]))

"""softmax预测值"""
y_pred = tf.nn.softmax(tf.matmul(X, W) + b)
"""交叉熵"""
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(y_pred), reduction_indices=[1]))
# cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(y_pred), axis=1)) 这样写也行
"""优化器"""
training_op = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cross_entropy)
"""评估"""
prediction = tf.equal(tf.argmax(y_pred, axis=1), tf.argmax(y, axis=1))
accuracy = tf.reduce_mean(tf.cast(prediction, tf.float32))

init = tf.global_variables_initializer()

"""正式训练"""
with tf.Session() as sess:
    init.run()
    for epoch in range(n_epochs):
        batch_xs, batch_ys = data.train.next_batch(batch_size)
        sess.run(training_op, feed_dict={X: batch_xs, y: batch_ys})
        print("Epoch ", epoch)
        print("cross_entropy:", cross_entropy.eval({X: batch_xs, y: batch_ys}))
        print("TrainSet Accuracy", accuracy.eval({X: batch_xs, y: batch_ys}))
        print("ValidSet Accuracy", accuracy.eval({X: data.validation.images, y: data.validation.labels}))

    print(accuracy.eval({X:data.test.images, y:data.test.labels}))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值