深度学习之识别图中模糊的手写数字

实例描述:
从MNIST数据集中选择一副图,这幅图上有一个手写的数字,让机器模拟人眼来区分这个手写的数字到底是几。
实现步骤:
(1)导入MNIST数据集;
(2)分析MNIST样本特点定义变量;
(3)构建模型;
(4)训练模型并输出中间状态参数;
(5)测试模型;
(6)保存模型;
(7)读取模型;
使用工具:
操作系统win7, Spyder(Anaconda3),MNIST数据集
实现过程:
(1)导入MNIST数据集;

import tensorflow as tf
import input_data   # 经过上一博客设置,此时可将导入写成这个样子
import pylab

mnist = input_data.read_data_sets("D:/Anaconda3Project/MNIST_data/", one_hot=True)
# 路径为自定义,可根据实际情况选择数据集存放路径
# one_hot=True,表示将样本标签转化为one_hot编码。例如:一共10类,0的one_hot为1000000000,1的one_hot为0100000000.......以此类推,只有一个位为1,1所在的位置就代表着第几类。

结果如下:
在这里插入图片描述
(2)分析图片的特点,定义变量;

print('输入数据:',mnist.train.images)   # 
print('训练数据集shape:',mnist.train.images.shape)   # 输出训练数据集里图片个数
im = mnist.train.images[1]   # 导出数据集中第一幅图片
im = im.reshape(-1,28)   # 将图片的shape变为计算机计算行数,自己定义列数为28列
pylab.imshow(im)
pylab.show()
print('测试数据集shape:',mnist.test.images.shape)   # 输出测试数据集里图片个数
print('验证数据集shape:',mnist.validation.images.shape)   # 输出验证数据集里图片个数


tf.reset_default_graph()   # 重置图
# 定义占位符
x = tf.placeholder(tf.float32, [None, 784])   # MNIST数据集的维度是28*28=784
y = tf.placeholder(tf.float32, [None, 10])   # 数字0~9,共10个类别

代码理解:
tf.reset_default_graph()
代码中定义的张量(tensor)、变量(Variable)、占位符(placeholder)、图中的节点操作(operation,OP)都是在一个叫做“图”的容器中完成的。一个TensorFlow程序默认是建立一个图的,所以重置图,可以保证程序不出现重定义报错。
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])
占位符可以理解为一种形参,它需要实际参数传入,传入的个数可以不定,在本代码中,由于输入图片是55000*784的矩阵,所以创建一个[None,784]的占位符x,None表示任一索引的图,784表示每一张图展平成784维的向量,None,10]的占位符y,意为任一索引的图,其类别为10类之一。
(3)构建模型;

# 定义学习参数
W = tf.Variable(tf.random_normal([784,10]))
b = tf.Variable(tf.zeros([10]))
# 定义输出节点
pred = tf.nn.softmax(tf.matmul(x, W) + b)
# 定义反向传播的结构
# 损失函数
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred),reduction_indices=1))
# 将生成的pred与样本y进行一次交叉熵的运算,然后取平均值
# 定义学习率参数
learning_rate = 0.01
# 使用梯度下降优化器
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
# 更新b和W,使cost变小,cost越小,b和W就是训练出来的合适值

