TensorFlow - 基于 CNN 数字识别-云服务器玩法在线实验

[复制链接]
查看: 423|回复: 0

3

主题

3

帖子

21

积分

新手上路

Rank: 1

积分
21
发表于 2020-12-28 11:15:12 | 显示全部楼层 |阅读模式

实验内容

TensorFlow是由Google开发的用于数值计算的开源软件库,本教程采用简单的卷积神经网络模型,模型为: 输入 - 第一层卷积 - 第一层池化 - 第二层卷积 - 第二层池化 - 第一层全连接 - 第二层全连接。

免费在线实验地址:点击进入

实验资源:云服务器,没有云服务器的朋友推荐1折抢购:69元/年的阿里云服务器或者88元/年的腾讯云服务器

软件环境Ubuntu 14.04 64 位


TensorFlow 实现基于 CNN 数字识别的代码

前期准备
TensorFlow 相关 API 可以到在实验TensorFlow - 相关 API中学习。
训练数据下载:

  1. wget https://devlab-1251520893.cos.ap-guangzhou.myqcloud.com/t10k-images-idx3-ubyte.gz
  2. wget https://devlab-1251520893.cos.ap-guangzhou.myqcloud.com/t10k-labels-idx1-ubyte.gz
  3. wget https://devlab-1251520893.cos.ap-guangzhou.myqcloud.com/train-images-idx3-ubyte.gz
  4. wget https://devlab-1251520893.cos.ap-guangzhou.myqcloud.com/train-labels-idx1-ubyte.gz
复制代码
CNN 模型构建示例代码:
现在您可以在 /home/ubuntu 目录下创建源文件 mnist_model.py,内容可参考:
示例代码:/home/ubuntu/mnist_model.py
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*

  3. from __future__ import absolute_import
  4. from __future__ import division
  5. from __future__ import print_function

  6. import argparse
  7. import sys
  8. import tempfile

  9. from tensorflow.examples.tutorials.mnist import input_data

  10. import tensorflow as tf

  11. FLAGS = None


  12. def deepnn(x):

  13.   with tf.name_scope('reshape'):
  14.     x_image = tf.reshape(x, [-1, 28, 28, 1])

  15.   #第一层卷积层,卷积核为5*5,生成32个feature maps.
  16.   with tf.name_scope('conv1'):
  17.     W_conv1 = weight_variable([5, 5, 1, 32])
  18.     b_conv1 = bias_variable([32])
  19.     h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) #激活函数采用relu

  20.   # 第一层池化层,下采样2.
  21.   with tf.name_scope('pool1'):
  22.     h_pool1 = max_pool_2x2(h_conv1)

  23.   # 第二层卷积层,卷积核为5*5,生成64个feature maps
  24.   with tf.name_scope('conv2'):
  25.     W_conv2 = weight_variable([5, 5, 32, 64])
  26.     b_conv2 = bias_variable([64])
  27.     h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)#激活函数采用relu

  28.   # 第二层池化层,下采样2.
  29.   with tf.name_scope('pool2'):
  30.     h_pool2 = max_pool_2x2(h_conv2)

  31.   #第一层全连接层,将7x7x64个feature maps与1024个features全连接
  32.   with tf.name_scope('fc1'):
  33.     W_fc1 = weight_variable([7 * 7 * 64, 1024])
  34.     b_fc1 = bias_variable([1024])

  35.     h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
  36.     h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

  37.   #dropout层,训练时候随机让某些隐含层节点权重不工作
  38.   with tf.name_scope('dropout'):
  39.     keep_prob = tf.placeholder(tf.float32)
  40.     h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

  41.   # 第二层全连接层,1024个features和10个features全连接
  42.   with tf.name_scope('fc2'):
  43.     W_fc2 = weight_variable([1024, 10])
  44.     b_fc2 = bias_variable([10])

  45.     y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
  46.   return y_conv, keep_prob

  47. #卷积
  48. def conv2d(x, W):
  49.   return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

  50. #池化
  51. def max_pool_2x2(x):
  52.   return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
  53.                         strides=[1, 2, 2, 1], padding='SAME')
  54. #权重
  55. def weight_variable(shape):
  56.   initial = tf.truncated_normal(shape, stddev=0.1)
  57.   return tf.Variable(initial)

  58. #偏置
  59. def bias_variable(shape):
  60.   initial = tf.constant(0.1, shape=shape)
  61.   return tf.Variable(initial)
