深度学习(一)——简单神经网络识别手写数字

MNIST数据集相当于深度学习中的“Hello World”,用于开始做测试用的简单的视觉数据集,由几万张28*28的手写数字组成,只包含灰度信息,分为十类0~9。

1.主要步骤

1)选择softmax regression模型
2)定义算是函数,这里选择交叉熵
3)选择优化算法梯度下降法
4)迭代进行数据训练
5)进行验证和准确率评测

2,代码

#加载数据
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf

#训练集5.5w,测试机1w,验证集0.5w,每个样本有一个label
mnist=input_data.read_data_sets("MNIST_data/",one_hot=True)

#label是一个10维的向量,[1,0,0,0,0,0,0,0,0,0],其代表数字为0


#placeholder数据输入的地方,第一个参数数据类型,第二个参数是数据尺寸大小
sess=tf.InteractiveSession()
x=tf.placeholder(tf.float32,[None,784])

#定义权重和截距b
W=tf.Variable(tf.zeros([784,10]))
b=tf.Variable(tf.zeros([10]))

#softmax regression算法公式
y=tf.nn.softmax(tf.matmul(x,W)+b)

#定义一个损失函数,多分类问题多用cross_entropy
y_=tf.placeholder(tf.float32,[None,10])
cross_entropy=tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))

#定义优化算法和训练速率,用梯度下降法和0.5的速率
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}))

准确率为:0.9156

参考:
《Tensorflow实战》

猜你喜欢

转载自blog.csdn.net/weixin_38285131/article/details/80790024