前言::LeNet是最早用于数字识别的CNN网络,本文就以数字识别为例,分析下这个最基本的CNN网络。
网络结构如下图所示:
def le_net(x, y):
# 1. 输入层
with tf.variable_scope('input1'):
# 将输入的x的格式转换为规定的格式
# [None, input_dim] -> [None, height, weight, channels]
net = tf.reshape(x, shape=[-1, 28, 28, 1])
# 2. 卷积层
with tf.variable_scope('conv2'):
# 卷积
# conv2d(input, filter, strides, padding, use_cudnn_on_gpu=True, data_format="NHWC", name=None) => 卷积的API
# data_format: 表示的是输入的数据格式,两种:NHWC和NCHW,N=>样本数目,H=>Height, W=>Weight, C=>Channels
# input:输入数据,必须是一个4维格式的图像数据,具体格式和data_format有关,如果data_format是NHWC的时候,input的格式为: [batch_size, height, weight, channels] => [批次中的图片数目,图片的高度,图片的宽度,图片的通道数];如果data_format是NCHW的时候,input的格式为: [batch_size, channels, height, weight] => [批次中的图片数目,图片的通道数,图片的高度,图片的宽度]
# filter: 卷积核,是一个4维格式的数据,shape: [height, weight, in_channels, out_channels] => [窗口的高度,窗口的宽度,输入的channel通道数(上一层图片的深度),输出的通道数(卷积核数目)]
# strides:步长,是一个4维的数据,每一维数据必须和data_format格式匹配,表示的是在data_format每一维上的移动步长,当格式为NHWC的时候,strides的格式为: [batch, in_height, in_weight, in_channels] => [样本上的移动大小,高度的移动大小,宽度的移动大小,深度的移动大小],要求在样本上和在深度通道上的移动必须是1;当格式为NCHW的时候,strides的格式为: [batch,in_channels, in_height, in_weight]
# padding: 只支持两个参数"SAME", "VALID",当取值为SAME的时候,表示进行填充,"在TensorFlow中,如果步长为1,并且padding为SAME的时候,经过卷积之后的图像大小是不变的";当VALID的时候,表示多余的特征会丢弃;
net = tf.nn.conv2d(input=net, filter=get_variable('w', [5, 5, 1, 20]), strides=[1, 1, 1, 1], padding='SAME')
net = tf.nn.bias_add(net, get_variable('b', [20]))
# 激励 ReLu
# tf.nn.relu => max(fetures, 0)
# tf.nn.relu6 => min(max(fetures,0), 6)
net = tf.nn.relu(net)
# 3. 池化
with tf.variable_scope('pool3'):
# 和conv2一样,需要给定窗口大小和步长
# max_pool(value, ksize, strides, padding, data_format="NHWC", name=None)
# avg_pool(value, ksize, strides, padding, data_format="NHWC", name=None)
# 默认格式下:NHWC,value:输入的数据,必须是[batch_size, height, weight, channels]格式
# 默认格式下:NHWC,ksize:指定窗口大小,必须是[batch, in_height, in_weight, in_channels], 其中batch和in_channels必须为1
# 默认格式下:NHWC,strides:指定步长大小,必须是[batch, in_height, in_weight, in_channels],其中batch和in_channels必须为1
# padding: 只支持两个参数"SAME", "VALID",当取值为SAME的时候,表示进行填充,;当VALID的时候,表示多余的特征会丢弃;
net = tf.nn.max_pool(value=net, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# 4. 卷积
with tf.variable_scope('conv4'):
net = tf.nn.conv2d(input=net, filter=get_variable('w', [5, 5, 20, 50]), strides=[1, 1, 1, 1], padding='SAME')
net = tf.nn.bias_add(net, get_variable('b', [50]))
net = tf.nn.relu(net)
# 5. 池化
with tf.variable_scope('pool5'):
net = tf.nn.max_pool(value=net, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# 6. 全连接
with tf.variable_scope('fc6'):
# 28 -> 14 -> 7(因为此时的卷积不改变图片的大小)
net = tf.reshape(net, shape=[-1, 7 * 7 * 50])
net = tf.add(tf.matmul(net, get_variable('w', [7 * 7 * 50, 500])), get_variable('b', [500]))
net = tf.nn.relu(net)
# 7. 全连接
with tf.variable_scope('fc7'):
net = tf.add(tf.matmul(net, get_variable('w', [500, n_classes])), get_variable('b', [n_classes]))
act = tf.nn.softmax(net)
return act
详细代码可以从我的github网站下载:https://github.com/dctongsheng/Lenet/upload