复制代码
训练 CNN 模型示例代码:
现在您可以在 /home/ubuntu 目录下创建源文件 train_mnist_model.py,内容可参考:
示例代码:/home/ubuntu/train_mnist_model.py
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*

  3. from __future__ import absolute_import
  4. from __future__ import division
  5. from __future__ import print_function

  6. import argparse
  7. import sys
  8. import tempfile

  9. from tensorflow.examples.tutorials.mnist import input_data

  10. import tensorflow as tf

  11. import mnist_model

  12. FLAGS = None


  13. def main(_):
  14.   mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

  15.   #输入变量,mnist图片大小为28*28
  16.   x = tf.placeholder(tf.float32, [None, 784])

  17.   #输出变量,数字是1-10
  18.   y_ = tf.placeholder(tf.float32, [None, 10])

  19.   # 构建网络,输入—>第一层卷积—>第一层池化—>第二层卷积—>第二层池化—>第一层全连接—>第二层全连接
  20.   y_conv, keep_prob = mnist_model.deepnn(x)

  21.   #第一步对网络最后一层的输出做一个softmax,第二步将softmax输出和实际样本做一个交叉熵
  22.   #cross_entropy返回的是向量
  23.   with tf.name_scope('loss'):
  24.     cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_,
  25.                                                             logits=y_conv)

  26.   #求cross_entropy向量的平均值得到交叉熵
  27.   cross_entropy = tf.reduce_mean(cross_entropy)

  28.   #AdamOptimizer是Adam优化算法:一个寻找全局最优点的优化算法,引入二次方梯度校验
  29.   with tf.name_scope('adam_optimizer'):
  30.     train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

  31.   #在测试集上的精确度
  32.   with tf.name_scope('accuracy'):
  33.     correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
  34.     correct_prediction = tf.cast(correct_prediction, tf.float32)
  35.   accuracy = tf.reduce_mean(correct_prediction)

  36.   #将神经网络图模型保存本地,可以通过浏览器查看可视化网络结构
  37.   graph_location = tempfile.mkdtemp()
  38.   print('Saving graph to: %s' % graph_location)
  39.   train_writer = tf.summary.FileWriter(graph_location)
  40.   train_writer.add_graph(tf.get_default_graph())

  41.   #将训练的网络保存下来
  42.   saver = tf.train.Saver()
  43.   with tf.Session() as sess:
  44.     sess.run(tf.global_variables_initializer())
  45.     for i in range(5000):
  46.       batch = mnist.train.next_batch(50)
  47.       if i % 100 == 0:
  48.         train_accuracy = accuracy.eval(feed_dict={
  49.             x: batch[0], y_: batch[1], keep_prob: 1.0})#输入是字典,表示tensorflow被feed的值
  50.         print('step %d, training accuracy %g' % (i, train_accuracy))
  51.       train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

  52.     test_accuracy = 0
  53.     for i in range(200):
  54.       batch = mnist.test.next_batch(50)
  55.       test_accuracy += accuracy.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0}) / 200;

  56.     print('test accuracy %g' % test_accuracy)

  57.     save_path = saver.save(sess,"mnist_cnn_model.ckpt")

  58. if __name__ == '__main__':
  59.   parser = argparse.ArgumentParser()
  60.   parser.add_argument('--data_dir', type=str,
  61.                       default='./',
  62.                       help='Directory for storing input data')
  63.   FLAGS, unparsed = parser.parse_known_args()
  64.   tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
复制代码
然后执行:
  1. cd /home/ubuntu;
  2. python train_mnist_model.py
