Tensor flow小案例——04简易手写数字识别

本文介绍了一个使用TensorFlow实现的手写数字识别模型,通过构建神经网络并在MNIST数据集上进行训练,逐步提高了识别准确率,最终达到90%以上。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# 定义神经网络中的隐藏层
def add_layer(inputs, size_inputs, size_outputs, act_fun = None):
    Weight = tf.Variable(tf.random_normal([size_inputs, size_outputs]))
    biases = tf.Variable(tf.zeros([1, size_outputs]) + 0.1)
    Wx_plus_b = tf.matmul(inputs, Weight) + biases
    if act_fun == None:
        output = Wx_plus_b
    else:
        output = act_fun(Wx_plus_b)
    return output

# 计算正确率
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))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})
    return result

# 引入数据
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)


# 定义输入变量
xs = tf.placeholder(tf.float32, [None, 784], name='x_in')
ys = tf.placeholder(tf.float32, [None, 10], name='y_in')

# 预测值
prediction = add_layer(xs, 784, 10, act_fun=tf.nn.softmax)

# 定义代价函数
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction), reduction_indices=[1]))

# 定义训练方法:梯度下降;  指定学习率:0.001(一定不要太大,否则会NAN);  训练目的:最小化loss
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)


# 初始化全部变量
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

# 迭代5,000次
for i in range(5000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys})
    # sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
    # 输出正确率
    if i % 50 == 0:
        print(compute_accuracy(mnist.test.images, mnist.test.labels))

sess.close()

 

 

结果:

0.1072
0.6214
0.7308
0.7728
0.7939
0.8129
0.8296
0.8383
0.8468
0.8515
0.8545
0.858
0.8628
0.8616
0.868
0.8686
0.871
0.8717
0.8752
0.8734
0.8782
0.8806
0.8787
0.8795
0.8792
0.8763
0.8838
0.8799
0.8808
0.8849
0.8826
0.8829
0.8863
0.8887
0.8888
0.8878
0.8867
0.8888
0.8901
0.8918
0.8864
0.8889
0.8905
0.8922
0.8896
0.8903
0.8905
0.8934
0.8911
0.8919
0.8924
0.8922
0.8923
0.897
0.8961
0.897
0.8952
0.8966
0.8968
0.8953
0.8981
0.8984
0.8961
0.8998
0.8977
0.8987
0.8968
0.8986
0.8978
0.9001
0.9016
0.9001
0.9015
0.8989
0.9015
0.8988
0.8978
0.9023
0.9023
0.902
0.903
0.8986
0.8971
0.9024
0.9029
0.9047
0.9058
0.9045
0.9054
0.9
0.9041
0.9059
0.9038
0.9016
0.9035
0.9041
0.9076
0.9057
0.9036
0.9058

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值