首先看一下卷积神经网络模型,如下图:

卷积神经网络(CNN)由输入层、卷积层、激活函数、池化层、全连接层组成,即INPUT-CONV-RELU-POOL-FC
池化层:为了减少运算量和数据维度而设置的一种层。

代码如下:

  1. n_input = 784 # 28*28的灰度图
  2. n_output = 10 # 完成一个10分类的操作
  3. weights = {
  4. #'权重参数': tf.Variable(tf.高期([feature的H, feature的W, 当前feature连接的输入的深度, 最终想得到多少个特征图], 标准差=0.1)),
  5. 'wc1': tf.Variable(tf.random_normal([3, 3, 1, 64], stddev=0.1)),
  6. 'wc2': tf.Variable(tf.random_normal([3, 3, 64, 128], stddev=0.1)),
  7.    #'全连接层参数': tf.Variable(tf.高斯([特征图H*特征图W*深度, 最终想得到多少个特征图], 标准差=0.1)),
  8. 'wd1': tf.Variable(tf.random_normal([7*7*128, 1024], stddev=0.1)),
  9. 'wd2': tf.Variable(tf.random_normal([1024, n_output], stddev=0.1))
  10. }
  11. biases = {
  12.    #'偏置参数': tf.Variable(tf.高斯([第1层有多少个偏置项], 标准差=0.1)),
  13. 'bc1': tf.Variable(tf.random_normal([64], stddev=0.1)),
  14. 'bc2': tf.Variable(tf.random_normal([128], stddev=0.1)),
  15. 'bd1': tf.Variable(tf.random_normal([1024], stddev=0.1)),
  16. 'bd2': tf.Variable(tf.random_normal([n_output], stddev=0.1))
  17. }
  18.  
  19. #卷积神经网络
  20. def conv_basic(_input, _w, _b, _keepratio):
  21. #将输入数据转化成一个四维的[n, h, w, c]tensorflow格式数据
  22. #_input_r = tf.将输入数据转化成tensorflow格式(输入, shape=[batch_size大小, H, W, 深度])
  23. _input_r = tf.reshape(_input, shape=[-1, 28, 28, 1])
  24.  
  25. #第1层卷积
  26. #_conv1 = tf.nn.卷积(输入, 权重参数, 步长=[batch_size大小, H, W, 深度], padding='建议选择SAME')
  27. _conv1 = tf.nn.conv2d(_input_r, _w['wc1'], strides=[1, 1, 1, 1], padding='SAME')
  28. #_conv1 = tf.nn.非线性激活函数(tf.nn.加法(_conv1, _b['bc1']))
  29. _conv1 = tf.nn.relu(tf.nn.bias_add(_conv1, _b['bc1']))
  30. #第1层池化
  31. #_pool1 = tf.nn.池化函数(_conv1, 指定池化窗口的大小=[batch_size大小, H, W, 深度], strides=[1, 2, 2, 1], padding='SAME')
  32. _pool1 = tf.nn.max_pool(_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
  33. #随机杀死一些节点,不让所有神经元都加入到训练中
  34. #_pool_dr1 = tf.nn.dropout(_pool1, 保留比例)
  35. _pool_dr1 = tf.nn.dropout(_pool1, _keepratio)
  36.  
  37. #第2层卷积
  38. _conv2 = tf.nn.conv2d(_pool_dr1, _w['wc2'], strides=[1, 1, 1, 1], padding='SAME')
  39. _conv2 = tf.nn.relu(tf.nn.bias_add(_conv2, _b['bc2']))
  40. _pool2 = tf.nn.max_pool(_conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
  41. _pool_dr2 = tf.nn.dropout(_pool2, _keepratio)
  42.  
  43. #全连接层
  44. #转化成tensorflow格式
  45. _dense1 = tf.reshape(_pool_dr2, [-1, _w['wd1'].get_shape().as_list()[0]])
  46. #第1层全连接层
  47. _fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1']))
  48. _fc_dr1 = tf.nn.dropout(_fc1, _keepratio)
  49. #第2层全连接层
  50. _out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2'])
  51. #返回值
  52. out = { 'input_r': _input_r, 'conv1': _conv1, 'pool1': _pool1, 'pool1_dr1': _pool_dr1,
  53. 'conv2': _conv2, 'pool2': _pool2, 'pool_dr2': _pool_dr2, 'dense1': _dense1,
  54. 'fc1': _fc1, 'fc_dr1': _fc_dr1, 'out': _out
  55. }
  56. return out
  57. print ("CNN READY")
  58.  
  59. #设置损失函数&优化器(代码说明:略 请看前面文档)
  60. learning_rate = 0.001
  61. x = tf.placeholder("float", [None, nsteps, diminput])
  62. y = tf.placeholder("float", [None, dimoutput])
  63. myrnn = _RNN(x, weights, biases, nsteps, 'basic')
  64. pred = myrnn['O']
  65. cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
  66. optm = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) # Adam Optimizer
  67. accr = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(pred,1), tf.argmax(y,1)), tf.float32))
  68. init = tf.global_variables_initializer()
  69. print ("Network Ready!")
  70.  
  71. #训练(代码说明:略 请看前面文档)
  72. training_epochs = 5
  73. batch_size = 16
  74. display_step = 1
  75. sess = tf.Session()
  76. sess.run(init)
  77. print ("Start optimization")
  78. for epoch in range(training_epochs):
  79. avg_cost = 0.
  80. #total_batch = int(mnist.train.num_examples/batch_size)
  81. total_batch = 100
  82. # Loop over all batches
  83. for i in range(total_batch):
  84. batch_xs, batch_ys = mnist.train.next_batch(batch_size)
  85. batch_xs = batch_xs.reshape((batch_size, nsteps, diminput))
  86. # Fit training using batch data
  87. feeds = {x: batch_xs, y: batch_ys}
  88. sess.run(optm, feed_dict=feeds)
  89. # Compute average loss
  90. avg_cost += sess.run(cost, feed_dict=feeds)/total_batch
  91. # Display logs per epoch step
  92. if epoch % display_step == 0:
  93. print ("Epoch: %03d/%03d cost: %.9f" % (epoch, training_epochs, avg_cost))
  94. feeds = {x: batch_xs, y: batch_ys}
  95. train_acc = sess.run(accr, feed_dict=feeds)
  96. print (" Training accuracy: %.3f" % (train_acc))
  97. testimgs = testimgs.reshape((ntest, nsteps, diminput))
  98. feeds = {x: testimgs, y: testlabels, istate: np.zeros((ntest, 2*dimhidden))}
  99. test_acc = sess.run(accr, feed_dict=feeds)
  100. print (" Test accuracy: %.3f" % (test_acc))
  101. print ("Optimization Finished.")

