第J1周:ResNet-50算法实战与解析

本周任务:

  1. 请根据本文TensorFlow代码,编写出相应的Pytorch代码
  2. 了解残差结构
  3. 是否可以将残差模块融入到C3当中(自由探索)

前期工作

  • 语言环境:Python3.9.18
  • 编译器:Jupyter Lab
  • 深度学习环境:Pytorch 1.12.1

1.设置GPU

import torch
import torch.nn as nn
import torchvision
from torchvision import transforms,datasets

import os,PIL,random,pathlib

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
device

2. 导入数据

data_dir = "F:/365data/J1/bird_photos/"
data_dir = pathlib.Path(data_dir)

data_path = list(data_dir.glob('*'))
classeNames = [str(path).split('\\')[4] for path in data_path]
classeNames
train_transforms = transforms.Compose([
    transforms.Resize([224,224]),
    transforms.ToTensor(),
    transforms.Normalize(
        mean = [0.485,0.456,0.406],
        std = [0.229,0.224,0.225]
    )
])

test_transforms = transforms.Compose([
    transforms.Resize([224,224]),
    transforms.ToTensor(),
    transforms.Normalize(
        mean = [0.485,0.456,0.406],
        std = [0.229,0.224,0.225]
    )
])

total_data = datasets.ImageFolder("F:/365data/J1/bird_photos/",transform = train_transforms)
total_data

3.划分训练集测试集

train_size = int(len(total_data) * 0.8)
test_size = len(total_data) - train_size
train_dataset,test_dataset = torch.utils.data.random_split(total_data,[train_size,test_size])
train_dataset,test_dataset
batch_size = 8

train_dl = torch.utils.data.DataLoader(train_dataset,
                                       batch_size = batch_size,
                                       shuffle = True,
                                       num_workers = 1)

test_dl = torch.utils.data.DataLoader(test_dataset,
                                      batch_size = batch_size,
                                      shuffle = True,
                                      num_workers = 1)
for X,y in test_dl:
    print('Shape of X:',X.shape)
    print('shape of y:',y.shape,y.dtype)
    break

4.数据可视化

import matplotlib.pyplot as plt 
from PIL import Image

image_folder = 'F:/365data/J1/bird_photos/Bananaquit/'

image_files = [f for f in os.listdir(image_folder) if f.endswith(('.jpg','.jpeg','.png'))]

fig,axes = plt.subplots(3,8,figsize=(16,6))

for ax,img_file in zip(axes.flat,image_files):
    img_path = os.path.join(image_folder,img_file)
    img = PIL.Image.open(img_path)
    ax.imshow(img)
    ax.axis('off')

plt.tight_layout()
plt.show()

二、构建ResNet-50模型

1.构造模型

import torch.nn.functional as F
# 构造ResNet50模型
class ResNetblock(nn.Module):
    def __init__(self,in_channels,out_channels,stride=1):
        super(ResNetblock,self).__init__()
        self.blockconv = nn.Sequential(
            nn.Conv2d(in_channels,out_channels,kernel_size=1,stride=stride),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(),
            nn.Conv2d(out_channels,out_channels,kernel_size=3,stride=1,padding=1),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(),
            nn.Conv2d(out_channels,out_channels*4,kernel_size=1,stride=1),
            nn.BatchNorm2d(out_channels*4)
        )
        if stride !=1 or in_channels != out_channels*4:
            self.shortcut = nn.Sequential(
                nn.Conv2d(in_channels,out_channels*4,kernel_size=1,stride=stride),
                nn.BatchNorm2d(out_channels*4)
            )
        
    def forward(self,x):
            residual = x 
            out = self.blockconv(x)
            if hasattr(self,'shortcut'): # 如果self中含有shortcut属性
                residual = self.shortcut(x)
            out += residual
            out = F.relu(out)
            return out
    
class ResNet50(nn.Module):
    def __init__(self,block,num_classes=1000):
          super(ResNet50,self).__init__()

          self.conv1 = nn.Sequential(
               nn.ZeroPad2d(3),
               nn.Conv2d(3,64,kernel_size=7,stride=2),
               nn.BatchNorm2d(64),
               nn.ReLU(),
               nn.MaxPool2d((3,3),stride=2)
          )
          self.in_channels = 64
		  # ResNet50中的四大层,每大层都是由ConvBlock与IdentityBlock堆叠而成
          self.layer1 = self.make_layer(ResNetblock,64,3,stride =1)
          self.layer2 = self.make_layer(ResNetblock,128,4,stride=2)
          self.layer3 = self.make_layer(ResNetblock,256,6,stride=2)
          self.layer4 = self.make_layer(ResNetblock,512,3,stride=2)

          self.avgpool = nn.AvgPool2d((7,7))
          self.fc = nn.Linear(512*4,num_classes)
    # 每个大层的定义函数
    def make_layer(self,block,channels,num_blocks,stride=1):
         strides = [stride] + [1]*(num_blocks-1)
         layers = []
         
         for stride in strides:
              layers.append(block(self.in_channels,channels,stride))
              self.in_channels = channels*4
              
         return nn.Sequential(*layers)
         
    def forward(self,x):
         out = self.conv1(x)
         out = self.layer1(out)
         out = self.layer2(out)
         out = self.layer3(out)
         out = self.layer4(out)
         out = self.avgpool(out)
         out = out.view(out.size(0),-1)
         out = self.fc(out)

         return out
 
