神经网络学习小记录1——利用tensorflow构建卷积神经网络(CNN)

拼搏现实的明天。 2021-11-23 04:32 616阅读 0赞

神经网络学习小记录1——利用tensorflow构建卷积神经网络(CNN)

  • 学习前言
    • 简介
    • 隐含层介绍
      • 1、卷积层
      • 2、池化层
      • 3、全连接层
    • 具体实现代码
      • 卷积层、池化层与全连接层实现代码
      • 全部代码

学习前言

学习神经网络已经有一段时间,从普通的BP神经网络到LSTM长短期记忆网络都有一定的了解,但是从未系统的把整个神经网络的结构记录下来,我相信这些小记录可以帮助我更加深刻的理解神经网络。
在这里插入图片描述

简介

卷积神经网络(Convolutional Neural Networks, CNN)是一类包含卷积计算且具有深度结构的前馈神经网络(Feedforward Neural Networks),是深度学习(deep learning)的代表算法之一。
其主要结构分为输入层、隐含层、输出层。
在tensorboard中,其结构如图所示:
CNN
对于卷积神经网络而言,其输入层、输出层与平常的卷积神经网络无异。但其隐含层可以分为三个部分,分别是卷积层(对输入数据进行特征提取)、池化层(特征选择和信息过滤)、全连接层(等价于传统前馈神经网络中的隐含层)。

隐含层介绍

1、卷积层

卷积将输入图像放进一组卷积滤波器,每个滤波器激活图像中的某些特征。
假设一副黑白图像为5*5的大小,像这样:
示例
利用如下卷积器进行卷积:
示例
卷积结果为:
示例
卷积过程可以提取特征,卷积神经网络是根据特征来完成分类的。
在tensorflow中,卷积层的重要函数是:
tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None),其中:
1、input是输入量,shape是[batch, height, width, channels]。;
2、filter是使用的卷积核;
3、strides是步长,其格式[1,step,step,1],step指的是在图像卷积的每一维的步长;
4、padding:string类型的量,只能是”SAME”,”VALID”其中之一,SAME表示卷积前后图像面积不变。

2、池化层

池化层用于在卷积层进行特征提取后,输出的特征图会被传递至池化层进行特征选择和信息过滤。
常见的池化是最大池化,最大池化指的是取出这些被卷积后的数据的最大值,就是取出其最大特征。
假设其池化窗口为2X2,步长为2。
原图像为:
示例
池化后为:
示例
在tensorflow中,池化层的重要函数是:
tf.nn.max_pool(value, ksize, strides, padding, data_format, name)
1、value:池化层的输入,一般池化层接在卷积层后面,shape是[batch, height, width, channels]。
2、ksize:池化窗口的大小,取一个四维向量,一般是[1, in_height, in_width, 1]。
3、strides:和卷积类似,窗口在每一个维度上滑动的步长,也是[1, stride,stride, 1]。
4、padding:和卷积类似,可以取’VALID’ 或者’SAME’。

这是tensorboard中卷积层和池化层的连接结构:
卷积层池化层

3、全连接层

全连接层与普通神经网络的结构相同,如图所示:
全连接层

具体实现代码

