当前位置:   article > 正文

tensorboard 可视化卷积层_tensorboardx可视化卷积层

tensorboardx可视化卷积层

不说废话先上代码:

  1. #coding:utf-8
  2. #learning how to use tensorboard in cnn
  3. import tensorflow.examples.tutorials.mnist.input_data as input_data
  4. mnist = input_data.read_data_sets("data/", one_hot=True)
  5. import tensorflow as tf
  6. import matplotlib.pyplot as plt
  7. import numpy as np
  8. #define fuctions*******************************************************************************************************************
  9. def weight_variable(shape):
  10. initial = tf.truncated_normal(shape,stddev = 0.1)
  11. return tf.Variable(initial)
  12. def bias_variable(shape):
  13. initial = tf.constant(0.1,shape=shape)#行向量
  14. return tf.Variable(initial)
  15. def conv2d(x,w):
  16. return tf.nn.conv2d(x,w,strides=[1,1,1,1],padding='SAME')
  17. def max_pool_2X2(x):
  18. return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
  19. def variable_summaries(var,name):
  20. with tf.name_scope('summaries'):
  21. mean = tf.reduce_mean(var)
  22. tf.summary.scalar('mean/'+name,mean)
  23. with tf.name_scope('stddev'):
  24. stddev = tf.sqrt(tf.reduce_mean(tf.square(var-mean)))
  25. tf.summary.scalar('stddev/'+name,stddev)
  26. tf.summary.histogram(name,var)
  27. def conv_image_visual(conv_image,image_weight,image_height,cy,cx,channels):
  28. #slice off one image ande remove the image dimension
  29. #original image is a 4d tensor[batche_size,weight,height,channels]
  30. conv_image = tf.slice(conv_image,(0,0,0,0),(1,-1,-1,-1))
  31. conv_image = tf.reshape(conv_image,(image_height,image_weight,channels))
  32. #add a couple of pixels of zero padding around the image
  33. image_weight += 4
  34. image_height += 4
  35. conv_image = tf.image.resize_image_with_crop_or_pad(conv_image,image_height,image_weight)
  36. conv_image = tf.reshape(conv_image,(image_height,image_weight,cy,cx))
  37. conv_image = tf.transpose(conv_image,(2,0,3,1))
  38. conv_image = tf.reshape(conv_image,(1,cy*image_height,cx*image_weight,1))
  39. return conv_image
  40. #**********************************************************************************************************************************
  41. with tf.name_scope('intput'):
  42. x = tf.placeholder(tf.float32,shape = [None,784],name = 'x')
  43. y_ = tf.placeholder(tf.float32,shape = [None,10],name = 'labels')
  44. input_image = tf.reshape(x,shape = [-1,28,28,1])
  45. tf.summary.image('input_image',input_image,max_outputs = 1 )
  46. with tf.name_scope('cnn_block'):
  47. w_conv1 = weight_variable([5,5,1,32])
  48. b_conv1 = bias_variable([32])
  49. variable_summaries(w_conv1,'first_cnn_layer_weight')
  50. variable_summaries(b_conv1,'first_cnn_layer_bais')
  51. with tf.name_scope('reshape'):
  52. #将输入数据转换成28×28,channel = 1的图像
  53. x_image = tf.reshape(x,[-1,28,28,1])
  54. with tf.name_scope('first_cnn_layer'):
  55. #进行第一层卷积网络的运算h_conv1=[-1,28,28,32]
  56. h_conv1 = tf.nn.relu(conv2d(x_image,w_conv1)+b_conv1)
  57. with tf.name_scope('conv1_vis'):
  58. conv1_image = conv_image_visual(h_conv1,28,28,4,8,32)
  59. tf.summary.image('h_conv1',conv1_image)
  60. with tf.name_scope('first_pool_layer'):
  61. h_pool1 = max_pool_2X2(h_conv1)
  62. with tf.name_scope('second_cnn_layer'):
  63. #第二层卷积网络
  64. w_conv2 = weight_variable([5,5,32,64])
  65. b_conv2 = bias_variable([64])
  66. #第二层卷积输出[batch_size,14,14,64]
  67. h_conv2 = tf.nn.relu(conv2d(h_pool1,w_conv2)+b_conv2)
  68. with tf.name_scope('conv2_vis'):
  69. conv2_iamge = conv_image_visual(h_conv2,14,14,8,8,64)
  70. tf.summary.image('h_conv2',conv2_iamge)
  71. with tf.name_scope('second_pool_layer'):
  72. h_pool2 = max_pool_2X2(h_conv2)
  73. with tf.name_scope('first_fullconect_layer'):
  74. #经过两个池化操作图片从28*28降维到了7*7,
  75. w_fc1 = weight_variable([7*7*64,1024])
  76. b_fc1 = bias_variable([1024])
  77. #reshape为行向量
  78. with tf.name_scope('h_pool2_reshape'):
  79. h_pool2_reshape = tf.reshape(h_pool2,[-1,7*7*64])
  80. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_reshape,w_fc1)+b_fc1)
  81. #使用dropout防止过拟合
  82. with tf.name_scope('dropout'):
  83. keep_prob = tf.placeholder(tf.float32)
  84. h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)
  85. with tf.name_scope('out_put_layer'):
  86. #输出层
  87. w_fc2 = weight_variable([1024,10])
  88. b_fc2 = bias_variable([10])
  89. with tf.name_scope('softmax'):
  90. y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop,w_fc2)+b_fc2)
  91. #损失函数
  92. with tf.name_scope('cross_entropy'):
  93. cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
  94. tf.summary.scalar('cross_entropy',cross_entropy)
  95. with tf.name_scope('train_step'):
  96. train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
  97. with tf.name_scope('accuracy'):
  98. with tf.name_scope('correct_prediction'):
  99. correct_prediction = tf.equal(tf.argmax(y_conv,1),tf.argmax(y_,1))
  100. with tf.name_scope('accuracy'):
  101. accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
  102. tf.summary.scalar('accuracy',accuracy)
  103. init_op = tf.global_variables_initializer()
  104. merged = tf.summary.merge_all()
  105. with tf.Session() as sess:
  106. sess.run(init_op)
  107. train_writer = tf.summary.FileWriter("tensorboard/",sess.graph)
  108. for i in range(1000):
  109. batch = mnist.train.next_batch(50)
  110. summary, _ = sess.run([merged,train_step],feed_dict = {x:batch[0],y_:batch[1],keep_prob:0.5})
  111. train_writer.add_summary(summary,i)
  112. if i%10 == 0:
  113. summary,acc = sess.run([merged,accuracy],feed_dict = {x:batch[0],y_:batch[1],keep_prob:0.5})
  114. train_writer.add_summary(summary,i)
  115. print "step %d,training accuracy %g"%(i,acc)
  116. train_writer.close();
  117. #print "test accuracy %g"%accuracy.eval(feed_dict = {x:mnist.test.images,y_:mnist.test.labels,keep_prob:1.0}

