tensorflow CNN卷积神经网络

来源:互联网 发布:mac dd bs 编辑:程序博客网 时间:2024/05/23 01:19

    • 卷积神经网络CNNConvlutional Network

卷积神经网络CNN(Convlutional Network)

http://blog.csdn.net/pirage/article/details/53187483

https://news.uc.cn/a_10094573562509432898/

平移不变形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) 取切片的最大值
- mean pooling : y=mean(xi) 取切片的平均值
1×1 convolutions

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

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

inception

YANN LECUN’98 发表的一个经典CNN模型 LENET-5image -> 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 tffrom tensorflow.examples.tutorials.mnist import input_datamnist = 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=7841表示颜色通道数目y_ = tf.placeholder(tf.float32, [None, 10])### 1. 第一层网络# 把x_image的厚度由1增加到32,长宽由28*28缩小为14*14W_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*7W_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*1W_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})

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实际上执行了以下操作:

Flattens the filter to a 2-D matrix with shape[filter_height * filter_width * in_channels, output_channels]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]For each patch, right-multiplies the filter matrix and the image patch vector.
原创粉丝点击