tensorflow实战入门题目--手写数字的识别

版权声明:未经过本人同意不得转发 https://blog.csdn.net/weixin_42956785/article/details/83930158

tensorflow实战入门题目–手写数字的识别

这是我的第一篇博客,有很多写不好的地方,还请大家多多批评指正。

手写体的示范:

手写体的示范

导入数据,由于mnist手写数字在

from tensorflow.examples.tutorials.mnist import input_data   #载入Mnist,由于比较出名,所以在tensorflow里面已有这个数据集
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)  #验证集的形状、维度

计算图:
在这里插入图片描述

引入tensorflow框架,并创建一个会话

imp1ort tensorflow as tf   #引入tensorflow的框架
sess = tf.InteractiveSession()#创建一个会话

输入x的数据,给权值w和basic赋初始值(此处赋初始值为零)

x = tf.placeholder(tf.float32,[None,784])#x的输入数据,定义类型为float32,None表示输入的行数不确定,占位符
w = tf.Variable(tf.zeros([784,10]))  #初始化权值w的值  784*10的全为0的向量
b = tf.Variable(tf.zeros([10]))  #初始化bias的值

在这里插入图片描述
在这里插入图片描述

使用Softmax Regression函数

y = tf.nn.softmax(tf.matmul(x,w) + b) #用softmax Regression 输出这张照片对应数字的百分比,维度(None,10),且百分比的和为一
# Softmax Regression经常用于分类问题的解决

输入训练集数据的真正的测试结果

y_ = tf.placeholder("float",[None,10])  #输入训练集真实的结果(q代表的数字)

使用coress_entropy定义损失函数

y_ = tf.placeholder("float",[None,10])  #输入训练集真实的数字
#计算交叉熵,定义损失函数 tf.reduce_mean对于每个测试数据求均值,tf.reduce_sum进行求和
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),reduction_indices=[1]))

优化算法–此处选择随机梯度下降的算法SGD

#优化算法,这里采用梯度下降,反向传播,学习率为0.5,优化目标为cross_entropy
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)  

迭代训练

tf.global_variables_initializer().run()   #初始化全局所有的参数#迭代训练,每次随机选择100个训练数据
for i in range(1000):
    batch_xs,batch_ys = mnist.train.next_batch(100)#随机抽取100组数据    
    train_step.run({x:batch_xs,y_:batch_ys })  #此处进行封装

计算准确率

correct_predicition = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))  #输出结果为bool型·
accuracy = tf.reduce_mean(tf.cast(correct_predicition,tf.float32))   #将bool型转换为float32,并求平均数
print(accuracy.eval({x:mnist.test.images,y_:mnist.test.labels}))    #计算准确率,eval执行整个Session()

tensorflow,我们定义的各个公式其实是Computation Graph,在执行这行代码的时候,计算还没有实际发生,只有等调用run的方法,并feed数据的时计算才真正的执行。比如cross、entropy、train、step、accuracy等都是计算图(tensorflow会自动建立)中的节点,而不是数据结果,我可以通过run方法执行这些节点或者说运算操作来获取结果。

猜你喜欢

转载自blog.csdn.net/weixin_42956785/article/details/83930158