ResNet 残差网络学习

ResNet 残差网络学习

最近学习ResNet 残差网络,思路大致是首先构建出残差块,然后在添加网络层。先构建最简单的残差块。

Stacks of 2 x (3 x 3) Conv2D-BN-ReLU

残差块结构 2 x (3 x 3) Conv2D-BN-ReLU

def res_block_v1(x, input_filter, output_filter):
    res_x = Conv2D(kernel_size=(3,3), filters=output_filter, strides=1, padding='same')(x)
    res_x = BatchNormalization()(res_x)
    res_x = Activation('relu')(res_x)
    res_x = Conv2D(kernel_size=(3,3), filters=output_filter, strides=1, padding='same')(res_x)
    res_x = BatchNormalization()(res_x)
    if input_filter == output_filter:
        identity = x
    else:
        identity = Conv2D(kernel_size=(1,1), filters=output_filter, strides=1, padding='same')(x)
    x = keras.layers.add([identity, res_x])
    output = Activation('relu')(x)
    return output


然后搭建网络层,以自己实际情况搭建,一般50层以内可采用上面的残差块结构,这里就简易搭建几层

def resnet_v1(x): # x为tensor
    x = Conv2D(kernel_size=(3,3), filters=16, strides=1, padding='same', activation='relu')(x)
    x = res_block_v1(x, 16, 16)
    x = res_block_v1(x, 16, 32)
    x = Flatten()(x)
    outputs = Dense(10, activation='softmax', kernel_initializer='he_normal')(x)
    return outputs

导入训练数据`

import keras
from keras.datasets import cifar10
from keras.layers import Conv2D,Input,BatchNormalization,Activation,Dense,Flatten,MaxPooling2D,Dropout
from keras.optimizers import Optimizer,Adam
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ModelCheckpoint,ReduceLROnPlateau,EarlyStopping
from keras.utils.np_utils import to_categorical

(x_train_src,y_train_src),(x_test_src,y_test_src) = cifar10.load_data()

num_classes = 10
x_train = x_train_src.astype('float32') / 255
x_test = x_test_src.astype('float32') / 255
y_train = to_categorical(y_train_src, num_classes)
y_test = to_categorical(y_test_src, num_classes)

input_shape = x_train.shape[1:]
x = Input(shape=input_shape)
model = Model(x,resnet_v1(x))
model.compile(loss = 'categorical_crossentropy',optimizer=Adam(lr=0.01),metrics=['accuracy'])
model.summary

batch_size = 128
epochs = 200

history = model.fit(x_train, y_train,
                    batch_size=batch_size,
                    epochs=epochs,
                    verbose=1,
                    validation_data=(x_test, y_test))
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值