卷积层、池化层与全连接层实现代码

  1. def conv2d(x,W,step,pad): #用于进行卷积,x为输入值,w为卷积核
  2. return tf.nn.conv2d(x,W,strides = [1,step,step,1],padding = pad)
  3. def max_pool_2X2(x,step,pad): #用于池化,x为输入值,step为步数
  4. return tf.nn.max_pool(x,ksize = [1,2,2,1],strides= [1,step,step,1],padding = pad)
  5. def weight_variable(shape): #用于获得W
  6. initial = tf.truncated_normal(shape,stddev = 0.1) #从截断的正态分布中输出随机值
  7. return tf.Variable(initial)
  8. def bias_variable(shape): #获得bias
  9. initial = tf.constant(0.1,shape=shape) #生成普通值
  10. return tf.Variable(initial)
  11. def add_layer(inputs,in_size,out_size,n_layer,activation_function = None,keep_prob = 1):
  12. #用于添加全连接层
  13. layer_name = 'layer_%s'%n_layer
  14. with tf.name_scope(layer_name):
  15. with tf.name_scope("Weights"):
  16. Weights = tf.Variable(tf.truncated_normal([in_size,out_size],stddev = 0.1),name = "Weights")
  17. tf.summary.histogram(layer_name+"/weights",Weights)
  18. with tf.name_scope("biases"):
  19. biases = tf.Variable(tf.zeros([1,out_size]) + 0.1,name = "biases")
  20. tf.summary.histogram(layer_name+"/biases",biases)
  21. with tf.name_scope("Wx_plus_b"):
  22. Wx_plus_b = tf.matmul(inputs,Weights) + biases
  23. tf.summary.histogram(layer_name+"/Wx_plus_b",Wx_plus_b)
  24. if activation_function == None :
  25. outputs = Wx_plus_b
  26. else:
  27. outputs = activation_function(Wx_plus_b)
  28. print(activation_function)
  29. outputs = tf.nn.dropout(outputs,keep_prob)
  30. tf.summary.histogram(layer_name+"/outputs",outputs)
  31. return outputs
  32. def add_cnn_layer(inputs, in_z_dim, out_z_dim, n_layer, conv_step = 1, pool_step = 2, padding = "SAME"):
  33. #用于生成卷积层和池化层
  34. layer_name = 'layer_%s'%n_layer
  35. with tf.name_scope(layer_name):
  36. with tf.name_scope("Weights"):
  37. W_conv = weight_variable([5,5,in_z_dim,out_z_dim])
  38. with tf.name_scope("biases"):
  39. b_conv = bias_variable([out_z_dim])
  40. with tf.name_scope("conv"):
  41. #卷积层
  42. h_conv = tf.nn.relu(conv2d(inputs, W_conv, conv_step, padding)+b_conv)
  43. with tf.name_scope("pooling"):
  44. #池化层
  45. h_pool = max_pool_2X2(h_conv, pool_step, padding)
  46. return h_pool