代码理解:
pred = tf.nn.softmax(tf.matmul(x, W) + b)
tf.matmul(x, W)表示x乘以W,然后再加上b,把它们的和输入到tf.nn.softmax()函数里。softmax函数的数学表达式为:
在这里插入图片描述
其含义为将一组数据整理为一个概率分布。例如:一张图的原向量为[1,2,3],经过softmax变换后为:
在这里插入图片描述向量内部数据类型由整型变为浮点型,这样就成为一个概率分布,方便接下来计算交叉熵。
cost = tf.reduce_mean(-tf.reduce_sum(ytf.log(pred),reduction_indices=1))
y
tf.log(pred)为交叉熵计算,数学公式为:
在这里插入图片描述
其含义可通过代码举例,例如:y为[1,0,0,…],pred为[0.3,0.2,0.5,…],-tf.reduce_sum(y*tf.log(pred)结果为:
在这里插入图片描述
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
不懂,不能理解,大概意思是,通过梯度下降优化器让损失值(cost)变小,b和W不断向合适的方向调整,损失值(cost)越小则b和W就越准确。这部分原理TensorFlow已经实现好了,我们简单理解即可,应该把重点放在使用什么方法来计算误差,使用那些梯度下降的优化算法,如何调节梯度下降中的参数(如学习率)问题上。
(4)训练模型并输出中间状态参数;

training_epochs = 25   # 定义迭代次数
batch_size = 100   # 在训练过程中一次取100条数据进行训练
display_step = 1   # 每训练一次就把具体的中间状态显示出来

# 启动session
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())   # Initializing OP,含有tf.Variable时必须初始化变量
    
    # 启动循环开始训练
    for epoch in range(training_epochs):
        avg_cost = 0.   # 定义平均损失值
        total_batch = int(mnist.train.num_examples/batch_size)     # 计算训练数据可以划分多少个batch大小的组
        for i in range(total_batch):   # 每一组每一组地训练
            batch_xs,batch_ys = mnist.train.next_batch(batch_size)   # 每次返回100个训练集的数据
            # 运行优化器
            _, c = sess.run([optimizer, cost], feed_dict={x:batch_xs, y:batch_ys})   # 计算损失值,不断更正参数变量
            # 计算平均loss值
            avg_cost += c/total_batch
        # 显示训练中的详细信息
        if (epoch+1) % display_step == 0:
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))
    print("Finished!")

结果如下:
在这里插入图片描述
(5)测试模型;

correct_prediction = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))   # 计算预测类别索引与真实类别索引相等的数量
 # 计算准确类
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
print("Accuracy:",accuracy.eval({x:mnist.test.images,y:mnist.test.labels}))

代码理解:
correct_prediction = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
tf.argmax(array,axis),计算array中最大值的索引,axis=1代表按行查找(axis=0代表按列查找)。
tf.equal(A,B),计算两个矩阵或者向量的相等的元素,如果是相等的那就返回True,反正返回False,返回的值的矩阵维度和A是一样的。
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
tf.cast(x,dtype,name=None)将括号中的x转化为dtype。
tf.reduce_mean(),计算张量tensor沿着指定的数轴(tensor的某一维度)上的的平均值,如果不指定默认为计算所有元素的均值。
print(“Accuracy:”,accuracy.eval({x:mnist.test.images,y:mnist.test.labels}))
accuracy.eval({x:mnist.test.images,y:mnist.test.labels})相当于
sess.run(accuracy, {x:mnist.test.images,y_: mnist.test.labels}),eval()只能用于tf.Tensor类对象,也就是有输出的Operation。
结果如下:
在这里插入图片描述
(6)保存模型;
在session创建之前添加如下代码:

saver = tf.train.Saver()    # 生成saver
model_path = "D:/Anaconda3Project/MNIST模型/521model.ckpt"   # 定义模型保存路径

在测试模型后紧接下面代码:

save_path = saver.save(sess, model_path)
print("Model saved in file: %s" % save_path)

(7)读取模型;

with tf.Session() as sess:
    # 初始化变量
    sess.run(tf.global_variables_initializer())
    # 恢复模型变量
    saver.restore(sess, model_path)
    # 测试model
    correct_prediction = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
    # 计算准确类
    accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
    print("Accuracy:",accuracy.eval({x:mnist.test.images,y:mnist.test.labels}))
    
    output = tf.argmax(pred,1)   
    batch_xs, batch_ys = mnist.train.next_batch(2)   
    outputval,predv = sess.run([output,pred],feed_dict={x:batch_xs})
    print(outputval,predv,batch_ys)
    
    im = batch_xs[0]
    im = im.reshape(-1,28)
    pylab.imshow(im)
    pylab.show()
    
    im = batch_xs[1]
    im = im.reshape(-1,28)
    pylab.imshow(im)
    pylab.show()

代码理解:
output = tf.argmax(pred,1)
batch_xs, batch_ys = mnist.train.next_batch(2)
outputval,predv = sess.run([output,pred],feed_dict={x:batch_xs})
print(outputval,predv,batch_ys)
这几行代码看不明白含义(无奈),先给自己留个坑。。。此时运行结果如下:
在这里插入图片描述
最后,贴出完整代码,训练测试一气呵成,和上面的代码完全相同:

import tensorflow as tf
import input_data
import pylab