model = ResNet50(block=ResNetblock,num_classes=len(classeNames)).to(device)
model

将ResNet50的两个基本块ConvBlock、IdentityBlock通过if条件合并到了一起,当步数不为1或输入特征数≠输出特征数*4时,即为ConvBlock块;反之则为IdentityBlock块。

2. 统计模型参数

# 统计模型参数量以及其他指标
import torchsummary as summary
summary.summary(model, (3, 224, 224))

三、训练模型

1. 构建训练函数

def train(dataloader,model,optimizer,loss_fn):
    size = len(dataloader.dataset)
    num_batches = len(dataloader)

    train_acc,train_loss = 0,0

    for X,y in dataloader:
        X,y = X.to(device),y.to(device)

        pred = model(X)
        loss = loss_fn(pred,y)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        train_loss += loss.item()
        train_acc += (pred.argmax(1) == y).type(torch.float).sum().item()

    train_loss /= num_batches
    train_acc /= size

    return train_acc,train_loss

2. 构建测试函数

def test (dataloader, model, loss_fn):
    size        = len(dataloader.dataset)  # 测试集的大小
    num_batches = len(dataloader)          # 批次数目, (size/batch_size,向上取整)
    test_loss, test_acc = 0, 0
    
    # 当不进行训练时,停止梯度更新,节省计算内存消耗
    with torch.no_grad():
        for imgs, target in dataloader:
            imgs, target = imgs.to(device), target.to(device)
            
            # 计算loss
            target_pred = model(imgs)
            loss        = loss_fn(target_pred, target)
            
            test_loss += loss.item()
            test_acc  += (target_pred.argmax(1) == target).type(torch.float).sum().item()

    test_acc  /= size
    test_loss /= num_batches

    return test_acc, test_loss

3. 优化器和学习率

loss_fn = nn.CrossEntropyLoss()
learn_rate = 1e-3
opt = torch.optim.SGD(model.parameters(),lr=learn_rate)

4. 训练

import copy 

epochs = 10

train_loss=[]
train_acc=[]
test_loss=[]
test_acc=[]
best_acc = 0

for epoch in range(epochs):

    model.train()
    epoch_train_acc,epoch_train_loss = train(train_dl,model,opt,loss_fn)

    model.eval()
    epoch_test_acc,epoch_test_loss = test(test_dl,model,loss_fn)

    if epoch_test_acc > best_acc:
        best_acc = epoch_test_acc
        best_model = copy.deepcopy(model)

    train_acc.append(epoch_train_acc)
    train_loss.append(epoch_train_loss)
    test_acc.append(epoch_test_acc)
    test_loss.append(epoch_test_loss)

    lr = opt.state_dict()['param_groups'][0]['lr']

    template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%, Test_loss:{:.3f}, Lr:{:.2E}')
    print(template.format(epoch+1, epoch_train_acc*100, epoch_train_loss, 
                          epoch_test_acc*100, epoch_test_loss, lr))

# 保存最佳模型到文件中
PATH = 'F:/365data/J1best_model.pth'  # 保存的参数文件名
torch.save(best_model.state_dict(), PATH)

print('Done')
Epoch: 1, Train_acc:26.3%, Train_loss:1.433, Test_acc:19.5%, Test_loss:1.450, Lr:1.00E-03
Epoch: 2, Train_acc:33.8%, Train_loss:1.345, Test_acc:30.1%, Test_loss:1.413, Lr:1.00E-03
Epoch: 3, Train_acc:40.3%, Train_loss:1.307, Test_acc:38.9%, Test_loss:1.271, Lr:1.00E-03
Epoch: 4, Train_acc:48.7%, Train_loss:1.192, Test_acc:48.7%, Test_loss:1.147, Lr:1.00E-03
Epoch: 5, Train_acc:57.3%, Train_loss:1.055, Test_acc:64.6%, Test_loss:0.853, Lr:1.00E-03
Epoch: 6, Train_acc:61.3%, Train_loss:0.950, Test_acc:77.0%, Test_loss:0.663, Lr:1.00E-03
Epoch: 7, Train_acc:60.4%, Train_loss:1.001, Test_acc:74.3%, Test_loss:0.761, Lr:1.00E-03
Epoch: 8, Train_acc:67.3%, Train_loss:0.867, Test_acc:74.3%, Test_loss:0.710, Lr:1.00E-03
Epoch: 9, Train_acc:64.4%, Train_loss:0.905, Test_acc:66.4%, Test_loss:0.800, Lr:1.00E-03
Epoch:10, Train_acc:66.8%, Train_loss:0.810, Test_acc:85.8%, Test_loss:0.655, Lr:1.00E-03
Done

5. 模型评估

import matplotlib.pyplot as plt
#隐藏警告
import warnings
warnings.filterwarnings("ignore")               #忽略警告信息
plt.rcParams['font.sans-serif']    = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False      # 用来正常显示负号
plt.rcParams['figure.dpi']         = 100        #分辨率

epochs_range = range(epochs)

plt.figure(figsize=(12, 3))
plt.subplot(1, 2, 1)

plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, train_loss, label='Training Loss')
plt.plot(epochs_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

在这里插入图片描述

总结

  • 残差块的作用是减少梯度爆炸,以便构造更深层的网络
  • ConvBlock块的跳跃连接中的卷积核的作用是使输出的特征数与主干的特征数一致,这样就能相加了;而IdentityBlock的输入与输出特征数本来就是相同的,所以可以直接相加
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值