InceptionNet tensorflow实战(CIFAR10数据集)

 

从VGGNet拓展出来的

 

import tensorflow as tf
import os
import pickle
import numpy as np


def load_data(filename):
    """read data from data file."""
    with open(filename, 'rb') as f:
        data = pickle.load(f, encoding='bytes')
        return data[b'data'], data[b'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


CIFAR_DIR = "dataset/cifar-10-batches-py"
print(os.listdir(CIFAR_DIR))

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,
                                              (2, 2),
                                              (2, 2),
                                              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_layer = tf.concat(
        [conv1_1, conv3_3, conv5_5, padded_pooling],
        axis=3)
    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
                         padding='same',
                         activation=tf.nn.relu,
                         name='conv1')

pooling1 = tf.layers.max_pooling2d(conv1,
                                   (2, 2),  # kernel size
                                   (2, 2),  # stride
                                   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,
                                   (2, 2),  # kernel size
                                   (2, 2),  # stride
                                   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_)
# y_ -> sofmax
# y -> one_hot
# loss = ylogy_

# indices
predict = tf.argmax(y_, 1)
# [1,0,1,1,1,0,0,0]
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 = 10000
test_steps = 100

# train 10k: 74.65%
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))

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是使用TensorFlow在CIFAR数据集上验证GoogLeNet神经网络性能的步骤: 1. 下载CIFAR数据集并解压缩,可以使用以下代码: ```python import tensorflow as tf from tensorflow.keras.datasets import cifar10 (x_train, y_train), (x_test, y_test) = cifar10.load_data() # Normalize pixel values to be between 0 and 1 x_train, x_test = x_train / 255.0, x_test / 255.0 ``` 2. 构建GoogLeNet模型,可以使用以下代码: ```python from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, Dense, Conv2D, MaxPooling2D, AveragePooling2D, Dropout, Flatten, concatenate def inception_module(prev_layer, filters): # 1x1 convolution conv1 = Conv2D(filters[0], (1,1), padding='same', activation='relu')(prev_layer) # 3x3 convolution conv3 = Conv2D(filters[1], (3,3), padding='same', activation='relu')(prev_layer) # 5x5 convolution conv5 = Conv2D(filters[2], (5,5), padding='same', activation='relu')(prev_layer) # Max pooling pool = MaxPooling2D((3,3), strides=(1,1), padding='same')(prev_layer) pool_conv = Conv2D(filters[3], (1,1), padding='same', activation='relu')(pool) # Concatenate all filters concat = concatenate([conv1, conv3, conv5, pool_conv], axis=-1) return concat def googlenet(input_shape, num_classes): inputs = Input(shape=input_shape) # First convolutional layer x = Conv2D(64, (7,7), strides=(2,2), padding='same', activation='relu')(inputs) x = MaxPooling2D((3,3), strides=(2,2), padding='same')(x) # Second convolutional layer x = Conv2D(192, (3,3), strides=(1,1), padding='same', activation='relu')(x) x = MaxPooling2D((3,3), strides=(2,2), padding='same')(x) # First inception module x = inception_module(x, filters=[64, 96, 128, 16, 32, 32]) # Second inception module x = inception_module(x, filters=[128, 128, 192, 32, 96, 64]) # Third inception module x = inception_module(x, filters=[192, 96, 208, 16, 48, 64]) # Max pooling layer x = MaxPooling2D((3,3), strides=(2,2), padding='same')(x) # Fourth inception module x = inception_module(x, filters=[160, 112, 224, 24, 64, 64]) # Fifth inception module x = inception_module(x, filters=[128, 128, 256, 24, 64, 64]) # Sixth inception module x = inception_module(x, filters=[112, 144, 288, 32, 64, 64]) # Seventh inception module x = inception_module(x, filters=[256, 160, 320, 32, 128, 128]) # Max pooling layer x = MaxPooling2D((3,3), strides=(2,2), padding='same')(x) # Eighth inception module x = inception_module(x, filters=[256, 160, 320, 32, 128, 128]) # Ninth inception module x = inception_module(x, filters=[384, 192, 384, 48, 128, 128]) # Dropout layer x = Dropout(0.4)(x) # Flatten layer x = Flatten()(x) # Fully connected layer outputs = Dense(num_classes, activation='softmax')(x) model = Model(inputs=inputs, outputs=outputs) return model ``` 3. 编译和训练模型,可以使用以下代码: ```python model = googlenet(input_shape=(32, 32, 3), num_classes=10) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) history = model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test)) ``` 4. 评估模型性能,可以使用以下代码: ```python test_loss, test_acc = model.evaluate(x_test, y_test) print('Test accuracy:', test_acc) ``` 以上就是使用tensorflow框架在cifar数据集上验证googlenet神经网络性能的步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值