1 Lenet5模型简介

截屏2020-12-21 下午8.37.03.png

2 TensorFlow实现

mnist_lenet5_forward.py文件

  1. import tensorflow as tf
  2. # 每张图片分辨率为28*28
  3. IMAGE_SIZE = 28
  4. # Mnist数据集为灰度图,故输入图片通道数NUM_CHANNELS取值为1
  5. NUM_CHANNELS = 1
  6. # 第一层卷积核大小为5
  7. CONV1_SIZE = 5
  8. # 卷积核个数为32
  9. CONV1_KERNEL_NUM = 32
  10. # 第二层卷积核大小为5
  11. CONV2_SIZE = 5
  12. # 卷积核个数为64
  13. CONV2_KERNEL_NUM = 64
  14. # 全连接层第一层为 512 个神经元
  15. FC_SIZE = 512
  16. # 全连接层第二层为 10 个神经元
  17. OUTPUT_NODE = 10
  18. # 权重w计算
  19. def get_weight(shape, regularizer):
  20. w = tf.Variable(tf.truncated_normal(shape, stddev=0.1))
  21. if regularizer != None: tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(regularizer)(w))
  22. return w
  23. # 偏置b计算
  24. def get_bias(shape):
  25. b = tf.Variable(tf.zeros(shape))
  26. return b
  27. # 卷积层计算
  28. def conv2d(x, w):
  29. return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')
  30. # 最大池化层计算
  31. def max_pool_2x2(x):
  32. return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
  33. def forward(x, train, regularizer):
  34. # 实现第一层卷积
  35. conv1_w = get_weight([CONV1_SIZE, CONV1_SIZE, NUM_CHANNELS, CONV1_KERNEL_NUM], regularizer)
  36. conv1_b = get_bias([CONV1_KERNEL_NUM])
  37. conv1 = conv2d(x, conv1_w)
  38. # 非线性激活
  39. relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1_b))
  40. # 最大池化
  41. pool1 = max_pool_2x2(relu1)
  42. # 实现第二层卷积
  43. conv2_w = get_weight([CONV2_SIZE, CONV2_SIZE, CONV1_KERNEL_NUM, CONV2_KERNEL_NUM], regularizer)
  44. conv2_b = get_bias([CONV2_KERNEL_NUM])
  45. conv2 = conv2d(pool1, conv2_w)
  46. relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_b))
  47. pool2 = max_pool_2x2(relu2)
  48. # 获取一个张量的维度
  49. pool_shape = pool2.get_shape().as_list()
  50. # pool_shape[1] 为长 pool_shape[2] 为宽 pool_shape[3]为高
  51. nodes = pool_shape[1] * pool_shape[2] * pool_shape[3]
  52. # 得到矩阵被拉长后的长度,pool_shape[0]为batch值
  53. reshaped = tf.reshape(pool2, [pool_shape[0], nodes])
  54. # 实现第三层全连接层
  55. fc1_w = get_weight([nodes, FC_SIZE], regularizer)
  56. fc1_b = get_bias([FC_SIZE])
  57. fc1 = tf.nn.relu(tf.matmul(reshaped, fc1_w) + fc1_b)
  58. # 如果是训练阶段,则对该层输出使用dropout
  59. if train: fc1 = tf.nn.dropout(fc1, 0.5)
  60. # 实现第四层全连接层
  61. fc2_w = get_weight([FC_SIZE, OUTPUT_NODE], regularizer)
  62. fc2_b = get_bias([OUTPUT_NODE])
  63. y = tf.matmul(fc1, fc2_w) + fc2_b
  64. return y

