Pytorch实战 | P8 YOLOv5-C3模块实现天气图片识别

● 本文为365天深度学习训练营 中的学习记录博客
● 参考文章:Pytorch实战 | 第P8天:YOLOv5-C3模块实现天气图片识别
● 原作者:K同学啊|接辅导、项目定制

一、我的环境

● 语言环境:Python3.8
● 编译器:pycharm
● 深度学习环境:Pytorch
● 数据来源:链接: https://pan.baidu.com/s/1SEfd8mvWt7BpzmWOeaIRkQ 提取码: gdie

二、主要代码实现

1、main.py

# -*- coding: utf-8 -*-
import copy

import torch.utils.data
from torchvision import transforms, datasets
from model import model_K, train, test
import torch.nn as nn
import torchsummary as summary

# 1、导入并处理和转换数据

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/', train_transforms)
# 划分数据集
train_size = int(len(total_data) * 0.8)
test_size = len(total_data) - train_size
train_data, test_data = torch.utils.data.random_split(total_data, [train_size, test_size])

batch_size = 32
train_dl = torch.utils.data.DataLoader(train_data, batch_size=batch_size, shuffle=True)
test_dl = torch.utils.data.DataLoader(test_data, batch_size=batch_size, shuffle=True)

for X, y in test_dl:
    print("Shape of X [N, C, H, W]: ", X.shape)
    print("Shape of y: ", y.shape, y.dtype)
    break

# 2、构建网络模型 model.py

# 3、模型训练
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print("Using {} device".format(device))

model = model_K().to(device)

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

optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)
loss_fn = nn.CrossEntropyLoss()

epochs = 20

train_loss = []
train_acc = []
test_loss = []
test_acc = []

best_acc = 0
best_model = None

for epoch in range(epochs):
    model.train()
    epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, optimizer, device)

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

    # 保存最佳模型
    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 = optimizer.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))

# 保存最佳模型
torch.save(model.state_dict(), './model/model.pth')
print('Done')

# 4、模型评估
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()

model.py

# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import torch.nn as nn
import torch
from PIL import Image


def autopad(k, p=None):  # kernel, padding
    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):
    # standard convolution
    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):  # input, output, kernel
        super(Conv, self).__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):
    # standard bottleneck
    def __init__(self, c1, c2, shortcut=True, g=1, e=0.5):  # input, output shorcut, groups, expansion
        super(Bottleneck, self).__init__()
        c_ = int(c2 * e)  # hidden channels
        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):
    # CSP Bottleneck with 3 convolutions
    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):  # input, output, number, shortcut, groups, expansion
        super(C3, self).__init__()
        c_ = int(c2 * e)  # hidden channels
        self.cv1 = Conv(c1, c_, 1, 1)
        self.cv2 = Conv(c1, c_, 1, 1)
        self.cv3 = Conv(2 * c_, c2, 1)  # act = FReLU(c2)
        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 model_K(nn.Module):
    def __init__(self):
        super(model_K, self).__init__()

        # 卷积模块
        self.Conv = Conv(3, 32, 3, 2)

        # C3模块1
        self.C3_1 = C3(32, 64, 3, 2)

        # 全连接网络层,用于分类
        self.classifier = nn.Sequential(
            nn.Linear(in_features=802816, out_features=100),
            nn.ReLU(),
            nn.Linear(in_features=100, out_features=4)
        )

    def forward(self, x):
        x = self.Conv(x)
        x = self.C3_1(x)
        x = torch.flatten(x, start_dim=1)
        x = self.classifier(x)

        return x


def train(dataloader, model, loss_fn, optimizer, device):
    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_acc += (pred.argmax(1) == y).type(torch.float).sum().item()
        train_loss += loss.item()

    size = len(dataloader.dataset)  # 训练集的大小
    num_batch = len(dataloader)

    train_acc /= size
    train_loss /= num_batch

    return train_acc, train_loss


def test(dataloader, model, loss_fn, device):
    test_acc, test_loss = 0, 0
    # 停止梯度更新
    with torch.no_grad():
        for imgs, target in dataloader:
            imgs, target = imgs.to(device), target.to(device)

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

    size = len(dataloader.dataset)
    num_batch = len(dataloader)
    test_acc /= size
    test_loss /= num_batch

    return test_acc, test_loss


def predict(model, img_path, transforms):
    img = Image.open(img_path).convert('RGB')
    plt.imshow(img)
    plt.show()

    img = transforms(img).unsqueeze(0)

    model.eval()
    ouput = model(img)

    _, pred = torch.max(ouput, 1)

    return pred

三、遇到的主要问题

1、对原理的掌握不够
2、在写对一张图片predict的时候,由于失误把图片转换的尺寸本应该[224, 224]写成了[244,244],导致预测报错
错误代码:

# -*- coding: utf-8 -*-
import torch.cuda
import torchvision.transforms as transforms
from model import model_K, predict

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

model = model_K().to(device)
model.load_state_dict(torch.load('./model/model.pth', map_location='cpu'))

img_path = './data-test/6.jpg'

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

class_dic = {'0': 'cloudy', '1': 'rain', '2': 'shine', '3': 'sunrise'}
pred_idx = str(predict(model, img_path, pre_transforms).item())
print(class_dic[pred_idx])

调试的时候在训练的forward的x.shape变化是[32, 3, 224, 224] -> [32, 32, 112, 112]->[32, 64, 112, 112]
调试的时候在预测的forward的x.shape变化是[1, 3, 244, 244] -> [1, 32, 122, 122] ->[1, 64, 122, 122]

调试了半天,硬是没看出来。

3、以下是训练过程中的准确率和loss表现
Pytorch实战 | P8 YOLOv5-C3模块实现天气图片识别_第1张图片

你可能感兴趣的:(深度学习实践100例,pytorch,深度学习,python,人工智能)