一.ResNet网络结构分析:
本文以ResNet18为例,分析深度残差网络的内部结构,所有的ResNet网络均先由Basic Block串接成Res Block,随后Res Block再串接成各种各样的ResNet网络。因此首先阐述什么Basic Block,然后说明什么是Res Block,最后讲述一个完整的ResNet网络结构。
1.Basic Block:
如图1所示是一个完整的Basic Block,其中包含2个相同输出通道的卷积层,每个卷积层后接一个批量归一化BN层(Batch Normalization)和ReLU激活函数。然后将输入跳过这两个卷积运算后直接加在最后的ReLU激活函数前。这样的设计要求2个卷积层的输出形状与输入形状一样,从而可以相加。如果想改变通道数,就需要引入一个额外的1*1卷积层来讲输入变换成需要的形状后做相加运算!
为了简化图1,后续Basic Block均表示为图2所,省略掉其中的批量归一化BN层(并不是舍弃BN层,只是在图中不画而已!!!)
2.Res Block:
所谓的Res Block就是将上述的Basic Block串接而已。如图3所示。此时上下两个Basic Block完全一样。Res Block是组成ResNet网络的基本单元。ResNet网络就是由一个个Res Block串接而成。
3.ResNet网络(以ResNet18和ResNet50为例):
ResNet18和ResNet50的网络结构如图4所示。图中包含了每一层的参数和输出。其中,每一层的参数设置均参考原论文,原论文的参数设置如表1所示。18与50代表了网络的层数,以18为例(17个卷积层+1个全连接层)。
二.ResNet18编程实现(采用CIFAR 100数据集)
首先完成ResNet 18网络的搭建,而后利用CIFAR100数据集训练搭建好的网络。网络的搭建程序为resnet.py;网络的训练程序为resnet 18_train.py。ResNet 18网络结构参见表1.
1.resnet.py
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, Sequential
class BasicBlock(layers.Layer):
def __init__(self, filter_num, stride=1):
super(BasicBlock, self).__init__()
self.conv1 = layers.Conv2D(filter_num, (3, 3), strides=stride, padding='same')
self.bn1 = layers.BatchNormalization()
self.relu = layers.Activation('relu')
self.conv2 = layers.Conv2D(filter_num, (3, 3), strides=1, padding='same')
self.bn2 = layers.BatchNormalization()
if stride != 1:
self.downsample = Sequential()
self.downsample.add(layers.Conv2D(filter_num, (1, 1), strides=stride))
#self.downsample = layers.Conv2D(filter_num, (1,1), strides = stride)
else:
self.downsample = lambda x:x
def call(self, inputs, training=None):
# [b, h, w, c]
out = self.conv1(inputs)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
identity = self.downsample(inputs)
output = layers.add([out, identity])
output = tf.nn.relu(output)
return output
class ResNet(keras.Model):
def __init__(self, layer_dims, num_classes=100): # [2, 2, 2, 2]
super(ResNet, self).__init__()
self.stem = Sequential([layers.Conv2D(64, (3, 3), strides=(1, 1)),
layers.BatchNormalization(),
layers.Activation('relu'),
layers.MaxPool2D(pool_size=(2, 2), strides=(1, 1), padding='same')
])
self.layer1 = self.build_resblock(64, layer_dims[0])
self.layer2 = self.build_resblock(128, layer_dims[1], stride=2)
self.layer3 = self.build_resblock(256, layer_dims[2], stride=2)
self.layer4 = self.build_resblock(512, layer_dims[3], stride=2)
# output: [b, 512, h, w],
self.avgpool = layers.GlobalAveragePooling2D()
self.fc = layers.Dense(num_classes)
def build_resblock(self, filter_num, blocks, stride=1):
res_blocks = Sequential()
# may down sample
res_blocks.add(BasicBlock(filter_num, stride))
for _ in range(1, blocks):
res_blocks.add(BasicBlock(filter_num, stride=1))
return res_blocks
def call(self, inputs, training=None):
x = self.stem(inputs)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
# [b, c]
x = self.avgpool(x)
# [b, 100]
x = self.fc(x)
return x
def resnet18():
return ResNet([2, 2, 2, 2])
2.resnet18_train.py
import tensorflow as tf
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
import os
from resnet import resnet18
import datetime
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
tf.random.set_seed(2345)
#图片的预处理
def preprocess(x, y):
# [-1~1],将灰度值变换到[-1,1]防止梯度弥散
x = 2 * tf.cast(x, dtype=tf.float32) / 255. - 1
y = tf.cast(y, dtype=tf.int32)
return x,y
(x,y), (x_test, y_test) = datasets.cifar100.load_data()
y = tf.squeeze(y, axis=1)
y_test = tf.squeeze(y_test, axis=1)
print(x.shape, y.shape, x_test.shape, y_test.shape)
train_db = tf.data.Dataset.from_tensor_slices((x,y))
train_db = train_db.shuffle(1000).map(preprocess).batch(64)
test_db = tf.data.Dataset.from_tensor_slices((x_test,y_test))
test_db = test_db.map(preprocess).batch(64)
sample = next(iter(train_db))
print('sample:', sample[0].shape, sample[1].shape,
tf.reduce_min(sample[0]), tf.reduce_max(sample[0]))
def main():
# [b, 32, 32, 3] => [b, 1, 1, 512]
model = resnet18()
model.build(input_shape=(None, 32, 32, 3))
#查看模型参数
model.summary()
#设置优化器
optimizer = optimizers.Adam(lr=1e-4)
#可视化设置
current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
log_dir = 'logs/' + current_time
summary_writer = tf.summary.create_file_writer(log_dir)
for epoch in range(500):
for step, (x,y) in enumerate(train_db):
with tf.GradientTape() as tape:
# [b, 32, 32, 3] => [b, 100]
logits = model(x)
# [b] => [b, 100]
y_onehot = tf.one_hot(y, depth=100)
# compute loss
loss = tf.losses.categorical_crossentropy(y_onehot, logits, from_logits=True)
loss = tf.reduce_mean(loss)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
if step %50 == 0:
print(epoch, step, 'loss:', float(loss))
with summary_writer.as_default():
tf.summary.scalar('train-loss', float(loss), step=step)
#测试阶段
total_num = 0
total_correct = 0
for x,y in test_db:
logits = model(x)
prob = tf.nn.softmax(logits, axis=1)
pred = tf.argmax(prob, axis=1)
pred = tf.cast(pred, dtype=tf.int32)
correct = tf.cast(tf.equal(pred, y), dtype=tf.int32)
correct = tf.reduce_sum(correct)
total_num += x.shape[0]
total_correct += int(correct)
acc = total_correct / total_num
print(epoch, 'acc:', acc)
if __name__ == '__main__':
main()
3.运行结果
时间原因,只运行了第一个epoch(如图5)+第二个epoch的前500个step(如图6);可视化结果为:如图7。
图5 第一个epoch训练结果 图6 第二个epoch前500step训练结果
图7 loss曲线可视化
3.内存溢出的部分解决方案:
way1:减少batchsize;
way2:调整网络结构:resnet[2,2,2,2]——>resnet[1,1,1,1] (调整之后由于层数发生变化,就不是ResNet18了);
way3:尝试Google CoLab
way4:购买新的显卡