【學(xué)習(xí)一下】借鑒InceptionNet思想,實(shí)現(xiàn)圖片分類

  • 2014年,ImageNet挑戰(zhàn)賽(ILSVRC14)中,GoogLeNet(InceptionNet v1)獲得了第一名、VGG獲得了第二名,這兩類模型結(jié)構(gòu)的共同特點(diǎn)是層次更深了

InceptionNet 優(yōu)點(diǎn)

  • InceptionNet通過分支的方式增大網(wǎng)絡(luò)的寬度和深度能夠很好的提高網(wǎng)絡(luò)的性能,避免過擬合。

    • 一般來說卷積網(wǎng)絡(luò)要提升表達(dá)能力,主要依靠增加輸出通道的數(shù)量,但是帶來的副作用是計(jì)算量增大和過擬合。因此InceptionNet采用分支網(wǎng)絡(luò)堆疊在一起產(chǎn)生較大通道的輸出。InceptionNet中產(chǎn)生4個(gè)網(wǎng)絡(luò)(3個(gè)卷積和1個(gè)池化)對(duì)前一層的輸出做計(jì)算,然后將不同卷積大小的輸出在通道上堆疊在一起。卷積、池化后的尺寸相同,將通道相加,一方面增加了網(wǎng)絡(luò)的寬度,另一方面同時(shí)網(wǎng)絡(luò)中的卷積和大小也不一樣,可以增加網(wǎng)絡(luò)對(duì)不同尺度的適應(yīng)性。
  • InceptionNet分支采用了1*1的卷積網(wǎng)絡(luò),1*1卷積的主要目的是為了減少參數(shù),還用于修正線性激活。因?yàn)檫@是一個(gè)可以跨通道組織信息,提高網(wǎng)絡(luò)的表達(dá)能力,提供更多的非線性變換。為什么可以減少參數(shù)呢?比如,上一層的輸出為100*100*128,經(jīng)過具有256個(gè)通道的5*5卷積層之后(stride=1,pad=2),輸出數(shù)據(jù)為100*100*256,其中,卷積層的參數(shù)為128*5*5*256= 819200。而假如上一層輸出先經(jīng)過具有32個(gè)通道的1*1卷積層,再經(jīng)過具有256個(gè)輸出的5*5卷積層,那么輸出數(shù)據(jù)仍為為100*100*256,但卷積參數(shù)量已經(jīng)減少為128*1*1*32 + 32*5*5*256= 204800,大約減少了4倍。

  • InceptionNet為了避免梯度消失,網(wǎng)絡(luò)額外增加了2個(gè)輔助的softmax用于向前傳導(dǎo)梯度(輔助分類器)。輔助分類器是將中間某一層的輸出用作分類,并按一個(gè)較小的權(quán)重(0.3)加到最終分類結(jié)果中,這樣相當(dāng)于做了模型融合,同時(shí)給網(wǎng)絡(luò)增加了反向傳播的梯度信號(hào),也提供了額外的正則化,對(duì)于整個(gè)網(wǎng)絡(luò)的訓(xùn)練很有裨益。而在實(shí)際測(cè)試的時(shí)候,這兩個(gè)額外的softmax會(huì)被去掉。

  • 提出并采用了 BatchNormalization(BN)。BN是一種非常有用的正則化方法,可以讓卷積網(wǎng)絡(luò)的訓(xùn)練速度加快很多,同時(shí)收斂后的分類準(zhǔn)確率也可以提高很多。BN就是神經(jīng)網(wǎng)絡(luò)在訓(xùn)練的時(shí)候?qū)γ總€(gè)Batch數(shù)據(jù)的內(nèi)部進(jìn)行標(biāo)準(zhǔn)化。BN在某種程度上還起到正則的作用,所以可以減小或者取消Dropout,優(yōu)化網(wǎng)絡(luò)結(jié)構(gòu)。同時(shí)添加BN后,還需要對(duì)超參數(shù)做一些調(diào)整,增大學(xué)速率,加快學(xué)習(xí)速率的衰減,去除Drought,減輕正則,去除LRN,對(duì)樣本進(jìn)行洗牌等等。

  • 網(wǎng)絡(luò)最后采用了AveragePool來代替全連接層,該想法來自NIN(Network in Network),事實(shí)證明這樣可以將準(zhǔn)確率提高0.6%。但是,實(shí)際在最后還是加了一個(gè)全連接層,主要是為了方便對(duì)輸出進(jìn)行靈活調(diào)整。

  • InceptionNet將一個(gè)較大的卷積網(wǎng)絡(luò)拆分成兩個(gè)小的卷積網(wǎng)絡(luò)(VGGNet也使用了此思想)。比如將一個(gè) 5?5 的卷積核分成兩個(gè) 3?3 的卷積核(作用是一樣),這樣可以節(jié)約大量參數(shù),加速運(yùn)算并減輕過擬合,同時(shí)增加了一層非線性變換拓展了模型的表達(dá)能力。

借鑒inceptionNet的思想,實(shí)現(xiàn)圖片的分類

  • 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:
    - 圖片的寬和高沒有改變,通道數(shù)改變了(卷積的通道加池化后的通道,池化不改變通道數(shù)目)
    """
    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: 神經(jīng)元圖, 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))
                
                
            
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容