zoukankan      html  css  js  c++  java
  • 卷积神经网络

    学习笔记:Deep Learning(三)卷积神经网络

    原创 2016年11月16日 15:57:40

    卷积神经网络CNN(Convlutional Network)

    平移不变形*translate invariance,位置不同内容不变。权重共享*可以实现平移不变性,当两种输入可以获得同样的信息的时候,则应该共享权重,并利用这些输入共同训练权重。

    评议不变形和权重共享的思想,使得我们可以用卷积神经网络研究图片,循环神经网络研究文本和序列。

    概念

    CNN是一种在空间上共享参数的神经网络,它对图片处理过程如下图描述:

    卷积神经网络金字塔

    原图片像素大小256*256,具有RGB三个通道,也就是[width=256,height=256,depth=3],第一个卷积后,生成[width=128,height=128,depth=16]大小的特征图,第二个卷积,第三个卷积……最后生成一个[width=1,height=1,depth=m]的向量,训练分类器。

    卷积就是用一个patch块,以步长stride,按行按列扫描原图像,将原图像的特征映射到后一层的特征map。

    • patch 也叫kernel,一个局部切片,上图第一个卷积就是采用了2*2大小的patch。

    • stride 步长,每跨多少步抽取信息。

    • padding 步长不能整除图片大小时边距的处理方法,“SAME”表示超过边界用0填充,使得输出保持和输入相同的大小,“VALID”表示不超过边界,通常会丢失一些信息。

    把上面的3个卷积叠加,然后连上一个全连接层Fully Connected Layer,就可以训练分类了。

    训练时,链式公式在使用共现权重时事怎样呢?nothing,就是对每个patch的梯度进行叠加。

    改进网络的三个方法

    pooling

    池化:使用small tride(=1)得到feature map,然后邻域内进行卷积,用某种方法(就是pooling)结合起来,得到后一层的特征。

    pooling

    例如,第一行是原来的方法,使用stride为2进行卷积,第二行pooling方法,首先使用stride=1进行卷积,得到与原图像大小相同的特征图,用pooling size=2,pooling stride=2参数进行pooling combine。

    pooling有两种方法: 
    - max pooling : y=max(xi)y=max(xi) 取切片的最大值 
    - mean pooling : y=mean(xi)y=mean(xi) 取切片的平均值

    1×1 convolutions

    仅关注一个像素,对每个像素进行卷积,实际上就是像素矩阵相乘,对于深层网络,矩阵相乘的代价比较低。

    inception

    对每个卷积层,执行各种卷积运行,将输出结果串联一起。

    inception

    YANN LECUN’98 发表的一个经典CNN模型 LENET-5 
    image -> Convolution -> Max Pooling -> Convolution -> Max Pooling -> Fully Connected Layer -> Fully Connected Layer -> classifier

    用TensorFlow实现CNN代码

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    __author__ = 'houlisha'
    
    
    import tensorflow as tf
    from tensorflow.examples.tutorials.mnist import input_data
    
    mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
    
    # 产生随机变量,符合 normal 分布
    def weight_variable(shape):
        initial = tf.truncated_normal(shape, stddev=0.1)
        return tf.Variable(initial)
    
    # 产生常量矩阵
    def bias_variable(shape):
        initial = tf.constant(0.1, shape=shape)
        return tf.Variable(initial)
    
    # 定义2维的convolutional图层
    # strides:每跨多少步抽取信息,strides[1, x_movement,y_movement, 1], [0]和strides[3]必须为1
    # padding:边距处理,“SAME”表示输出图层和输入图层大小保持不变,设置为“VALID”时表示舍弃多余边距(丢失信息)
    def conv2d(x, W):
        return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
    
    # 定义pooling图层
    # pooling:解决跨步大时可能丢失一些信息的问题,max-pooling就是在前图层上依次不重合采样2*2的窗口最大值
    def max_pool_2x2(x):
        return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
    
    x = tf.placeholder(tf.float32, [None, 784])
    x_image = tf.reshape(x, [-1, 28, 28, 1])                   # 将原图reshape为4维,-1表示数据是黑白的,28*28=784,1表示颜色通道数目
    y_ = tf.placeholder(tf.float32, [None, 10])
    
    ### 1. 第一层网络
    # 把x_image的厚度由1增加到32,长宽由28*28缩小为14*14
    W_conv1 = weight_variable([5, 5, 1, 32])                    # 按照[5,5,输入通道=1,输出通道=32]生成一组随机变量
    b_conv1 = bias_variable([32])                               
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)    # 输出size 28*28*32(因为conv2d()中x和y步长都为1,边距保持不变)
    h_pool1 = max_pool_2x2(h_conv1)                             # 输出size 14*14*32
    
    ### 2. 第二层网络
    # 把h_pool1的厚度由32增加到64,长宽由14*14缩小为7*7
    W_conv2 = weight_variable([5, 5, 32, 64]) 
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
    h_pool2 = max_pool_2x2(h_conv2)
    
    ### 3. 第一层全连接
    # 把h_pool2由7*7*64,变成1024*1
    W_fc1 = weight_variable([7*7*64, 1024])
    b_fc1 = bias_variable([1024])
    h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])               # 把pooling后的结构reshape为一维向量
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
    keep_prob = tf.placeholder('float')
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)                   # 按照keep_prob的概率扔掉一些,为了减少过拟合 
    
    ### 4. 第二层全连接
    使用softmax计算概率进行分类, 最后一层网络,1024 -> 10, 
    W_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])
    y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
    
    cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))
    
    sess = tf.Session()
    sess.run(tf.initialize_all_variables())
    for i in range(20000):
        batch = mnist.train.next_batch(50)
        if i % 100 == 0:
            train_accuracy = accuracy.eval(session = sess, feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
            print 'step %d, training accuracy %g' % (i, train_accuracy)
        sess.run(train_step, feed_dict = {x: batch[0], y_: batch[1], keep_prob: 0.5})
    
    print 'test accuracy %g' % accuracy.eval(session = sess, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81

    tf.nn.conv2d到底做了啥?

    参考:http://stackoverflow.com/questions/34619177/what-does-tf-nn-conv2d-do-in-tensorflow

    tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, data_format=None, name=None)

    • input: A Tensor. type必须是以下几种类型之一: half, float32, float64.
    • filter: A Tensor. type和input必须相同
    • strides: A list of ints.一维,长度4, 在input上切片采样时,每个方向上的滑窗步长,必须和format指定的维度同阶
    • padding: A string from: “SAME”, “VALID”. padding 算法的类型
    • use_cudnn_on_gpu: An optional bool. Defaults to True.
    • data_format: An optional string from: “NHWC”, “NCHW”, 默认为”NHWC”。 
      指定输入输出数据格式,默认格式为”NHWC”, 数据按这样的顺序存储: 
      [batch, in_height, in_width, in_channels] 
      也可以用这种方式:”NCHW”, 数据按这样的顺序存储: 
      [batch, in_channels, in_height, in_width]
    • name: 操作名,可选.

    conv2d实际上执行了以下操作:

    1. Flattens the filter to a 2-D matrix with shape 
      [filter_height * filter_width * in_channels, output_channels]
    2. Extracts image patches from the the input tensor to form a virtual tensor of shape 
      [batch, out_height, out_width, filter_height * filter_width * in_channels]
    3. For each patch, right-multiplies the filter matrix and the image patch vector.
    版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pirage/article/details/53187483
  • 相关阅读:
    JavaScript和ASP.NET的传值
    访问webServices时遇到“测试窗体只能用于来自本地计算机的请求”的解决办法
    使用应用程序访问webservice功能
    利用应用程序访问webservice得到远程数据库数据并上传本地数据
    Win7 Wifi和安卓端连接
    Android项目运行junit测试类时出现错误Internal Error (classFileParser.cpp:3494)的解决办法
    安装Android开发工具及环境配置
    怎样修改注册表,让程序开机自动运行[收藏]
    怎么卸载Apache_pn服务PHPnow使用问题
    【转】mssql中大小写的区分
  • 原文地址:https://www.cnblogs.com/developer-ios/p/8649034.html
Copyright © 2011-2022 走看看