全部代码

  1. import tensorflow as tf
  2. from tensorflow.examples.tutorials.mnist import input_data
  3. mnist = input_data.read_data_sets("MNIST_data",one_hot = "true")
  4. def conv2d(x,W,step,pad):
  5. return tf.nn.conv2d(x,W,strides = [1,step,step,1],padding = pad)
  6. def max_pool_2X2(x,step,pad):
  7. return tf.nn.max_pool(x,ksize = [1,2,2,1],strides= [1,step,step,1],padding = pad)
  8. def weight_variable(shape):
  9. initial = tf.truncated_normal(shape,stddev = 0.1) #从截断的正态分布中输出随机值
  10. return tf.Variable(initial)
  11. def bias_variable(shape):
  12. initial = tf.constant(0.1,shape=shape) #生成普通值
  13. return tf.Variable(initial)
  14. def add_layer(inputs,in_size,out_size,n_layer,activation_function = None,keep_prob = 1):
  15. layer_name = 'layer_%s'%n_layer
  16. with tf.name_scope(layer_name):
  17. with tf.name_scope("Weights"):
  18. Weights = tf.Variable(tf.truncated_normal([in_size,out_size],stddev = 0.1),name = "Weights")
  19. tf.summary.histogram(layer_name+"/weights",Weights)
  20. with tf.name_scope("biases"):
  21. biases = tf.Variable(tf.zeros([1,out_size]) + 0.1,name = "biases")
  22. tf.summary.histogram(layer_name+"/biases",biases)
  23. with tf.name_scope("Wx_plus_b"):
  24. Wx_plus_b = tf.matmul(inputs,Weights) + biases
  25. tf.summary.histogram(layer_name+"/Wx_plus_b",Wx_plus_b)
  26. if activation_function == None :
  27. outputs = Wx_plus_b
  28. else:
  29. outputs = activation_function(Wx_plus_b)
  30. print(activation_function)
  31. outputs = tf.nn.dropout(outputs,keep_prob)
  32. tf.summary.histogram(layer_name+"/outputs",outputs)
  33. return outputs
  34. def add_cnn_layer(inputs, in_z_dim, out_z_dim, n_layer, conv_step = 1, pool_step = 2, padding = "SAME"):
  35. layer_name = 'layer_%s'%n_layer
  36. with tf.name_scope(layer_name):
  37. with tf.name_scope("Weights"):
  38. W_conv = weight_variable([5,5,in_z_dim,out_z_dim])
  39. with tf.name_scope("biases"):
  40. b_conv = bias_variable([out_z_dim])
  41. with tf.name_scope("conv"):
  42. h_conv = tf.nn.relu(conv2d(inputs, W_conv, conv_step, padding)+b_conv)
  43. with tf.name_scope("pooling"):
  44. h_pool = max_pool_2X2(h_conv, pool_step, padding)
  45. return h_pool
  46. def compute_accuracy(x_data,y_data):
  47. global prediction
  48. y_pre = sess.run(prediction,feed_dict={
  49. xs:x_data,keep_prob:1})
  50. correct_prediction = tf.equal(tf.arg_max(y_data,1),tf.arg_max(y_pre,1))
  51. accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
  52. result = sess.run(accuracy,feed_dict = {
  53. xs:batch_xs,ys:batch_ys,keep_prob:1})
  54. return result
  55. keep_prob = tf.placeholder(tf.float32)
  56. xs = tf.placeholder(tf.float32,[None,784])
  57. ys = tf.placeholder(tf.float32,[None,10])
  58. x_image = tf.reshape(xs,[-1,28,28,1])
  59. h_pool1 = add_cnn_layer(x_image, in_z_dim = 1, out_z_dim = 32, n_layer = "cnn1",)
  60. h_pool2 = add_cnn_layer(h_pool1, in_z_dim = 32, out_z_dim = 64, n_layer = "cnn2",)
  61. h_pool2_flat = tf.reshape(h_pool2,[-1,7*7*64])
  62. h_fc1_drop = add_layer(h_pool2_flat, 7*7*64, 1024, "layer1", activation_function = tf.nn.relu, keep_prob = keep_prob)
  63. prediction = add_layer(h_fc1_drop, 1024, 10, "layer2", activation_function = tf.nn.softmax, keep_prob = 1)
  64. with tf.name_scope("loss"):
  65. loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=ys,logits = prediction),name = 'loss')
  66. tf.summary.scalar("loss",loss)
  67. train = tf.train.AdamOptimizer(1e-4).minimize(loss)
  68. init = tf.initialize_all_variables()
  69. merged = tf.summary.merge_all()
  70. with tf.Session() as sess:
  71. sess.run(init)
  72. write = tf.summary.FileWriter("logs/",sess.graph)
  73. for i in range(5000):
  74. batch_xs,batch_ys = mnist.train.next_batch(100)
  75. sess.run(train,feed_dict = {
  76. xs:batch_xs,ys:batch_ys,keep_prob:0.5})
  77. if i % 100 == 0:
  78. print(compute_accuracy(mnist.test.images,mnist.test.labels))

希望得到朋友们的喜欢。

有不懂的朋友可以评论询问噢。

发表评论

表情:
评论列表 (有 0 条评论,616人围观)

还没有评论,来说两句吧...

相关阅读

    相关 神经网络CNN

    系列文章目录 上一篇文章简单的介绍了卷积神经网络及一些基础知识,比如说步长,填充,互相关运算等,这篇文章讲介绍卷积神经网络的组成及常见的几种神经网络。  [CNN简单介