tensorflow之helloworld

本文介绍了使用TensorFlow实现MNIST手写数字识别的过程,包括数据加载、Softmax Regression模型、损失函数和优化算法。通过解决deprecation警告,调整数据集导入方式,并展示模型训练与验证的步骤,最终得出准确率。

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

mnist手写字体识别

注:官方源代码在www.broadview.com.cn,我现阶段的学习方式是复现效果,过程中解决问题加深理解,经典代码段进行反复直到熟记。

tensorflow实现softmax regression识别手写数字

一边看tf实战书,一边跑3_2_helloworld代码。
遇到问题:read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and wil be removed in a future version.
解决方法:use alternatives such as official/mnist/dataset.py from tensorflow/models.
也就是将from tensorflow.examples.tutorials.mnist import input_data
改为from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets,去掉mnist = input_data.read_data_sets("./MNIST_data/",False,one_hot = True)前面的input_data
如下图
在这里插入图片描述
接着查看数据集训练集、测试集和验证集样本和标签的维数
在这里插入图片描述
结果如下:
在这里插入图片描述
我们的图像的像素是2828= 784.也就是将2828个像素点展开成1维的结果,为的是简化模型。
以训练集样本(55000,784)和标签(55000,10)为例进行解释:
我们训练数据的特征是一个55000*784的tensor,第一个维度是图片的编号,也就是有55000张手写数字的图片;第二维是图片中像素点的编号,如784表示每个像素的值,10表示10个类别。

接下来首先载入Tensorflow库,并建立一个新的InteractiveSession(这个命令会将这个session注册为默认的session,之后的运算也默认跑到这个session,不同的session之间的数据和运算应该是相互独立的),接下来创建一个Placeholder(输入数据的地方,其中第一个参数为数据类型,第二个参数[None ,784 ]代表tensor的shape,也就是数据的尺寸,None代表不限条件输入,784代表每个输入是一个784维的向量)

import tensorflow as tf
sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32,[None,784])

接下来要给softmax regression模型中的weight和biases创建variable对象,这些对象要在迭代过程中是持久化的,它要可以长期存在并在每一轮迭代中被更新,简单例子我们初始化全都为0,这里w的shape是[784,10],784是特征的维数,10代表有10类,

w = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))

实现y = softmax(Wx +b)

y = tf.nnsoftmax(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]))

其中在这里插入图片描述
接下来只要在定义一个优化算法就可以开始训练,我们使用SGD,定义和优化算法以后,Tensorflow就可以根据我们的定义的计算图进行自动求导,并根据反向传播(back propagation)算法进行训练,在每一轮迭代时候更新参数来减少loss。在后台tensorflow会自动添加许多的运算操作(operation)来实现刚才提到的反向传播和梯度下降。
在这里插入图片描述

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

下一步就是全局初始化

tf.global_variable_initializer().run()

最后一步我们开始训练操作train_step

for i in range(1000):
	batch_xs,batch_ys = mnist.train.next_batch(100)
	train_setp.run({x:batch_xs,y_:batch_ys})

提醒一下这里x的维度为[None,784],y_的维度为[None,10]
(标签),这里的意思是拿1000组batch,每个mini-batch是100张图片,预测它的对应标签。
完成训练以后,我们对模型进行验证,下面代码中tf.argmax是从一个tensor中寻找最大值序号,tf.argmax(y,1)就是求各个预测数字中概率最大的那个,而tf.argmax是找样本的真实数字类别

correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

注:tf.cast()将之前correct_prediction输出的bool值转换为float32.
最后运行整个过程计算出准确率

print(accuracy.eval(x:mnist.test.images,y_:mnist.test.labels))

在这里插入图片描述
运行结果
在这里插入图片描述
结束。。。。
接下来我就去熟记啦。

代码汇总

from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
mnist = read_data_sets("./MNIST_data/",False,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]))
#[None,10]
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}))

参考:https://blog.youkuaiyun.com/qq_34562093/article/details/80611611
https://www.cnblogs.com/always-fight/p/10370412.html
https://www.cnblogs.com/smallredness/p/11203250.html
https://blog.youkuaiyun.com/zxyhhjs2017/article/details/82349535

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值