TensorFlow实战1
TensorFlow实现手写数字识别
前言
本人正在学习TensorFlow的使用,使用的书籍是《TensorFlow实战》-黄文坚。
这是简单的对TensorFlow实战的了解:TensorFlow用softmax regression识别手写数字。
说明:我的TensorFlow环境已经搭建好了,最基础的CPU、windows7,没有GPU模块。还没安装好环境的小伙伴请先去搜索安装方法。
《TensorFlow实战》下载链接:https://pan.baidu.com/s/1jsA5YmEo212d9lkfQ2Bc5A
提取码:esjm
MNIST数据集
本次实战需要用到MNIST数据集,数据集有两种获取方法:一种是去官网下载,另一种是直接代码下载。根据本人的使用情况,我觉得去官网下载好再用是最好的,因为代码运行的时候不需要太长的时间去加载数据。
MNIST数据集的下载如下:
手动下载:http://yann.lecun.com/exdb/mnist四个压缩包
train-images-idx3-ubyte.gz: training set images (9912422 bytes)
train-labels-idx1-ubyte.gz: training set labels (28881 bytes)
t10k-images-idx3-ubyte.gz: test set images (1648877 bytes)
t10k-labels-idx1-ubyte.gz: test set labels (4542 bytes)
下载后也要解压,保存在文件夹中,文件的保存位置没有要求,加载的时候使用绝对路径就可以了。
学习心得
通过这次实战我觉得TensorFlow的大致流程可以分为以下几个部分:
1、数据集的输入
2、选用模型
3、选择合适的损失函数
4、训练模型
5、验证模型的准确率
本人第一次用TensorFlow,从啥都不懂到对TensorFlow有了一个大概印象,不得不说《TensorFlow实战》这本书是非常好用的,小白的我完全能接受,我也推荐大家使用这本书来一起学习。
全代码如下
#先下载MNIST数据保存到文件夹
#手动下载:http://yann.lecun.com/exdb/mnist四个压塑包
#
#train-images-idx3-ubyte.gz: training set images (9912422 bytes)
#train-labels-idx1-ubyte.gz: training set labels (28881 bytes)
#t10k-images-idx3-ubyte.gz: test set images (1648877 bytes)
#t10k-labels-idx1-ubyte.gz: test set labels (4542 bytes)
#加载MNIST数据,先下载MNIST数据保存到文件夹里,我的保存在了'H:\MNISTdata'
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets(r'H:\MNISTdata',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 #载入TensorFlow库
sess = tf.InteractiveSession() #创建一个InteractiveSession为session,之后的运算也在session里进行
x = tf.placeholder(tf.float32,[None,784]) #创建一个输入数据的地方(数据类型,【不限制条数的输入,784维的向量】)
#给softmax regression模型中的weights和biases创建Variable对象
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
#实现Softmax Regression算法:y=softmax(Wx+b)
y = tf.nn.softmax(tf.matmul(x,W)+b)
#在TensorFlow里定义损失函数:cross-entropy(信息熵)
y_ = tf.placeholder(tf.float32,[None,10]) #输入是真实的lable,用来计算cross-entropy
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),reduction_indices=[1]))
#直接调用tf.train.GradientDescentOptimizer,并设置学习速率为0.5,优化目标为cross-entropy;并修改函数名为train_stap
train_stap = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
#TensorFlow的全局参数初始化器tf.global_variables_initializer,并直接执行run方法
tf.global_variables_initializer().run()
#执行训练操作,从训练集中抽取100条样本构成一个mini-batch
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
train_stap.run({x:batch_xs, y_:batch_ys})
#验证模型的准确率
correct_prediction = tf.equal(tf.arg_max(y, 1), tf.arg_max(y_, 1))
#统计全部样本的accuracy
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#打印准确度
print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels}))
下一篇:链接: TensorFlow实战2.