mnist_lenet5_backward.py文件

  1. import tensorflow as tf
  2. from tensorflow.examples.tutorials.mnist import input_data
  3. import mnist_lenet5_forward
  4. import os
  5. import numpy as np
  6. # batch的数量
  7. BATCH_SIZE = 100
  8. # 初始学习率
  9. LEARNING_RATE_BASE = 0.005
  10. # 学习率衰减率
  11. LEARNING_RATE_DECAY = 0.99
  12. # 正则化
  13. REGULARIZER = 0.0001
  14. # 最大迭代次数
  15. STEPS = 50000
  16. # 滑动平均衰减率
  17. MOVING_AVERAGE_DECAY = 0.99
  18. # 模型保存路径
  19. MODEL_SAVE_PATH = "./model/"
  20. # 模型名称
  21. MODEL_NAME = "mnist_model"
  22. def backward(mnist):
  23. # 卷积层输入为四阶张量
  24. # 第一阶表示每轮喂入的图片数量,第二阶和第三阶分别表示图片的行分辨率和列分辨率,第四阶表示通道数
  25. x = tf.placeholder(tf.float32, [
  26. BATCH_SIZE,
  27. mnist_lenet5_forward.IMAGE_SIZE,
  28. mnist_lenet5_forward.IMAGE_SIZE,
  29. mnist_lenet5_forward.NUM_CHANNELS])
  30. y_ = tf.placeholder(tf.float32, [None, mnist_lenet5_forward.OUTPUT_NODE])
  31. # 前向传播过程
  32. y = mnist_lenet5_forward.forward(x, True, REGULARIZER)
  33. # 声明一个全局计数器
  34. global_step = tf.Variable(0, trainable=False)
  35. # 对网络最后一层的输出y做softmax,求取输出属于某一类的概率
  36. ce = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.argmax(y_, 1))
  37. # 向量求均值
  38. cem = tf.reduce_mean(ce)
  39. # 正则化的损失值
  40. loss = cem + tf.add_n(tf.get_collection('losses'))
  41. # 指数衰减学习率
  42. learning_rate = tf.train.exponential_decay(
  43. LEARNING_RATE_BASE,
  44. global_step,
  45. mnist.train.num_examples / BATCH_SIZE,
  46. LEARNING_RATE_DECAY,
  47. staircase=True)
  48. # 梯度下降算法的优化器
  49. # train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
  50. train_step = tf.train.MomentumOptimizer(learning_rate, 0.9).minimize(loss, global_step=global_step)
  51. # 采用滑动平均的方法更新参数
  52. ema = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
  53. ema_op = ema.apply(tf.trainable_variables())
  54. # 将train_step和ema_op两个训练操作绑定到train_op上
  55. with tf.control_dependencies([train_step, ema_op]):
  56. train_op = tf.no_op(name='train')
  57. # 实例化一个保存和恢复变量的saver
  58. saver = tf.train.Saver()
  59. # 创建一个会话
  60. with tf.Session() as sess:
  61. init_op = tf.global_variables_initializer()
  62. sess.run(init_op)
  63. # 通过 checkpoint 文件定位到最新保存的模型,若文件存在,则加载最新的模型
  64. ckpt = tf.train.get_checkpoint_state(MODEL_SAVE_PATH)
  65. if ckpt and ckpt.model_checkpoint_path:
  66. saver.restore(sess, ckpt.model_checkpoint_path)
  67. for i in range(STEPS):
  68. # 读取一个batch数据,将输入数据xs转成与网络输入相同形状的矩阵
  69. xs, ys = mnist.train.next_batch(BATCH_SIZE)
  70. reshaped_xs = np.reshape(xs, (
  71. BATCH_SIZE,
  72. mnist_lenet5_forward.IMAGE_SIZE,
  73. mnist_lenet5_forward.IMAGE_SIZE,
  74. mnist_lenet5_forward.NUM_CHANNELS))
  75. # 读取一个batch数据,将输入数据xs转成与网络输入相同形状的矩阵
  76. _, loss_value, step = sess.run([train_op, loss, global_step], feed_dict={x: reshaped_xs, y_: ys})
  77. if i % 100 == 0:
  78. print("After %d training step(s), loss on training batch is %g." % (step, loss_value))
  79. saver.save(sess, os.path.join(MODEL_SAVE_PATH, MODEL_NAME), global_step=global_step)
  80. def main():
  81. mnist = input_data.read_data_sets("./data/", one_hot=True)
  82. backward(mnist)
  83. if __name__ == '__main__':
  84. main()

mnist_lenet5_test.py文件

  1. import time
  2. import tensorflow as tf
  3. from tensorflow.examples.tutorials.mnist import input_data
  4. import mnist_lenet5_forward
  5. import mnist_lenet5_backward
  6. import numpy as np
  7. TEST_INTERVAL_SECS = 5
  8. #创建一个默认图,在该图中执行以下操作
  9. def test(mnist):
  10. with tf.Graph().as_default() as g:
  11. x = tf.placeholder(tf.float32,[
  12. mnist.test.num_examples,
  13. mnist_lenet5_forward.IMAGE_SIZE,
  14. mnist_lenet5_forward.IMAGE_SIZE,
  15. mnist_lenet5_forward.NUM_CHANNELS])
  16. y_ = tf.placeholder(tf.float32, [None, mnist_lenet5_forward.OUTPUT_NODE])
  17. #训练好的网络,故不使用 dropout
  18. y = mnist_lenet5_forward.forward(x,False,None)
  19. ema = tf.train.ExponentialMovingAverage(mnist_lenet5_backward.MOVING_AVERAGE_DECAY)
  20. ema_restore = ema.variables_to_restore()
  21. saver = tf.train.Saver(ema_restore)
  22. #判断预测值和实际值是否相同
  23. correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
  24. ## 求平均得到准确率
  25. accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  26. while True:
  27. with tf.Session() as sess:
  28. ckpt = tf.train.get_checkpoint_state(mnist_lenet5_backward.MODEL_SAVE_PATH)
  29. if ckpt and ckpt.model_checkpoint_path:
  30. saver.restore(sess, ckpt.model_checkpoint_path)
  31. # 根据读入的模型名字切分出该模型是属于迭代了多少次保存的
  32. global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
  33. reshaped_x = np.reshape(mnist.test.images,(
  34. mnist.test.num_examples,
  35. mnist_lenet5_forward.IMAGE_SIZE,
  36. mnist_lenet5_forward.IMAGE_SIZE,
  37. mnist_lenet5_forward.NUM_CHANNELS))
  38. #利用多线程提高图片和标签的批获取效率
  39. coord = tf.train.Coordinator()#3
  40. threads = tf.train.start_queue_runners(sess=sess, coord=coord)#4
  41. accuracy_score = sess.run(accuracy, feed_dict={x:reshaped_x,y_:mnist.test.labels})
  42. print("After %s training step(s), test accuracy = %g" % (global_step, accuracy_score))
  43. #关闭线程协调器
  44. coord.request_stop()#6
  45. coord.join(threads)#7
  46. else:
  47. print('No checkpoint file found')
  48. return
  49. time.sleep(TEST_INTERVAL_SECS)
  50. def main():
  51. mnist = input_data.read_data_sets("./data/", one_hot=True)
  52. test(mnist)
  53. if __name__ == '__main__':
  54. main()