利用Tensorflow实现卷积神经网络模型的更多相关文章

  1. 手写数字识别 ----卷积神经网络模型官方案例注释(基于Tensorflow,Python)

    # 手写数字识别 ----卷积神经网络模型 import os import tensorflow as tf #部分注释来源于 # http://www.cnblogs.com/rgvb178/p/ ...

  2. CNN-1: LeNet-5 卷积神经网络模型

    1.LeNet-5模型简介 LeNet-5 模型是 Yann LeCun 教授于 1998 年在论文 Gradient-based learning applied to document      ...

  3. 使用PyTorch简单实现卷积神经网络模型

    这里我们会用 Python 实现三个简单的卷积神经网络模型:LeNet .AlexNet .VGGNet,首先我们需要了解三大基础数据集:MNIST 数据集.Cifar 数据集和 ImageNet 数 ...

  4. 【TensorFlow/简单网络】MNIST数据集-softmax、全连接神经网络,卷积神经网络模型

    初学tensorflow,参考了以下几篇博客: soft模型 tensorflow构建全连接神经网络 tensorflow构建卷积神经网络 tensorflow构建卷积神经网络 tensorflow构 ...

  5. CNN-2: AlexNet 卷积神经网络模型

    1.AlexNet 模型简介 由于受到计算机性能的影响,虽然LeNet在图像分类中取得了较好的成绩,但是并没有引起很多的关注. 知道2012年,Alex等人提出的AlexNet网络在ImageNet大 ...

  6. CNN-3: VGGNet 卷积神经网络模型

    1.VGGNet 模型简介 VGG Net由牛津大学的视觉几何组(Visual Geometry Group)和 Google DeepMind公司的研究员一起研发的的深度卷积神经网络,在 ILSVR ...

  7. CNN-4: GoogLeNet 卷积神经网络模型

    1.GoogLeNet 模型简介 GoogLeNet 是2014年Christian Szegedy提出的一种全新的深度学习结构,该模型获得了ImageNet挑战赛的冠军. 2.GoogLeNet 模 ...

  8. caffe中LetNet-5卷积神经网络模型文件lenet.prototxt理解

    caffe在 .\examples\mnist文件夹下有一个 lenet.prototxt文件,这个文件定义了一个广义的LetNet-5模型,对这个模型文件逐段分解一下. name: "Le ...

  9. 吴裕雄--天生自然python Google深度学习框架:经典卷积神经网络模型

    import tensorflow as tf INPUT_NODE = 784 OUTPUT_NODE = 10 IMAGE_SIZE = 28 NUM_CHANNELS = 1 NUM_LABEL ...