效果图:

分析一下可视化卷积层最终要的一段代码:

  1. def conv_image_visual(conv_image,image_weight,image_height,cy,cx,channels):
  2. #slice off one image ande remove the image dimension
  3. #original image is a 4d tensor[batche_size,weight,height,channels]
  4. conv_image = tf.slice(conv_image,(0,0,0,0),(1,-1,-1,-1))
  5. conv_image = tf.reshape(conv_image,(image_height,image_weight,channels))
  6. #add a couple of pixels of zero padding around the image
  7. image_weight += 4
  8. image_height += 4
  9. conv_image = tf.image.resize_image_with_crop_or_pad(conv_image,image_height,image_weight)
  10. conv_image = tf.reshape(conv_image,(image_height,image_weight,cy,cx))
  11. conv_image = tf.transpose(conv_image,(2,0,3,1))
  12. conv_image = tf.reshape(conv_image,(1,cy*image_height,cx*image_weight,1))
  13. return conv_image

该函数的参数:conv_image:待可视化的卷积结果;image_w:卷积后图像的宽;iamge_h:卷积后图像的高;cy:图像显示的行数;cx:图像显示的列数;channels:图像的通道数;

比如我要显示第一个卷积层经过激活函数后的图像,经过一次卷积后图像的channels变成了32,如果我要将这32个通道的结果以4行8列显示的话,则cy=4,cx=8;

  1. conv_image = tf.slice(conv_image,(0,0,0,0),(1,-1,-1,-1))
  2. conv_image = tf.reshape(conv_image,(image_height,image_weight,channels))

 因为tf.summary.image()函数输入的tensor的格式为:[batch_size,height,width,channels]而channel只能为1,3,4分别表示gray,RGB,RGBA图像,而卷积后的图像格式为[batch_size,height,width,channels],这里的channel=卷积核的个数,因此如果直接将卷积后的图像输入到tf.summary.image()会报错,而且不能显示每一个卷积核作用到图像后的结果,因此我们第一步就是要消减卷积结果的维度tf.slice()操作后,消去了第一个(batch_size)维度,这个操作可以理解为从每一个batch中挑选了第一张图片进行显示,这也就造成了每一步显示的图片是不同的。

经过slice操作以后图像还是四维的因此使用reshape将图像降维成3维彻底剔除batch_size。以下例子说明了此操作的必要性

slice后数据是三维[[[7,8,9]]](三个括号),reshape后为[[7,8,9]]二维。

  1. #add a couple of pixels of zero padding around the image
  2. image_weight += 4
  3. image_height += 4
  4. conv_image = tf.image.resize_image_with_crop_or_pad(conv_image,image_height,image_weight)

使用零填充图像的边界,这里对原图像以外的四个像素进行了扩充

  1. conv_image = tf.reshape(conv_image,(image_height,image_weight,cy,cx))
  2. conv_image = tf.transpose(conv_image,(2,0,3,1))
  3. conv_image = tf.reshape(conv_image,(1,cy*image_height,cx*image_weight,1))

第一个reshape()是为了将n个channel拆分为cy×cx,tf.transpose()将图像由[image_height,image_weight,cy,cx]转换为[cy,image_height,cx,image_width]最后通过reshape()将n个卷积结果在一张图片上显示。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/346276
推荐阅读
相关标签
  

闽ICP备14008679号