您当前的位置: 首页 > 

静静喜欢大白

暂无认证

  • 1浏览

    0关注

    521博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【ResNet实现Mnist】

静静喜欢大白 发布时间:2020-07-21 11:23:24 ,浏览量:1

下午看到一篇介绍用tensorflow实现残差网络的博文,原文在此:https://blog.csdn.net/qq_29462849/article/details/80744522#commentsedit

运行了代码,精度很低,仔细查看了代码,量比较大,由于刚看了吴恩达老师的相关课程,对这一块印象比较深,发现了一个问题,在残差模块的最后一个卷积层,也就是输出卷积层,该博主将输出和快捷连接的值相加后又加了一个偏置值,这一点在吴老师的数学推导中并没有提到,因为快捷链接是插到了最后一个卷积层的线性操作和非线性操作之间,那么直接对二者的和做ReLU就可以了,加偏置是没有必要的,经过这一点的改良后,精度大幅度提高,原来训练3000次精度为11.35%,而现在则提高到了95.19%,来看代码:


 
  1. #tensorflow基于mnist数据集上的VGG11网络,可以直接运行
  2. from tensorflow.examples.tutorials.mnist import input_data
  3. import tensorflow as tf
  4. import os
  5. #tensorflow基于mnist实现VGG11
  6. mnist = input_data.read_data_sets( 'MNIST_data', one_hot= True)
  7. #x=mnist.train.images
  8. #y=mnist.train.labels
  9. #X=mnist.test.images
  10. #Y=mnist.test.labels
  11. x = tf.placeholder(tf.float32, [ None, 784])
  12. y = tf.placeholder(tf.float32, [ None, 10])
  13. sess = tf.InteractiveSession()
  14. def weight_variable(shape):
  15. #这里是构建初始变量
  16. initial = tf.truncated_normal(shape, mean= 0,stddev= 0.1)
  17. #创建变量
  18. return tf.Variable(initial)
  19. def bias_variable(shape):
  20. initial = tf.constant( 0.1, shape=shape)
  21. return tf.Variable(initial)
  22. #在这里定义残差网络的id_block块,此时输入和输出维度相同
  23. def identity_block(X_input, kernel_size, in_filter, out_filters, stage, block):
  24. """
  25. Implementation of the identity block as defined in Figure 3
  26. Arguments:
  27. X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
  28. kernel_size -- integer, specifying the shape of the middle CONV's window for the main path
  29. filters -- python list of integers, defining the number of filters in the CONV layers of the main path
  30. stage -- integer, used to name the layers, depending on their position in the network
  31. block -- string/character, used to name the layers, depending on their position in the network
  32. training -- train or test
  33. Returns:
  34. X -- output of the identity block, tensor of shape (n_H, n_W, n_C)
  35. """
  36. # defining name basis
  37. block_name = 'res' + str(stage) + block
  38. f1, f2, f3 = out_filters
  39. with tf.variable_scope(block_name):
  40. X_shortcut = X_input
  41. #first
  42. W_conv1 = weight_variable([ 1, 1, in_filter, f1])
  43. X = tf.nn.conv2d(X_input, W_conv1, strides=[ 1, 1, 1, 1], padding= 'SAME')
  44. b_conv1 = bias_variable([f1])
  45. X = tf.nn.relu(X+ b_conv1)
  46. #second
  47. W_conv2 = weight_variable([kernel_size, kernel_size, f1, f2])
  48. X = tf.nn.conv2d(X, W_conv2, strides=[ 1, 1, 1, 1], padding= 'SAME')
  49. b_conv2 = bias_variable([f2])
  50. X = tf.nn.relu(X+ b_conv2)
  51. #third
  52. W_conv3 = weight_variable([ 1, 1, f2, f3])
  53. X = tf.nn.conv2d(X, W_conv3, strides=[ 1, 1, 1, 1], padding= 'SAME')
  54. b_conv3 = bias_variable([f3])
  55. X = tf.nn.relu(X+ b_conv3)
  56. #final step
  57. add = tf.add(X, X_shortcut)
  58. #b_conv_fin = bias_variable([f3])
  59. add_result = tf.nn.relu(add)
  60. return add_result
  61. #这里定义conv_block模块,由于该模块定义时输入和输出尺度不同,故需要进行卷积操作来改变尺度,从而得以相加
  62. def convolutional_block( X_input, kernel_size, in_filter,
  63. out_filters, stage, block, stride=2):
  64. """
  65. Implementation of the convolutional block as defined in Figure 4
  66. Arguments:
  67. X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
  68. kernel_size -- integer, specifying the shape of the middle CONV's window for the main path
  69. filters -- python list of integers, defining the number of filters in the CONV layers of the main path
  70. stage -- integer, used to name the layers, depending on their position in the network
  71. block -- string/character, used to name the layers, depending on their position in the network
  72. training -- train or test
  73. stride -- Integer, specifying the stride to be used
  74. Returns:
  75. X -- output of the convolutional block, tensor of shape (n_H, n_W, n_C)
  76. """
  77. # defining name basis
  78. block_name = 'res' + str(stage) + block
  79. with tf.variable_scope(block_name):
  80. f1, f2, f3 = out_filters
  81. x_shortcut = X_input
  82. #first
  83. W_conv1 = weight_variable([ 1, 1, in_filter, f1])
  84. X = tf.nn.conv2d(X_input, W_conv1,strides=[ 1, stride, stride, 1],padding= 'SAME')
  85. b_conv1 = bias_variable([f1])
  86. X = tf.nn.relu(X + b_conv1)
  87. #second
  88. W_conv2 =weight_variable([kernel_size, kernel_size, f1, f2])
  89. X = tf.nn.conv2d(X, W_conv2, strides=[ 1, 1, 1, 1], padding= 'SAME')
  90. b_conv2 = bias_variable([f2])
  91. X = tf.nn.relu(X+b_conv2)
  92. #third
  93. W_conv3 = weight_variable([ 1, 1, f2,f3])
  94. X = tf.nn.conv2d(X, W_conv3, strides=[ 1, 1, 1, 1], padding= 'SAME')
  95. b_conv3 = bias_variable([f3])
  96. X = tf.nn.relu(X+b_conv3)
  97. #shortcut path
  98. W_shortcut =weight_variable([ 1, 1, in_filter, f3])
  99. x_shortcut = tf.nn.conv2d(x_shortcut, W_shortcut, strides=[ 1, stride, stride, 1], padding= 'VALID')
  100. #final
  101. add = tf.add(x_shortcut, X)
  102. #建立最后融合的权重
  103. #b_conv_fin = bias_variable([f3])
  104. add_result = tf.nn.relu(add)
  105. return add_result
  106. x1 = tf.reshape(x, [ -1, 28, 28, 1])
  107. w_conv1 = weight_variable([ 2, 2, 1, 64])
  108. x1 = tf.nn.conv2d(x1, w_conv1, strides=[ 1, 2, 2, 1], padding= 'SAME')
  109. b_conv1 = bias_variable([ 64])
  110. x1 = tf.nn.relu(x1+b_conv1)
  111. # 这里操作后变成14x14x64
  112. x1 = tf.nn.max_pool(x1, ksize=[ 1, 3, 3, 1], strides=[ 1, 1, 1, 1], padding= 'SAME')
  113. # stage 2
  114. x2 = convolutional_block(X_input=x1, kernel_size= 3, in_filter= 64, out_filters=[ 64, 64, 256], stage= 2, block= 'a', stride= 1)
  115. # 上述conv_block操作后,尺寸变为14x14x256
  116. x2 = identity_block(x2, 3, 256, [ 64, 64, 256], stage= 2, block= 'b' )
  117. x2 = identity_block(x2, 3, 256, [ 64, 64, 256], stage= 2, block= 'c')
  118. # 上述操作后张量尺寸变成14x14x256
  119. x2 = tf.nn.max_pool(x2, [ 1, 2, 2, 1], strides=[ 1, 2, 2, 1], padding= 'SAME')
  120. # 变成7x7x256
  121. flat = tf.reshape(x2, [ -1, 7* 7* 256])
  122. w_fc1 = weight_variable([ 7 * 7 * 256, 1024])
  123. b_fc1 = bias_variable([ 1024])
  124. h_fc1 = tf.nn.relu(tf.matmul(flat, w_fc1) + b_fc1)
  125. keep_prob = tf.placeholder(tf.float32)
  126. h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
  127. w_fc2 = weight_variable([ 1024, 10])
  128. b_fc2 = bias_variable([ 10])
  129. y_conv = tf.matmul(h_fc1_drop, w_fc2) + b_fc2
  130. #建立损失函数,在这里采用交叉熵函数
  131. cross_entropy = tf.reduce_mean(
  132. tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=y_conv))
  133. train_step = tf.train.AdamOptimizer( 1e-3).minimize(cross_entropy)
  134. correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y, 1))
  135. accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  136. #初始化变量
  137. sess.run(tf.global_variables_initializer())
  138. os.environ[ "TF_CPP_MIN_LOG_LEVEL"]= "3"
  139. for i in range( 3001):
  140. batch = mnist.train.next_batch( 10)
  141. if i% 100 == 0:
  142. train_accuracy = accuracy.eval(feed_dict={
  143. x:batch[ 0], y: batch[ 1], keep_prob: 1.0})
  144. print( "step %d, training accuracy %g"%(i, train_accuracy))
  145. train_step.run(feed_dict={x: batch[ 0], y: batch[ 1], keep_prob: 0.5})
  146. print( "test accuracy %g"%accuracy.eval(feed_dict={
  147. x: mnist.test.images, y: mnist.test.labels, keep_prob: 1.0}))

在identity_block和convolutional_block中注释掉b_conv_fin = bias_variable([f3]),也就是在做ReLU时不添加额外的偏置值,效率直线上升:

原来的代码效率:

更新后的代码训练1000次:

训练3000次:

ps.大家注意到我一开始还添加了额外的一条代码:os.environ["TF_CPP_MIN_LOG_LEVEL"]="3",之前在运行时报错了:The TensorFlow library wasn't compiled to use SSE instructions, but these are available on your machine and could speed up CPU computations.

大致就是说我的tensorflow不是原生的,不能使用sse为cpu加速,嗯。。。直接屏蔽掉。。。

 

关注
打赏
1510642601
查看更多评论
立即登录/注册

微信扫码登录

0.0397s