第J2周:ResNet50V2算法实战与解析
🍨 本文为🔗365天深度学习训练营365天深度学习训练营 中的学习记录博客
🍦 参考文章:365天深度学习训练营-第J2周:ResNet50V2算法实战与解析
🍖 原作者:K同学啊 | 接辅导、项目定制
🚀 文章来源:K同学的学习圈子
学习目标:
1.根据TensorFlow代码,编写出相应的Pytorch代码
2.了解ResNetV2与ResNetV的区别
我的环境
语言环境:python:3.7
编译器:jupytoer notebook
深度学习环境:Pytorch
torch == 2.0.1+cu117
数据的加载和预处理和J1相同
‘’’' Residual Block '''
class Block2(nn.Module):
def __init__(self, in_channel, filters, kernel_size=3, stride=1, conv_shortcut=False):
super(Block2, self).__init__()
self.preact = nn.Sequential(
nn.BatchNorm2d(in_channel),
nn.ReLU(True)
)
self.shortcut = conv_shortcut
if self.shortcut:
self.short = nn.Conv2d(in_channel, 4*filters, 1, stride=stride, padding=0, bias=False)
elif stride>1:
self.short = nn.MaxPool2d(kernel_size=1, stride=stride, padding=0)
else:
self.short = nn.Identity()
self.conv1 = nn.Sequential(
nn.Conv2d(in_channel, filters, 1, stride=1, bias=False),
nn.BatchNorm2d(filters),
nn.ReLU(True)
)
self.conv2 = nn.Sequential(
nn.Conv2d(filters, filters, kernel_size, stride=stride, padding=1, bias=False),
nn.BatchNorm2d(filters),
nn.ReLU(True)
)
self.conv3 = nn.Conv2d(filters, 4*filters, 1, stride=1, bias=False)
def forward(self, x):
x1 = self.preact(x)
if self.shortcut:
x2 = self.short(x1)
else:
x2 = self.short(x)
x1 = self.conv1(x1)
x1 = self.conv2(x1)
x1 = self.conv3(x1)
x = x1 + x2
return x
class Stack2(nn.Module):
def __init__(self, in_channel, filters, blocks, stride=2):
super(Stack2, self).__init__()
self.conv = nn.Sequential()
self.conv.add_module(str(0), Block2(in_channel, filters, conv_shortcut=True))
for i in range(1, blocks-1):
self.conv.add_module(str(i), Block2(4*filters, filters))
self.conv.add_module(str(blocks-1), Block2(4*filters, filters, stride=stride))
def forward(self, x):
x = self.conv(x)
return x
''' 构建ResNet50V2 '''
class ResNet50V2(nn.Module):
def __init__(self,
include_top=True, # 是否包含位于网络顶部的全链接层
preact=True, # 是否使用预激活
use_bias=True, # 是否对卷积层使用偏置
input_shape=[224, 224, 3],
classes=4,
pooling=None): # 用于分类图像的可选类数
super(ResNet50V2, self).__init__()
self.conv1 = nn.Sequential()
self.conv1.add_module('conv', nn.Conv2d(3, 64, 7, stride=2, padding=3, bias=use_bias, padding_mode='zeros'))
if not preact:
self.conv1.add_module('bn', nn.BatchNorm2d(64))
self.conv1.add_module('relu', nn.ReLU())
self.conv1.add_module('max_pool', nn.MaxPool2d(kernel_size=3, stride=2, padding=1))
self.conv2 = Stack2(64, 64, 3)
self.conv3 = Stack2(256, 128, 4)
self.conv4 = Stack2(512, 256, 6)
self.conv5 = Stack2(1024, 512, 3, stride=1)
self.post = nn.Sequential()
if preact:
self.post.add_module('bn', nn.BatchNorm2d(2048))
self.post.add_module('relu', nn.ReLU())
if include_top:
self.post.add_module('avg_pool', nn.AdaptiveAvgPool2d((1, 1)))
self.post.add_module('flatten', nn.Flatten())
self.post.add_module('fc', nn.Linear(2048, classes))
else:
if pooling=='avg':
self.post.add_module('avg_pool', nn.AdaptiveAvgPool2d((1, 1)))
elif pooling=='max':
self.post.add_module('max_pool', nn.AdaptiveMaxPool2d((1, 1)))
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.conv4(x)
x = self.conv5(x)
x = self.post(x)
return x
model = ResNet50V2().to(device)
#设置学习率
learn_rate = 1e-3
# 设置优化器
optimizer = torch.optim.Adam(model.parameters(),lr=learn_rate)
# 设置损失函数
loss_fun = nn.CrossEntropyLoss()
# 设置epoch
epochs = 40
#试化列表来存储训练和验证的准确率和损失值
train_acc = []
val_acc=[]
train_loss=[]
val_loss = []
for epoch in range(epochs):
# 训练阶段
model.train()
running_loss = 0.0
acc = 0
for data,label in train_dl:
data, label = data.to(device), label.to(device)
optimizer.zero_grad()
# print(pred_out.shape)
# print(label.shape)
pred_out = model(data)
loss = loss_fun(pred_out, label)
loss.backward()
optimizer.step()
running_loss += loss.item()
_,predicted = torch.max(pred_out.data,1)
acc += (predicted == label).sum().item()
epoch_loss = running_loss / len(train_dl)
epoch_acc = acc/len(train_dl.dataset)
train_loss.append(epoch_loss)
train_acc.append(epoch_acc)
#验证阶段
model.eval()
running_loss = 0.0
acc = 0
with torch.no_grad():
for data, label in test_dl:
data, label = data.to(device), label.to(device)
output = model(data)
loss = loss_fun(output,label)
running_loss += loss.item()
_,predicted = torch.max(output.data,1)
acc += (predicted == label).sum().item()
epoch_loss = running_loss/len(test_dl)
epoch_acc = acc/len(test_dl.dataset)
val_acc.append(epoch_acc)
val_loss.append(epoch_loss)
print('Epoch{}/{},Train_loss:{:.4f}, Train_acc:{:.2f}, Val_loss:{:.4f}, Val_acc:{:.2f}'
.format(epoch+1,epochs,train_loss[-1],train_acc[-1]*100, val_loss[-1],val_acc[-1]*100))
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] =False
plt.rcParams['figure.dpi'] = 100
plt.figure(figsize = (12,3))
plt.subplot(1,2,1)
plt.plot(range(epochs), train_acc, label='Training Accuracy')
plt.plot(range(epochs), val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1,2,2)
plt.plot(range(epochs), train_loss, label='Training Loss')
plt.plot(range(epochs), val_loss, label='Validation loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
总结
简单的知道模型是如何进行设计和逐步的改进。根据前一周的对代码的编写有了更进一步的熟悉。从图中可以看出模型的叠戴速度很快,准确率较高,但是有明显的过拟合现象,需要进一步探索。