随机推荐

  1. nodejs抓取页面内容,并分析有无某些内容的js文件

    nodejs获取网页内容绑定data事件,获取到的数据会分几次相应,如果想全局内容匹配,需要等待请求结束,在end结束事件里把累积起来的全局数据进行操作! 举个例子,比如要在页面中找有没有www.ba ...

  2. [Android实例] Android Studio插件-自动根据布局生成Activity等代码1.4 (开源)(申明:来源于网络)

    [Android实例] Android Studio插件-自动根据布局生成Activity等代码1.4 (开源)(申明:来源于网络) 地址:http://www.eoeandroid.com/thre ...

  3. MySQL设置只读模式

    MySQL设置了主从复制,为保证数据一致性需要在从库设置只读状态 查看默认读写状态 show global variables like "%read_only%"; 设置只读 # ...

  4. hdparm命令(转)

    转自:http://man.linuxde.net/hdparm hdparm命令提供了一个命令行的接口用于读取和设置IDE或SCSI硬盘参数. 语法 hdparm(选项)(参数) 选项 -a< ...

  5. F#周报2018年第48期

    新闻 F#2018年圣诞日历 Mac上的Visual Studio 2017新版本7.7 Rider 2018.3将引入远程调试功能 Visual Studio 2017新版本15.9.3 视频及幻灯 ...

  6. 动态环境下的slam问题如何解决?

    作者:颜沁睿链接:https://www.zhihu.com/question/47817909/answer/107775045来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注 ...

  7. ES6 import

    ES6标准发布后,module成为标准,标准的使用是以export指令导出接口,以import引入模块,但是在我们一贯的node模块中,我们采用的是CommonJS规范,使用require引入模块,使 ...

  8. 网络层block,delegate之优劣分析

    正常情况下, block 缺点: 1.block很难追踪,难以维护 2.block会延长先关对象的生命周期 block会给内部所有的对象引用计数+1, 一方面会带来潜在的循环引用(retain cyc ...

  9. 快速排序javascript实现

    快速排序基本思想: 以升序为例 数组arr,数组个数n; 1.选取一个待排序的元素.一般选第一个位置作为基准值temp=arr[0]. 2.选取带排序数组的两端元素的位置作为哨兵的位置,左端为哨兵i, ...

  10. php之二叉树

    二叉树的特点: ①.每个节点最多有两个子树,所以二叉树中不存在度大于2的节点.注意不是只有两个子树,最多有两个子树,没有子树或者只有一颗子树都是可以的. ②左子树和右子树是有顺序的. ③即使树中只有一 ...