复制代码
训练的时间会较长,可以喝杯茶耐心等待。
执行结果:
  1. step 3600, training accuracy 0.98
  2. step 3700, training accuracy 0.98
  3. step 3800, training accuracy 0.96
  4. step 3900, training accuracy 1
  5. step 4000, training accuracy 0.98
  6. step 4100, training accuracy 0.96
  7. step 4200, training accuracy 1
  8. step 4300, training accuracy 1
  9. step 4400, training accuracy 0.98
  10. step 4500, training accuracy 0.98
  11. step 4600, training accuracy 0.98
  12. step 4700, training accuracy 1
  13. step 4800, training accuracy 0.98
  14. step 4900, training accuracy 1
  15. test accuracy 0.9862
复制代码
测试 CNN 模型下载测试图片
下载 test_num.zip
  1. cd /home/ubuntu
  2. wget https://devlab-1251520893.cos.ap-guangzhou.myqcloud.com/test_num.zip
复制代码
解压测试图片包
解压 test_num.zip,其中 1-9.png 为 1-9 数字图片。
  1. unzip test_num.zip
复制代码
实现 predict 代码
现在您可以在 /home/ubuntu 目录下创建源文件 predict_mnist_model.py,内容可参考:
示例代码:/home/ubuntu/predict_mnist_model.py
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*

  3. from __future__ import absolute_import
  4. from __future__ import division
  5. from __future__ import print_function

  6. import argparse
  7. import sys
  8. import tempfile

  9. from tensorflow.examples.tutorials.mnist import input_data

  10. import tensorflow as tf

  11. import mnist_model
  12. from PIL import Image, ImageFilter

  13. def load_data(argv):

  14.     grayimage = Image.open(argv).convert('L')
  15.     width = float(grayimage.size[0])
  16.     height = float(grayimage.size[1])
  17.     newImage = Image.new('L', (28, 28), (255))

  18.     if width > height:
  19.         nheight = int(round((20.0/width*height),0))
  20.         if (nheigth == 0):
  21.             nheigth = 1
  22.         img = grayimage.resize((20,nheight), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
  23.         wtop = int(round(((28 - nheight)/2),0))
  24.         newImage.paste(img, (4, wtop))
  25.     else:
  26.         nwidth = int(round((20.0/height*width),0))
  27.         if (nwidth == 0):
  28.             nwidth = 1
  29.         img = grayimage.resize((nwidth,20), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
  30.         wleft = int(round(((28 - nwidth)/2),0))
  31.         newImage.paste(img, (wleft, 4))

  32.     tv = list(newImage.getdata())
  33.     tva = [ (255-x)*1.0/255.0 for x in tv]
  34.     return tva

  35. def main(argv):

  36.     imvalue = load_data(argv)

  37.     x = tf.placeholder(tf.float32, [None, 784])
  38.     y_ = tf.placeholder(tf.float32, [None, 10])
  39.     y_conv, keep_prob = mnist_model.deepnn(x)

  40.     y_predict = tf.nn.softmax(y_conv)
  41.     init_op = tf.global_variables_initializer()
  42.     saver = tf.train.Saver()
  43.     with tf.Session() as sess:
  44.         sess.run(init_op)
  45.         saver.restore(sess, "mnist_cnn_model.ckpt")
  46.         prediction=tf.argmax(y_predict,1)
  47.         predint = prediction.eval(feed_dict={x: [imvalue],keep_prob: 1.0}, session=sess)
  48.         print (predint[0])

  49. if __name__ == "__main__":
  50.     main(sys.argv[1])
复制代码
然后执行:

  1. cd /home/ubuntu;
  2. python predict_mnist_model.py 1.png
复制代码
执行结果:
  1. 1
复制代码
你可以修改 1.png 为 1-9.png 中任意一个
完成
腾讯云
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

精彩图文



在线客服(工作时间:9:00-22:00)
400-600-6565

内容导航

微信客服

Copyright   ©2015-2019  云服务器社区  Powered by©Discuz!  技术支持:尊托网络     ( 湘ICP备15009499号-1 )