365天深度学习训练营-第P9周:YOLOv5-Backbone模块实现

 我的环境:

  • 语言环境:Python3.11.2
  • 编译器:PyCharm Community Edition 2022.3
  • 深度学习环境:torch==2.0,torchvision==0.15.1 

 本次目标

  • 了解Backbone模块

 一、前期准备

        将数据集导入。

import torch
import torch.nn as nn
from torchvision import transforms,datasets
from torchvision.models import vgg16
import PIL,pathlib,warnings
from torchinfo import summary
import matplotlib.pyplot as plt

data_path='F:\\weather\\weather_photos'
data_path=pathlib.Path(data_path)
data_paths = list(data_path.glob('*'))
classNames = [str(path).split('\\')[2] for path in data_paths]
print(classNames)

        处理数据并划分数据集。

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]
    )
])

total_data =datasets.ImageFolder(data_path, transform=train_transforms)
print(total_data)
print(total_data.class_to_idx)

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

batch_size = 32
train_dl = torch.utils.data.DataLoader(train_dataset,batch_size=batch_size,shuffle=True)
test_dl = torch.utils.data.DataLoader(test_dataset,batch_size=batch_size)

二、构建包含Backbone模块的模型

def autopad(k, p=None):
    if p is None:
        p = k // 2 if isinstance(k, int) else [x // 2 for x in k]  # auto-pad
    return p


class Conv(nn.Module):
    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):
        super().__init__()
        self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
        self.bn = nn.BatchNorm2d(c2)
        self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())

    def forward(self, x):
        return self.act(self.bn(self.conv(x)))


class Bottleneck(nn.Module):
    def __init__(self, c1, c2, shortcut=True, g=1, e=0.5):
        super().__init__()
        c_ = int(c2 * e)
        self.cv1 = Conv(c1, c_, 1, 1)
        self.cv2 = Conv(c_, c2, 3, 1, g=g)
        self.add = shortcut and c1 == c2

    def forward(self, x):
        return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))


class C3(nn.Module):
    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
        super().__init__()
        c_ = int(c2 * e)
        self.cv1 = Conv(c1, c_, 1, 1)
        self.cv2 = Conv(c1, c_, 1, 1)
        self.cv3 = Conv(2 * c_, c2, 1)
        self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))

    def forward(self, x):
        return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))


class SPPF(nn.Module):
    def __init__(self, c1, c2, k=5):
        super().__init__()
        c_ = c1 // 2
        self.cv1 = Conv(c1, c_, 1, 1)
        self.cv2 = Conv(c_ * 4, c2, 1, 1)
        self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)

    def forward(self, x):
        x = self.cv1(x)
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            y1 = self.m(x)
            y2 = self.m(y1)
            return self.cv2(torch.cat([x, y1, y2, self.m(y2)], 1))

class YOLOv5_backbone(nn.Module):
    def __init__(self):
        super(YOLOv5_backbone, self).__init__()

        self.Conv_1 = Conv(3, 64, 3, 2, 2)
        self.Conv_2 = Conv(64, 128, 3, 2)
        self.C3_3 = C3(128, 128)
        self.Conv_4 = Conv(128, 256, 3, 2)
        self.C3_5 = C3(256, 256)
        self.Conv_6 = Conv(256, 512, 3, 2)
        self.C3_7 = C3(512, 512)
        self.Conv_8 = Conv(512, 1024, 3, 2)
        self.C3_9 = C3(1024, 1024)
        self.SPPF = SPPF(1024, 1024, 5)

        self.classifier = nn.Sequential(
            nn.Linear(in_features=65536, out_features=100),
            nn.ReLU(),
            nn.Linear(in_features=100, out_features=4)
        )

    def forward(self, x):
        x = self.Conv_1(x)
        x = self.Conv_2(x)
        x = self.C3_3(x)
        x = self.Conv_4(x)
        x = self.C3_5(x)
        x = self.Conv_6(x)
        x = self.C3_7(x)
        x = self.Conv_8(x)
        x = self.C3_9(x)
        x = self.SPPF(x)

        x = torch.flatten(x, start_dim=1)
        x = self.classifier(x)

        return x

model = YOLOv5_backbone().to("cpu")
summary(model)

