深度学习tensorflow之softmax(一)手写数字识别

代码实现

import tensorflow as tf
import random
from matplotlib import pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data

# 确定随机种子 保证每次运行结果一致
tf.set_random_seed(1)

# 读取mnist数据
mnist = input_data.read_data_sets(r'MNIST_data',one_hot=True)

n_class = 10

# 数据中图片的像素是28*28=784
# 设置占位符
X = tf.placeholder(dtype=tf.float32,shape=[None,784])
Y = tf.placeholder(dtype=tf.float32,shape=[None,n_class])

# 建立模型
# 初始化W,b
W = tf.Variable(tf.random_normal([784,n_class]))
b = tf.Variable(tf.random_normal([n_class]))

h = tf.nn.softmax(tf.matmul(X,W) + b)

# 定义代价
cost = tf.reduce_mean(tf.reduce_sum(-(Y * tf.log(h)),axis=1))

# 梯度下降训练
trains = tf.train.GradientDescentOptimizer(learning_rate=0.03).minimize(cost)

# 准确率
accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.arg_max(h,1),tf.arg_max(Y,1)),dtype=tf.float32))

# 参数
train_times = 15
batch_size = 100

# 开启会话
with tf.Session() as sess:
    # 初始化所有变量
    sess.run(tf.global_variables_initializer())
    # 开始训练
    # 训练批次
    for times in range(train_times):
        avg_cost = 0
        total_batch = int(mnist.train.num_examples / batch_size)
        # 小批次训练
        for i in range(total_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            c, _ = sess.run([cost,trains],feed_dict={X: batch_xs,Y: batch_ys})
            avg_cost += c / total_batch
        print(times+1,'cost: ',avg_cost)
    print('训练完毕')

    print('准确率: ',sess.run(accuracy,feed_dict={X: mnist.test.images,Y: mnist.test.labels}))

    #
    r = random.randint(0,mnist.test.num_examples-1)
    print('labels: ',sess.run(tf.argmax(mnist.test.labels[r:r+1],1)))
    print('prediction: ',sess.run(tf.argmax(h,1),feed_dict={X: mnist.test.images[r:r+1]}))

    # 画图
    plt.imshow(
        mnist.test.images[r:r+1].reshape(28,28),
        cmap='Greys',
        interpolation='nearest'
    )
    plt.show()

结果如下

在这里插入图片描述

画图如下

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值