alexnet总结
总共八层,作者说层数越多应该效果会更好,但是考虑GPU的计算能力整成八层,作者说任意减掉一层都会是识别效果下降,前俩层有卷积层,局部激活响应归一化lrn,激活函数relu以及池化层,中间俩层只有卷积和激活函数relu,第五层的卷积层只有卷积和池化层,没有lrn和relu,第六七八层又全都是全链接层,最后一层的输出为1000个神经元。
其中使用了relu,dropout,lrn,image patch,pca等方法来优化结果。
具体网络结构如下:
#conv1 (Convolution)kernel size:11 stride:4 pad:0 out_layer:96
#lrn
#relu
#pool1(MAX Pooling)kernel size :3 stride:2 pad:0
#conv2 (Convolution)kernel size:5 stride:1 pad:2 out_layer:256
#lrn
#relu
#pool2(MAX Pooling)kernel size :3 stride:2 pad:0
#conv3(Convolution)kernel size:3 stride:1 pad:1 out_layer:384
#conv4(Convolution)kernel size:3 stride:1 pad:1 out_layer:384
#conv5(Convolution)kernel size:3 stride:1 pad:1 out_layer:256
#pool5(MAX Pooling)kernel size:3 stride:2 pad:0
#fc6
#relu6
#drop6 out 4096
#fc7
#relu7
#drop7 out 4096
#fc8 out 1000
疑问:
1. 输出层数跟其他东西有关系吗??步长
注意事项
1 卷积需要设置的参数
tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, data_format=None, name=None)
W也就是filter
举个例子:
W=(11,11,3,96),11*11为卷积滤波器的高和宽,3为输入的维数,96为输出的维数,96可以理解为有96个这样,同样大小的滤波器,Strides
一般这么设置,strides=[1, k, k, 1],代表以k为步长padding
- “SAME”, “VALID”了俩个选项
- SAME那么卷积后生成的图像大小为 W/k向上取整,即还有剩下的就补全,k为步长,也可以这样理解,如果能够整除,也加一,如果不能整除,反正也要加一,所以可以这么写。
- VALID代表不会再原有的输入的基础上再添加新的像素,卷积后生成的图像大小为(w-f+1)/k向上取整,也可以等于(w-f)/k + 1,可以理解为最后一个填满了减掉11,前面除以步长则为前面的个数,最后再加一则为输出,自行体会哈哈哈
- 实例
假设输入图像为224×224×3,即为input
W=(11,11,3,96)
strides=[1, 4, 4, 1]
padding=same
这样,输出的矩形框的大小就为55×55,227/4 向上取整。
2 ReLUs与Local Response Normalization
收敛效果比tanh,sigmoid快,并且不容易梯度消失,但是,使用ReLU f(x)=max(0,x)后,激活函数后的值没有了区域空间,一般在Relu之后会做一个normalization。思想是找周围n个核的激活函数的值做归一化。具体如下图:
未添加图
3 pooling注意事项
tf.nn.max_pool(value, ksize, strides, padding, data_format=’NHWC’, name=None)
1. value,输入,shape为[batch,height,width,channels]
2. ksize=[1,k_h,k_w,1],pooling核的大小
3. stride=[1,s_h,s_w,1]
4. pading=padding,与上面一致
5. data_format
- 有NHWC,NCHW俩种选择。
- NHWC:[batch, in_height, in_width, in_channels]
- NCHW:[batch, in_channels, in_height, in_width]
4 数据处理
image patch
为了防止过拟合,最简单的方式是增加数据,patch也可以用来扩展数据集。
从256×256中随机提出224×224的patches,一般的patch的方式有:
- Flat
- Linear
- Quadratic
- Edged
另一种方式是利用PCA来扩展数据。
下面是一个alexnet网络来训练手写数字识别的例子
# -*- coding: utf-8 -*-
# 输入数据
import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
import tensorflow as tf
# 定义网络超参数
learning_rate = 0.001
training_iters = 200000
batch_size = 64
display_step = 20
# 定义网络参数
n_input = 784 # 输入的维度
n_classes = 10 # 标签的维度
dropout = 0.8 # Dropout 的概率
# 占位符输入
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_classes])
keep_prob = tf.placeholder(tf.float32)
# 卷积操作
def conv2d(name, l_input, w, b):
return tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(l_input, w, strides=[1, 1, 1, 1], padding='SAME'),b), name=name)
# 最大下采样操作
def max_pool(name, l_input, k):
return tf.nn.max_pool(l_input, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME', name=name)
# 归一化操作
def norm(name, l_input, lsize=4):
return tf.nn.lrn(l_input, lsize, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name=name)
# 定义整个网络
def alex_net(_X, _weights, _biases, _dropout):
# 向量转为矩阵
# 这个是把x的-1维即最后一维,即每一副图像从一维变为28*28*1维的图像
_X = tf.reshape(_X, shape=[-1, 28, 28, 1])
# 卷积层
conv1 = conv2d('conv1', _X, _weights['wc1'], _biases['bc1'])
# 下采样层
pool1 = max_pool('pool1', conv1, k=2)
# 归一化层
norm1 = norm('norm1', pool1, lsize=4)
# Dropout
norm1 = tf.nn.dropout(norm1, _dropout)
# 卷积
conv2 = conv2d('conv2', norm1, _weights['wc2'], _biases['bc2'])
# 下采样
pool2 = max_pool('pool2', conv2, k=2)
# 归一化
norm2 = norm('norm2', pool2, lsize=4)
# Dropout
norm2 = tf.nn.dropout(norm2, _dropout)
# 卷积
conv3 = conv2d('conv3', norm2, _weights['wc3'], _biases['bc3'])
# 下采样
pool3 = max_pool('pool3', conv3, k=2)
# 归一化
norm3 = norm('norm3', pool3, lsize=4)
# Dropout
norm3 = tf.nn.dropout(norm3, _dropout)
# 全连接层,先把特征图转为向量
dense1 = tf.reshape(norm3, [-1, _weights['wd1'].get_shape().as_list()[0]])
dense1 = tf.nn.relu(tf.matmul(dense1, _weights['wd1']) + _biases['bd1'], name='fc1')
# 全连接层
dense2 = tf.nn.relu(tf.matmul(dense1, _weights['wd2']) + _biases['bd2'], name='fc2') # Relu activation
# 网络输出层
out = tf.matmul(dense2, _weights['out']) + _biases['out']
return out
# 存储所有的网络参数
weights = {
'wc1': tf.Variable(tf.random_normal([3, 3, 1, 64])),
'wc2': tf.Variable(tf.random_normal([3, 3, 64, 128])),
'wc3': tf.Variable(tf.random_normal([3, 3, 128, 256])),
'wd1': tf.Variable(tf.random_normal([4096, 1024])),
#'wd1': tf.Variable(tf.random_normal([4\*4\*256, 1024])),
'wd2': tf.Variable(tf.random_normal([1024, 1024])),
'out': tf.Variable(tf.random_normal([1024, 10]))
}
biases = {
'bc1': tf.Variable(tf.random_normal([64])),
'bc2': tf.Variable(tf.random_normal([128])),
'bc3': tf.Variable(tf.random_normal([256])),
'bd1': tf.Variable(tf.random_normal([1024])),
'bd2': tf.Variable(tf.random_normal([1024])),
'out': tf.Variable(tf.random_normal([n_classes]))
}
# 构建模型
pred = alex_net(x, weights, biases, keep_prob)
# 定义损失函数和学习步骤
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# 测试网络
correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# 初始化所有的共享变量
init = tf.initialize_all_variables()
# 开启一个训练
with tf.Session() as sess:
sess.run(init)
step = 1
# Keep training until reach max iterations
#while step \* batch_size < training_iters:
while step * batch_size < training_iters:
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# 获取批数据
sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys, keep_prob: dropout})
if step % display_step == 0:
# 计算精度
acc = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.})
# 计算损失值
loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.})
#print "Iter " + str(step\*batch_size) + ", Minibatch Loss= " + "{:.6f}".format(loss) + ", Training Accuracy= " + "{:.5f}".format(acc)
print "Iter " + str(step*batch_size) + ", Minibatch Loss= " + "{:.6f}".format(loss) + ", Training Accuracy= " + "{:.5f}".format(acc)
step += 1
print "Optimization Finished!"
# 计算测试精度
print "Testing Accuracy:", sess.run(accuracy, feed_dict={x: mnist.test.images[:256], y: mnist.test.labels[:256], keep_prob: 1.})
input_data代码如下:
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Functions for downloading and reading MNIST data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gzip
import os
import tempfile
import numpy
from six.moves import urllib
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets