【学习一下】借鉴InceptionNet思想,实现图片分类

  • 2014年,ImageNet挑战赛(ILSVRC14)中,GoogLeNet(InceptionNet v1)获得了第一名、VGG获得了第二名,这两类模型结构的共同特点是层次更深了

InceptionNet 优点

  • InceptionNet通过分支的方式增大网络的宽度和深度能够很好的提高网络的性能,避免过拟合。

    • 一般来说卷积网络要提升表达能力,主要依靠增加输出通道的数量,但是带来的副作用是计算量增大和过拟合。因此InceptionNet采用分支网络堆叠在一起产生较大通道的输出。InceptionNet中产生4个网络(3个卷积和1个池化)对前一层的输出做计算,然后将不同卷积大小的输出在通道上堆叠在一起。卷积、池化后的尺寸相同,将通道相加,一方面增加了网络的宽度,另一方面同时网络中的卷积和大小也不一样,可以增加网络对不同尺度的适应性。
  • InceptionNet分支采用了1*1的卷积网络,1*1卷积的主要目的是为了减少参数,还用于修正线性激活。因为这是一个可以跨通道组织信息,提高网络的表达能力,提供更多的非线性变换。为什么可以减少参数呢?比如,上一层的输出为100*100*128,经过具有256个通道的5*5卷积层之后(stride=1,pad=2),输出数据为100*100*256,其中,卷积层的参数为128*5*5*256= 819200。而假如上一层输出先经过具有32个通道的1*1卷积层,再经过具有256个输出的5*5卷积层,那么输出数据仍为为100*100*256,但卷积参数量已经减少为128*1*1*32 + 32*5*5*256= 204800,大约减少了4倍。

  • InceptionNet为了避免梯度消失,网络额外增加了2个辅助的softmax用于向前传导梯度(辅助分类器)。辅助分类器是将中间某一层的输出用作分类,并按一个较小的权重(0.3)加到最终分类结果中,这样相当于做了模型融合,同时给网络增加了反向传播的梯度信号,也提供了额外的正则化,对于整个网络的训练很有裨益。而在实际测试的时候,这两个额外的softmax会被去掉。

  • 提出并采用了 BatchNormalization(BN)。BN是一种非常有用的正则化方法,可以让卷积网络的训练速度加快很多,同时收敛后的分类准确率也可以提高很多。BN就是神经网络在训练的时候对每个Batch数据的内部进行标准化。BN在某种程度上还起到正则的作用,所以可以减小或者取消Dropout,优化网络结构。同时添加BN后,还需要对超参数做一些调整,增大学速率,加快学习速率的衰减,去除Drought,减轻正则,去除LRN,对样本进行洗牌等等。

  • 网络最后采用了AveragePool来代替全连接层,该想法来自NIN(Network in Network),事实证明这样可以将准确率提高0.6%。但是,实际在最后还是加了一个全连接层,主要是为了方便对输出进行灵活调整。

  • InceptionNet将一个较大的卷积网络拆分成两个小的卷积网络(VGGNet也使用了此思想)。比如将一个 5∗5 的卷积核分成两个 3∗3 的卷积核(作用是一样),这样可以节约大量参数,加速运算并减轻过拟合,同时增加了一层非线性变换拓展了模型的表达能力。

借鉴inceptionNet的思想,实现图片的分类

  • inception_net:原尺寸32*32*3
    • 卷积层:filters=32,kernel_size=(3,3),strides=(1, 1),padding='same',卷积后尺寸:32*32*32
    • 池化层: pool_size=(2,2),strides=(2, 2),padding='same', 池化后尺寸:16*16*32
    • inception_block:[16, 16, 16] inception后的尺寸:16*16*(16+16+16+32)=16*16*80
    • inception_block:[16, 16, 16] inception后的尺寸:16*16*(16+16+16+80)=16*16*128
    • 池化层: pool_size=(2,2),strides=(2, 2),padding='valid', 池化后尺寸:(16-2+1)/2*8*128
    • inception_block:[16, 16, 16] inception后的尺寸:8*8(16+16+16+128)=16*16*176
    • inception_block:[16, 16, 16] inception后的尺寸:16*16*(16+16+16+176)=16*16*224
    • 池化层: pool_size=(2,2),strides=(2, 2),padding='valid', 池化后尺寸:8*8*224
import tensorflow as tf
import os
import pickle
import numpy as np

CIFAR_DIR = "./../cifar-10-batches-py"
print (os.listdir(CIFAR_DIR))
print(tf.__version__)
def load_data(filename):
    """read data from data file."""
    with open(filename, 'rb') as f:
        data = pickle.load(f, encoding='ISO8859-1')
        return data['data'], data['labels']

# tensorflow.Dataset.
class CifarData:
    def __init__(self, filenames, need_shuffle):
        all_data = []
        all_labels = []
        for filename in filenames:
            data, labels = load_data(filename)
            all_data.append(data)
            all_labels.append(labels)
        self._data = np.vstack(all_data)
        self._data = self._data / 127.5 - 1
        self._labels = np.hstack(all_labels)
        print (self._data.shape)
        print (self._labels.shape)
        
        self._num_examples = self._data.shape[0]
        self._need_shuffle = need_shuffle
        self._indicator = 0
        if self._need_shuffle:
            self._shuffle_data()
            
    def _shuffle_data(self):
        # [0,1,2,3,4,5] -> [5,3,2,4,0,1]
        p = np.random.permutation(self._num_examples)
        self._data = self._data[p]
        self._labels = self._labels[p]
    
    def next_batch(self, batch_size):
        """return batch_size examples as a batch."""
        end_indicator = self._indicator + batch_size
        if end_indicator > self._num_examples:
            if self._need_shuffle:
                self._shuffle_data()
                self._indicator = 0
                end_indicator = batch_size
            else:
                raise Exception("have no more examples")
        if end_indicator > self._num_examples:
            raise Exception("batch size is larger than all examples")
        batch_data = self._data[self._indicator: end_indicator]
        batch_labels = self._labels[self._indicator: end_indicator]
        self._indicator = end_indicator
        return batch_data, batch_labels

train_filenames = [os.path.join(CIFAR_DIR, 'data_batch_%d' % i) for i in range(1, 6)]
test_filenames = [os.path.join(CIFAR_DIR, 'test_batch')]

train_data = CifarData(train_filenames, True)
test_data = CifarData(test_filenames, False)
def inception_block(x,
                    output_channel_for_each_path,
                    name):
    """inception block implementation"""
    """
    Args:
    - x:
    - output_channel_for_each_path: eg: [10, 20, 5]
    - name:
    - 图片的宽和高没有改变,通道数改变了(卷积的通道加池化后的通道,池化不改变通道数目)
    """
    with tf.variable_scope(name):
        conv1_1 = tf.layers.conv2d(x,
                                   output_channel_for_each_path[0],
                                   (1, 1),
                                   strides = (1,1),
                                   padding = 'same',
                                   activation = tf.nn.relu,
                                   name = 'conv1_1')
        conv3_3 = tf.layers.conv2d(x,
                                   output_channel_for_each_path[1],
                                   (3, 3),
                                   strides = (1,1),
                                   padding = 'same',
                                   activation = tf.nn.relu,
                                   name = 'conv3_3')
        conv5_5 = tf.layers.conv2d(x,
                                   output_channel_for_each_path[2],
                                   (5, 5),
                                   strides = (1,1),
                                   padding = 'same',
                                   activation = tf.nn.relu,
                                   name = 'conv5_5')
        max_pooling = tf.layers.max_pooling2d(x,
                                              pool_size = (2, 2),
                                              strides = (2, 2),
                                              padding = 'valid',
                                              name = 'max_pooling')
    
    max_pooling_shape = max_pooling.get_shape().as_list()[1:]
    input_shape = x.get_shape().as_list()[1:]
    width_padding  = (input_shape[0] - max_pooling_shape[0]) // 2
    height_padding = (input_shape[1] - max_pooling_shape[1]) // 2
    padded_pooling = tf.pad(max_pooling,
                            [[0, 0],
                             [width_padding, width_padding],
                             [height_padding, height_padding],
                             [0, 0]])
    # concat : 指定轴拼接,其他轴的形状要相同
    concat_layer = tf.concat([conv1_1, conv3_3, conv5_5, padded_pooling],
                             axis = 3)
#     print(conv1_1.get_shape().as_list(),
#           conv3_3.get_shape().as_list(),
#           conv5_5.get_shape().as_list(),
#           padded_pooling.get_shape().as_list(),
#           concat_layer.get_shape().as_list())
    return concat_layer


x = tf.placeholder(tf.float32, [None, 3072])
y = tf.placeholder(tf.int64, [None])
# [None], eg: [0,5,6,3]
x_image = tf.reshape(x, [-1, 3, 32, 32])
# 32*32
x_image = tf.transpose(x_image, perm=[0, 2, 3, 1])

# conv1: 神经元图, feature_map, 输出图像
conv1 = tf.layers.conv2d(x_image,
                         32, # output channel number
                         (3,3), # kernel size
                         strides = (1, 1),
                         padding = 'same',
                         activation = tf.nn.relu,
                         name = 'conv1')

pooling1 = tf.layers.max_pooling2d(conv1,
                                   pool_size = (2, 2), # kernel size
                                   strides = (2, 2), # stride
                                   padding = 'same',
                                   name = 'pool1')

inception_2a = inception_block(pooling1,
                               [16, 16, 16],
                               name = 'inception_2a')
inception_2b = inception_block(inception_2a,
                               [16, 16, 16],
                               name = 'inception_2b')

pooling2 = tf.layers.max_pooling2d(inception_2b,
                                   pool_size = (2, 2), # kernel size
                                   strides = (2, 2), # stride
                                   padding='valid',
                                   name = 'pool2')

inception_3a = inception_block(pooling2,
                               [16, 16, 16],
                               name = 'inception_3a')
inception_3b = inception_block(inception_3a,
                               [16, 16, 16],
                               name = 'inception_3b')

pooling3 = tf.layers.max_pooling2d(inception_3b,
                                   (2, 2), # kernel size
                                   (2, 2), # stride
                                   name = 'pool3')


flatten = tf.layers.flatten(pooling3)
y_ = tf.layers.dense(flatten, 10)

loss = tf.losses.sparse_softmax_cross_entropy(labels=y, logits=y_)

# indices
predict = tf.argmax(y_, 1)
correct_prediction = tf.equal(predict, y)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float64))

with tf.name_scope('train_op'):
    train_op = tf.train.AdamOptimizer(1e-3).minimize(loss)
init = tf.global_variables_initializer()
batch_size = 20
train_steps = 1000
test_steps = 100


with tf.Session() as sess:
    sess.run(init)
    for i in range(train_steps):
        batch_data, batch_labels = train_data.next_batch(batch_size)
        loss_val, acc_val, _ = sess.run(
            [loss, accuracy, train_op],
            feed_dict={
                x: batch_data,
                y: batch_labels})
        if (i+1) % 100 == 0:
            print ('[Train] Step: %d, loss: %4.5f, acc: %4.5f'% (i+1, loss_val, acc_val))
        if (i+1) % 1000 == 0:
            test_data = CifarData(test_filenames, False)
            all_test_acc_val = []
            for j in range(test_steps):
                test_batch_data, test_batch_labels \
                    = test_data.next_batch(batch_size)
                test_acc_val = sess.run(
                    [accuracy],
                    feed_dict = {
                        x: test_batch_data, 
                        y: test_batch_labels
                    })
                all_test_acc_val.append(test_acc_val)
            test_acc = np.mean(all_test_acc_val)
            print ('[Test ] Step: %d, acc: %4.5f' % (i+1, test_acc))