ResNet18是一个经典的深度卷积神经网络模型,由微软亚洲研究院提出,用于参加2015年的ImageNet图像分类比赛。ResNet18的名称来源于网络中包含的18个卷积层。
ResNet18的基本结构如下:
向量。
ResNet18的主要特点是引入了残差块(Residual Block)的概念,用于解决深度卷积神经网络中梯度消失和梯度爆炸问题。在残差块中,跳跃连接(Shortcut Connection)可以将输入直接连接到输出,使得网络可以学习到残差信息,从而更好地进行特征提取和处理。
在训练过程中,ResNet18一般采用基于随机梯度下降(Stochastic Gradient Descent,SGD)的反向传播算法,通过最小化交叉熵损失函数来优化模型参数。在训练过程中,可以使用数据增强、正则化、dropout等技术来提高模型的泛化能力和鲁棒性。
总的来说,ResNet18是一个非常经典和有效的深度卷积神经网络模型,具有良好的特征提取和分类能力,可以应用于图像分类、目标检测等计算机视觉任务。
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers,datasets,models
def main():
(train_x,train_y),(test_x,test_y) = datasets.cifar10.load_data()
train_x = train_x.reshape([-1,32,32,3]) / 255.0
test_x = test_x.reshape([-1,32,32,3]) / 255.0
inputs = keras.Input((32,32,3))
output = ResNet18(inputs)
model = models.Model(inputs,output)
model.summary()
model.compile(loss = keras.losses.SparseCategoricalCrossentropy(),
optimizer=keras.optimizers.Adam(0.01),
metrics=['accuracy'])
model.fit(train_x,train_y,batch_size=128,epochs=10)
score = model.evaluate(test_x,test_y)
print("loss:",score[0])
print("acc:",score[1])
pass
def ConvCall(x,filtten,xx,yy,strides = (1,1)):
x = layers.Conv2D(filtten,(xx,yy),strides=strides,padding='same')(x)
x = layers.BatchNormalization()(x)
return x
def ResNetblock(input,filtten,strides = (1,1)):
x = ConvCall(input,filtten,3,3,strides=strides)
x = layers.Activation("relu")(x)
x = ConvCall(x,filtten,3,3,strides=(1,1))
if strides != (1,1):
residual = ConvCall(input,filtten,1,1,strides=strides)
else:
residual = input
x = x + residual
x = layers.Activation("relu")(x)
return x
def ResNet18(inputs):
x = ConvCall(inputs, 64, 3, 3, strides=(1, 1))
x = layers.Activation('relu')(x)
x = ResNetblock(x, 64, strides=(1, 1))
x = ResNetblock(x, 64, strides=(1, 1))
x = ResNetblock(x, 128, strides=(2, 2))
x = ResNetblock(x, 128, strides=(1, 1))
x = ResNetblock(x, 256, strides=(2, 2))
x = ResNetblock(x, 256, strides=(1, 1))
x = ResNetblock(x, 512, strides=(2, 2))
x = ResNetblock(x, 512, strides=(1, 1))
x = layers.GlobalAveragePooling2D()(x) # 全局平均池化
output = layers.Dense(10, "softmax")(x)
return output
if __name__ == '__main__':
main()