Tensorflow中最简单 mnist 手写体识别

机器学习中mnist相当于普通语言中的hello,world

使用softmax 函数实现
接下来就来实现它(我是在jupyter notebook上实现的)

#载入数据集,直接调用就行
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets("MNIST_data/",one_hot=True)
#查看是否载入成功
print(mnist.train.images.shape,mnist.train.labels.shape)
print(mnist.test.images.shape,mnist.test.labels.shape)
print(mnist.validation.images.shape,mnist.validation.labels.shape)
#创建于初始化参数
import tensorflow as tf
sess=tf.InteractiveSession()
x=tf.placeholder(tf.float32,[None,784])
w=tf.Variable(tf.zeros([784,10]))
b=tf.Variable(tf.zeros([10]))
#实现softmax Regression算法,直接调用就行
y=tf.nn.softmax(tf.matmul(x,w)+b)
#定义偏差损失函数
y_=tf.placeholder(tf.float32,[None,10])
cross_entropy=tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))
#梯度下降 更新参数
train_step=tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
tf.global_variables_initializer().run()
#开始训练
for i in range(1000):
    batch_xs,batch_ys=mnist.train.next_batch(100)
    train_step.run({
    
    x:batch_xs,y_:batch_ys})
#测试样本
correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
print(accuracy.eval({
    
    x:mnist.test.images,y_:mnist.test.labels}))
#关闭,防止内存泄露
tf.InteractiveSession.close(sess)

下面是输出
在这里插入图片描述
因为是最简单的过程,没有加任何优化,所以正确率大概在92%左右,如果加上优化可达98% 99%.

猜你喜欢

转载自blog.csdn.net/qq_43570528/article/details/101603579