'''
======================================================================
Layer (type:depth-idx)                        Param #
======================================================================
YOLOv5_backbone                               --
├─Conv: 1-1                                   --
│    └─Conv2d: 2-1                            1,728
│    └─BatchNorm2d: 2-2                       128
│    └─SiLU: 2-3                              --
├─Conv: 1-2                                   --
│    └─Conv2d: 2-4                            73,728
│    └─BatchNorm2d: 2-5                       256
│    └─SiLU: 2-6                              --
├─C3: 1-3                                     --
│    └─Conv: 2-7                              --
│    │    └─Conv2d: 3-1                       8,192
│    │    └─BatchNorm2d: 3-2                  128
│    │    └─SiLU: 3-3                         --
│    └─Conv: 2-8                              --
│    │    └─Conv2d: 3-4                       8,192
│    │    └─BatchNorm2d: 3-5                  128
│    │    └─SiLU: 3-6                         --
│    └─Conv: 2-9                              --
│    │    └─Conv2d: 3-7                       16,384
│    │    └─BatchNorm2d: 3-8                  256
│    │    └─SiLU: 3-9                         --
│    └─Sequential: 2-10                       --
│    │    └─Bottleneck: 3-10                  41,216
├─Conv: 1-4                                   --
│    └─Conv2d: 2-11                           294,912
│    └─BatchNorm2d: 2-12                      512
│    └─SiLU: 2-13                             --
├─C3: 1-5                                     --
│    └─Conv: 2-14                             --
│    │    └─Conv2d: 3-11                      32,768
│    │    └─BatchNorm2d: 3-12                 256
│    │    └─SiLU: 3-13                        --
│    └─Conv: 2-15                             --
│    │    └─Conv2d: 3-14                      32,768
│    │    └─BatchNorm2d: 3-15                 256
│    │    └─SiLU: 3-16                        --
│    └─Conv: 2-16                             --
│    │    └─Conv2d: 3-17                      65,536
│    │    └─BatchNorm2d: 3-18                 512
│    │    └─SiLU: 3-19                        --
│    └─Sequential: 2-17                       --
│    │    └─Bottleneck: 3-20                  164,352
├─Conv: 1-6                                   --
│    └─Conv2d: 2-18                           1,179,648
│    └─BatchNorm2d: 2-19                      1,024
│    └─SiLU: 2-20                             --
├─C3: 1-7                                     --
│    └─Conv: 2-21                             --
│    │    └─Conv2d: 3-21                      131,072
│    │    └─BatchNorm2d: 3-22                 512
│    │    └─SiLU: 3-23                        --
│    └─Conv: 2-22                             --
│    │    └─Conv2d: 3-24                      131,072
│    │    └─BatchNorm2d: 3-25                 512
│    │    └─SiLU: 3-26                        --
│    └─Conv: 2-23                             --
│    │    └─Conv2d: 3-27                      262,144
│    │    └─BatchNorm2d: 3-28                 1,024
│    │    └─SiLU: 3-29                        --
│    └─Sequential: 2-24                       --
│    │    └─Bottleneck: 3-30                  656,384
├─Conv: 1-8                                   --
│    └─Conv2d: 2-25                           4,718,592
│    └─BatchNorm2d: 2-26                      2,048
│    └─SiLU: 2-27                             --
├─C3: 1-9                                     --
│    └─Conv: 2-28                             --
│    │    └─Conv2d: 3-31                      524,288
│    │    └─BatchNorm2d: 3-32                 1,024
│    │    └─SiLU: 3-33                        --
│    └─Conv: 2-29                             --
│    │    └─Conv2d: 3-34                      524,288
│    │    └─BatchNorm2d: 3-35                 1,024
│    │    └─SiLU: 3-36                        --
│    └─Conv: 2-30                             --
│    │    └─Conv2d: 3-37                      1,048,576
│    │    └─BatchNorm2d: 3-38                 2,048
│    │    └─SiLU: 3-39                        --
│    └─Sequential: 2-31                       --
│    │    └─Bottleneck: 3-40                  2,623,488
├─SPPF: 1-10                                  --
│    └─Conv: 2-32                             --
│    │    └─Conv2d: 3-41                      524,288
│    │    └─BatchNorm2d: 3-42                 1,024
│    │    └─SiLU: 3-43                        --
│    └─Conv: 2-33                             --
│    │    └─Conv2d: 3-44                      2,097,152
│    │    └─BatchNorm2d: 3-45                 2,048
│    │    └─SiLU: 3-46                        --
│    └─MaxPool2d: 2-34                        --
├─Sequential: 1-11                            --
│    └─Linear: 2-35                           6,553,700
│    └─ReLU: 2-36                             --
│    └─Linear: 2-37                           404
======================================================================
Total params: 21,729,592
Trainable params: 21,729,592
Non-trainable params: 0
======================================================================
'''

三、训练模型

        设置超参数。

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

        编写训练函数和测试函数。

def train(dataloader,model,loss_fn,optimizer):
    size = len(dataloader.dataset)
    num_batchs = len(dataloader)
    train_loss, train_acc = 0, 0
    for X,y in dataloader:
        pred=model(X)
        loss=loss_fn(pred,y)

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

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

    return train_acc,train_loss

def test(dataloader,model,loss_fn):
    size=len(dataloader.dataset)
    num_batchs=len(dataloader)
    test_loss,test_acc=0,0

    with torch.no_grad():
        for imgs,target in dataloader:

            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_batchs

    return test_acc,test_loss

        正式训练。

epochs=20
train_loss=[]
train_acc=[]
test_loss=[]
test_acc=[]

for epoch in range(epochs):
    model.train()
    epoch_train_acc,epoch_train_loss= train(train_dl,model,loss_fn,opt)
    model.eval()
    epoch_test_acc,epoch_test_loss=test(test_dl,model, loss_fn)
    train_acc.append(epoch_train_acc)
    train_loss.append(epoch_train_loss)
    test_acc.append(epoch_test_acc)
    test_loss.append(epoch_test_loss)

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

四、结果可视化

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='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

五、指定图片进行预测 

classes = list(total_data.class_to_idx)
def predict_one_img(image_path, model, transform, classes):
    test_img = PIL.Image.open(image_path).convert('RGB')
    test_img=transform(test_img)
    img = test_img.to('cpu').unsqueeze(0)
    model.eval()
    output = model(img)
    x,pred = torch.max(output,1)
    pred_class=classes[pred]
    print(f'预测结果是{pred_class}')
predict_one_img(image_path='F:\\weather_photos\\cloudy\\cloudy1.jpg',model=model,transform=train_transforms,classes=classes)

        保存模型参数

PATH = './model.pth'
torch.save(model.state_dict(),PATH)

model.load_state_dict(torch.load(PATH))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值