mnist = input_data.read_data_sets("D:/Anaconda3Project/MNIST_data/", one_hot=True)
# 路径为自定义,可根据实际情况选择数据集存放路径
# one_hot=True,表示将样本标签转化为one_hot编码。例如:一共10类,0的one_hot为1000000000,1的one_hot为0100000000.......以此类推,只有一个位为1,1所在的位置就代表着第几类。
'''
print('输入数据:',mnist.train.images)   # 
print('训练数据集shape:',mnist.train.images.shape)   # 输出训练数据集里图片个数
im = mnist.train.images[1]   # 导出数据集中第一幅图片
im = im.reshape(-1,28)   # 将图片的shape变为计算机计算行数,自己定义列数为28列
pylab.imshow(im)
pylab.show()
print('测试数据集shape:',mnist.test.images.shape)   # 输出测试数据集里图片个数
print('验证数据集shape:',mnist.validation.images.shape)   # 输出验证数据集里图片个数
'''

tf.reset_default_graph() # 重置图
# 定义占位符
x = tf.placeholder(tf.float32, [None, 784])   # MNIST数据集的维度是28*28=784
y = tf.placeholder(tf.float32, [None, 10])   # 数字0~9,共10个类别
# 定义学习参数
W = tf.Variable(tf.random_normal([784,10]))
b = tf.Variable(tf.zeros([10]))
# 定义输出节点
pred = tf.nn.softmax(tf.matmul(x, W) + b)
# 定义反向传播的结构
# 损失函数
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred),reduction_indices=1))
# 将生成的pred与样本y进行一次交叉熵的运算,然后取平均值
# 定义学习类参数
learning_rate = 0.01
# 使用梯度下降优化器
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
# 更新b和W,使cost变小,cost越小,b和W就是训练出来的合适值
training_epochs = 25   # 定义迭代次数
batch_size = 100   # 在训练过程中一次取100条数据进行训练
display_step = 1   # 每训练一次就把具体的中间状态显示出来

saver = tf.train.Saver()    # 生成saver
model_path = "D:/Anaconda3Project/MNIST模型/521model.ckpt"   # 定义模型保存路径

# 启动session
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())   # Initializing OP
    
    # 启动循环开始训练
    for epoch in range(training_epochs):
        avg_cost = 0.
        total_batch = int(mnist.train.num_examples/batch_size)     # 计算训练数据可以划分多少个batch大小的组
        for i in range(total_batch):   # 每一组每一组地训练
            batch_xs,batch_ys = mnist.train.next_batch(batch_size)   # 每次返回100个训练集的数据
            # 运行优化器
            _, c = sess.run([optimizer, cost], feed_dict={x:batch_xs, y:batch_ys})
            # 计算平均loss值
            avg_cost += c/total_batch
        # 显示训练中的详细信息
        if (epoch+1) % display_step == 0:
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))
    print("Finished!")
    correct_prediction = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))   # 计算预测类别索引与真实类别索引相等的数量
    # 计算准确类
    accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
    print("Accuracy:",accuracy.eval({x:mnist.test.images,y:mnist.test.labels}))
    # 保存模型
    save_path = saver.save(sess, model_path)
    print("Model saved in file: %s" % save_path)

with tf.Session() as sess:
    # 初始化变量
    sess.run(tf.global_variables_initializer())
    # 恢复模型变量
    saver.restore(sess, model_path)
    # 测试model
    correct_prediction = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
    # 计算准确类
    accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
    print("Accuracy:",accuracy.eval({x:mnist.test.images,y:mnist.test.labels}))
    
    output = tf.argmax(pred,1)   
    batch_xs, batch_ys = mnist.train.next_batch(2)   
    outputval,predv = sess.run([output,pred],feed_dict={x:batch_xs})
    print(outputval,predv,batch_ys)
    
    im = batch_xs[0]
    im = im.reshape(-1,28)
    pylab.imshow(im)
    pylab.show()
    
    im = batch_xs[1]
    im = im.reshape(-1,28)
    pylab.imshow(im)
    pylab.show()

后来许多人问我一个人夜晚踟蹰路上的心情,我想起的却不是孤单和路长,二是波澜壮阔的海和天空中闪耀的星光。
愿自己在深度学习的领域里坚持走下去!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值