365天深度学习训练营-第P3周:天气识别

  • 本文为365天深度学习训练营 中的学习记录博客
  • 参考文章:Pytorch实战 | 第P3周:彩色图片识别:天气识别
  • 原作者:K同学啊|接辅导、项目定制

目录

  • 一、课题背景和开发环境
    • 开发环境
  • 二、前期准备
    • 1.设置GPU
    • 2.导入数据并划分数据集
    • 3.数据可视化
  • 三、构建简单的CNN网络
  • 四、训练模型
    • 1.设置超参数
    • 2.编写训练函数
    • 3.编写测试函数
    • 4.正式训练
  • 五、预测&结果可视化
    • 1.训练结果可视化
    • 2.预测本地图片
  • 六、总结

一、课题背景和开发环境

第P3周:天气识别

  • 难度:新手入门⭐
  • 语言:Python3、Pytorch

要求:

  1. 本地读取并加载数据。
  2. 测试集accuracy到达93%

拔高:

  1. 测试集accuracy到达95%
  2. 调用模型识别一张本地图片

本次的重点在于学会构建CNN网络


开发环境

  • 电脑系统:Windows 10
  • 语言环境:Python 3.8.2
  • 编译器:无(直接在cmd.exe内运行)
  • 深度学习环境:Pytorch
  • 显卡及显存:NVIDIA GeForce GTX 1660 Ti 12G
  • CUDA版本:Release 10.0, V10.0.130(cmd输入nvcc -Vnvcc --version指令可查看)
  • 数据:百度网盘(提取码:hqij )

二、前期准备

1.设置GPU

import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import torchvision

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

print("Using {} device".format(device))
# device(type='cuda')
Using cuda device

2.导入数据并划分数据集

import os
import PIL
import random
import pathlib
import warnings
import numpy as np
import matplotlib.pyplot as plt

''' 读取本地数据集并划分训练集与测试集 '''
def localDataset(data_dir):
    data_dir = pathlib.Path(data_dir)
    
    # 读取本地数据集
    data_paths = list(data_dir.glob('*'))
    classeNames = [str(path).split("\\")[-1] for path in data_paths]
    print('ClassName', classeNames, '\n')
    
    # 关于transforms.Compose的更多介绍可以参考:https://blog.csdn.net/qq_38251616/article/details/124878863
    train_transforms = torchvision.transforms.Compose([
        torchvision.transforms.Resize([224, 224]),  # 将输入图片resize成统一尺寸
        torchvision.transforms.ToTensor(),          # 将PIL Image或numpy.ndarray转换为tensor,并归一化到[0,1]之间
        torchvision.transforms.Normalize(           # 标准化处理-->转换为标准正太分布(高斯分布),使模型更容易收敛
            mean=[0.485, 0.456, 0.406], 
            std=[0.229, 0.224, 0.225])  # 其中 mean=[0.485,0.456,0.406]与std=[0.229,0.224,0.225] 从数据集中随机抽样计算得到的。
    ])
    total_data = torchvision.datasets.ImageFolder(data_dir, transform=train_transforms)
    print(total_data, '\n')
    
    # 划分训练集与测试集
    train_size = int(0.8 * len(total_data))
    test_size  = len(total_data) - train_size
    print('train_size', train_size, 'test_size', test_size, '\n')
    train_dataset, test_dataset = torch.utils.data.random_split(total_data, [train_size, test_size])
    
    return train_dataset, test_dataset


''' 加载数据,并设置batch_size '''
def loadData(train_ds, test_ds, batch_size=32, root='', show_flag=False):
    # batch_size = 32
    # 从 train_ds 加载训练集
    train_dl = torch.utils.data.DataLoader(train_ds,
                                           batch_size=batch_size,
                                           shuffle=True,
                                           num_workers=1)
    # 从 test_ds 加载测试集
    test_dl  = torch.utils.data.DataLoader(test_ds,
                                           batch_size=batch_size,
                                           shuffle=True,
                                           num_workers=1)
    
    # 取一个批次查看数据格式
    # 数据的shape为:[batch_size, channel, height, weight]
    # 其中batch_size为自己设定,channel,height和weight分别是图片的通道数,高度和宽度。
    for X, y in test_dl:
        print("Shape of X [N, C, H, W]: ", X.shape)
        print('Shape of y: ', y.shape, y.dtype, '\n')
        break
    
    imgs, labels = next(iter(train_dl))
    print('Image shape: ', imgs.shape, '\n')
    # torch.Size([32, 3, 224, 224])  # 所有数据集中的图像都是224*224的RGB图
    displayData(imgs, root, show_flag)
    return train_dl, test_dl


batch_size = 32
data_dir = './data/weather_photos/'
train_ds, test_ds = localDataset(data_dir)
train_dl, test_dl = loadData(train_ds, test_ds, batch_size, data_dir, True)
ClassName ['cloudy', 'rain', 'shine', 'sunrise']

Dataset ImageFolder
    Number of datapoints: 1125
    Root location: data\weather_photos
    StandardTransform
Transform: Compose(
               Resize(size=[224, 224], interpolation=bilinear)
               ToTensor()
               Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
           )

train_size 900 test_size 225

Shape of X [N, C, H, W]:  torch.Size([32, 3, 224, 224])
Shape of y:  torch.Size([32]) torch.int64

Image shape:  torch.Size([32, 3, 224, 224])

3.数据可视化

''' 数据可视化 '''
def displayData(imgs, root='', flag=False):
    # 指定图片大小,图像大小为20宽、5高的绘图(单位为英寸inch)
    plt.figure('Data Visualization', figsize=(20, 5)) 
    for i, imgs in enumerate(imgs[:20]):
        # 维度顺序调整 [3, 224, 224]->[224, 224, 3]
        npimg = imgs.numpy().transpose((1, 2, 0))
        # 将整个figure分成2行10列,绘制第i+1个子图。
        plt.subplot(2, 10, i+1)
        plt.imshow(npimg)  # cmap=plt.cm.binary
        plt.axis('off')
    plt.savefig(os.path.join(root, 'DatasetDisplay.png'))
    if flag:
        plt.show()
    else:
        plt.close('all')

数据可视化


三、构建简单的CNN网络

对于一般的CNN网络来说,都是由特征提取网络和分类网络构成,其中特征提取网络用于提取图片的特征,分类网络用于将图片进行分类。

import torch
import torch.nn as nn
import torchvision
from torchinfo import summary

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.conv1=nn.Sequential(
            nn.Conv2d(3, 12, kernel_size=5, padding=0), # 12*220*220
            nn.BatchNorm2d(12),
            nn.ReLU()
        )
        self.conv2=nn.Sequential(
            nn.Conv2d(12, 12, kernel_size=5, padding=0), # 12*216*216
            nn.BatchNorm2d(12),
            nn.ReLU()
        )
        self.pool3=nn.Sequential(
            nn.MaxPool2d(2)                              # 12*108*108
        )
        self.conv4=nn.Sequential(
            nn.Conv2d(12, 24, kernel_size=5, padding=0), # 24*104*104
            nn.BatchNorm2d(24),
            nn.ReLU()
        )
        self.conv5=nn.Sequential(
            nn.Conv2d(24, 24, kernel_size=5, padding=0), # 24*100*100
            nn.BatchNorm2d(24),
            nn.ReLU()
        )
        self.pool6=nn.Sequential(
            nn.MaxPool2d(2)                              # 24*50*50
        )
        self.conv7=nn.Sequential(
            nn.Conv2d(24, 48, kernel_size=5, padding=0), # 48*46*46
            nn.BatchNorm2d(48),
            nn.ReLU()
        )
        self.conv8=nn.Sequential(
            nn.Conv2d(48, 48, kernel_size=5, padding=0), # 48*42*42
            nn.BatchNorm2d(48),
            nn.ReLU()
        )
        self.pool9=nn.Sequential(
            nn.MaxPool2d(2)                              # 48*21*21
        )
        self.fc=nn.Sequential(
            nn.Linear(48*21*21, num_classes)
        )
    
    def forward(self, x):
       batch_size = x.size(0)
       x = self.conv1(x)  # 卷积-BN-激活
       x = self.conv2(x)  # 卷积-BN-激活
       x = self.pool3(x)  # 池化
       x = self.conv4(x)  # 卷积-BN-激活
       x = self.conv5(x)  # 卷积-BN-激活
       x = self.pool6(x)  # 池化
       x = self.conv7(x)  # 卷积-BN-激活
       x = self.conv8(x)  # 卷积-BN-激活
       x = self.pool9(x)  # 池化
       x = x.view(batch_size, -1)  # flatten 变成全连接网络需要的输入 (batch, 48*21*21) ==> (batch, -1), -1 此处自动算出的是21168
       x = self.fc(x)
       
       return x


device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using {} device".format(device))
''' 调用并将模型转移到GPU中(我们模型运行均在GPU中进行) '''
model = Model().to(device)
''' 显示网络结构 '''
summary(model)
print(model)
=================================================================
Layer (type:depth-idx)                   Param #
=================================================================
Model                                    --
├─Sequential: 1-1                        --
│    └─Conv2d: 2-1                       912
│    └─BatchNorm2d: 2-2                  24
│    └─ReLU: 2-3                         --
├─Sequential: 1-2                        --
│    └─Conv2d: 2-4                       3,612
│    └─BatchNorm2d: 2-5                  24
│    └─ReLU: 2-6                         --
├─Sequential: 1-3                        --
│    └─MaxPool2d: 2-7                    --
├─Sequential: 1-4                        --
│    └─Conv2d: 2-8                       7,224
│    └─BatchNorm2d: 2-9                  48
│    └─ReLU: 2-10                        --
├─Sequential: 1-5                        --
│    └─Conv2d: 2-11                      14,424
│    └─BatchNorm2d: 2-12                 48
│    └─ReLU: 2-13                        --
├─Sequential: 1-6                        --
│    └─MaxPool2d: 2-14                   --
├─Sequential: 1-7                        --
│    └─Conv2d: 2-15                      28,848
│    └─BatchNorm2d: 2-16                 96
│    └─ReLU: 2-17                        --
├─Sequential: 1-8                        --
│    └─Conv2d: 2-18                      57,648
│    └─BatchNorm2d: 2-19                 96
│    └─ReLU: 2-20                        --
├─Sequential: 1-9                        --
│    └─MaxPool2d: 2-21                   --
├─Sequential: 1-10                       --
│    └─Linear: 2-22                      84,676
=================================================================
Total params: 197,680
Trainable params: 197,680
Non-trainable params: 0
=================================================================
Model(
  (conv1): Sequential(
    (0): Conv2d(3, 12, kernel_size=(5, 5), stride=(1, 1))
    (1): BatchNorm2d(12, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU()
  )
  (conv2): Sequential(
    (0): Conv2d(12, 12, kernel_size=(5, 5), stride=(1, 1))
    (1): BatchNorm2d(12, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU()
  )
  (pool3): Sequential(
    (0): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (conv4): Sequential(
    (0): Conv2d(12, 24, kernel_size=(5, 5), stride=(1, 1))
    (1): BatchNorm2d(24, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU()
  )
  (conv5): Sequential(
    (0): Conv2d(24, 24, kernel_size=(5, 5), stride=(1, 1))
    (1): BatchNorm2d(24, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU()
  )
  (pool6): Sequential(
    (0): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (conv7): Sequential(
    (0): Conv2d(24, 48, kernel_size=(5, 5), stride=(1, 1))
    (1): BatchNorm2d(48, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU()
  )
  (conv8): Sequential(
    (0): Conv2d(48, 48, kernel_size=(5, 5), stride=(1, 1))
    (1): BatchNorm2d(48, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU()
  )
  (pool9): Sequential(
    (0): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (fc): Sequential(
    (0): Linear(in_features=21168, out_features=4, bias=True)
  )
)

四、训练模型

1.设置超参数

loss_fn    = nn.CrossEntropyLoss() # 创建损失函数
learn_rate = 1e-4 # 学习率
opt        = torch.optim.Adam(model.parameters(),lr=learn_rate)

2.编写训练函数

optimizer.zero_grad()
loss.backward()
optimizer.step()
关于以上三个函数,我在之前的文章中有做说明,这里不再赘述

# 训练循环
def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)  # 训练集的大小
    num_batches = len(dataloader)   # 批次数目

    train_loss, train_acc = 0, 0  # 初始化训练损失和正确率
    
    for X, y in dataloader:  # 获取图片及其标签
        X, y = X.to(device), y.to(device)
        
        # 计算预测误差
        pred = model(X)          # 网络输出
        loss = loss_fn(pred, y)  # 计算网络输出和真实值之间的差距,targets为真实值,计算二者差值即为损失
        
        # 反向传播
        optimizer.zero_grad()  # grad属性归零
        loss.backward()        # 反向传播
        optimizer.step()       # 每一步自动更新
        
        # 记录acc与loss
        train_acc  += (pred.argmax(1) == y).type(torch.float).sum().item()
        train_loss += loss.item()
            
    train_acc  /= size
    train_loss /= num_batches

    return train_acc, train_loss

3.编写测试函数

测试函数和训练函数大致相同,但是由于不进行梯度下降对网络权重进行更新,所以不需要传入优化器

def test (dataloader, model, loss_fn):
    size        = len(dataloader.dataset)  # 测试集的大小
    num_batches = len(dataloader)          # 批次数目
    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

4.正式训练

model.train()
model.eval()

关于以上两个个函数,我在之前的文章中有做说明,这里不再赘述

import time

start_epoch = 0
epochs      = 50
train_loss  = []
train_acc   = []
test_loss   = []
test_acc    = []

''' 加载之前保存的模型 '''
if not os.path.exists(output) or not os.path.isdir(output):
    os.makedirs(output)
if start_epoch > 0:
    resumeFile = os.path.join(output, 'epoch'+str(start_epoch)+'.pkl')
    if not os.path.exists(resumeFile) or not os.path.isfile(resumeFile):
        start_epoch = 0
    else:
        model.load_state_dict(torch.load(resumeFile))  # 加载模型参数

''' 开始训练模型 '''
print('\nStart training...')
for epoch in range(start_epoch, 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(time.strftime('[%Y-%m-%d %H:%M:%S]'), template.format(epoch+1, epoch_train_acc*100, epoch_train_loss, epoch_test_acc*100, epoch_test_loss))
print('Done\n')

''' 保存模型参数 '''
saveFile = os.path.join(output, 'epoch'+str(epochs)+'.pkl')
torch.save(model.state_dict(), saveFile)
Start training...
[2022-10-10 16:37:04] Epoch: 1, Train_acc:73.1%, Train_loss:0.674, Test_acc:68.0%,Test_loss:1.462
[2022-10-10 16:37:15] Epoch: 2, Train_acc:87.1%, Train_loss:0.386, Test_acc:84.4%,Test_loss:0.353
[2022-10-10 16:37:25] Epoch: 3, Train_acc:88.6%, Train_loss:0.309, Test_acc:87.6%,Test_loss:0.823
[2022-10-10 16:37:36] Epoch: 4, Train_acc:90.0%, Train_loss:0.278, Test_acc:91.1%,Test_loss:0.237
[2022-10-10 16:37:46] Epoch: 5, Train_acc:94.0%, Train_loss:0.180, Test_acc:92.0%,Test_loss:0.184
[2022-10-10 16:37:57] Epoch: 6, Train_acc:96.6%, Train_loss:0.139, Test_acc:91.1%,Test_loss:0.187
[2022-10-10 16:38:07] Epoch: 7, Train_acc:94.3%, Train_loss:0.158, Test_acc:92.9%,Test_loss:0.200
[2022-10-10 16:38:18] Epoch: 8, Train_acc:97.0%, Train_loss:0.116, Test_acc:93.8%,Test_loss:0.134
[2022-10-10 16:38:29] Epoch: 9, Train_acc:95.9%, Train_loss:0.119, Test_acc:91.1%,Test_loss:0.167
[2022-10-10 16:38:39] Epoch:10, Train_acc:97.9%, Train_loss:0.072, Test_acc:95.1%,Test_loss:0.117
[2022-10-10 16:38:50] Epoch:11, Train_acc:98.2%, Train_loss:0.142, Test_acc:92.4%,Test_loss:0.155
[2022-10-10 16:39:01] Epoch:12, Train_acc:93.7%, Train_loss:0.246, Test_acc:92.9%,Test_loss:0.172
[2022-10-10 16:39:12] Epoch:13, Train_acc:95.1%, Train_loss:0.161, Test_acc:92.4%,Test_loss:0.167
[2022-10-10 16:39:24] Epoch:14, Train_acc:96.8%, Train_loss:0.100, Test_acc:92.4%,Test_loss:0.232
[2022-10-10 16:39:35] Epoch:15, Train_acc:97.3%, Train_loss:0.083, Test_acc:96.0%,Test_loss:0.129
[2022-10-10 16:39:45] Epoch:16, Train_acc:98.8%, Train_loss:0.050, Test_acc:93.8%,Test_loss:0.149
[2022-10-10 16:39:56] Epoch:17, Train_acc:97.7%, Train_loss:0.105, Test_acc:91.6%,Test_loss:0.172
[2022-10-10 16:40:07] Epoch:18, Train_acc:95.3%, Train_loss:0.123, Test_acc:94.7%,Test_loss:0.148
[2022-10-10 16:40:18] Epoch:19, Train_acc:97.7%, Train_loss:0.074, Test_acc:94.7%,Test_loss:0.132
[2022-10-10 16:40:29] Epoch:20, Train_acc:99.2%, Train_loss:0.041, Test_acc:95.1%,Test_loss:0.131
[2022-10-10 16:40:40] Epoch:21, Train_acc:99.0%, Train_loss:0.040, Test_acc:96.0%,Test_loss:0.113
[2022-10-10 16:40:51] Epoch:22, Train_acc:99.4%, Train_loss:0.165, Test_acc:93.8%,Test_loss:0.139
[2022-10-10 16:41:02] Epoch:23, Train_acc:95.4%, Train_loss:0.234, Test_acc:93.3%,Test_loss:0.440
[2022-10-10 16:41:13] Epoch:24, Train_acc:96.1%, Train_loss:0.131, Test_acc:93.8%,Test_loss:0.159
[2022-10-10 16:41:24] Epoch:25, Train_acc:98.2%, Train_loss:0.057, Test_acc:95.1%,Test_loss:0.227
[2022-10-10 16:41:36] Epoch:26, Train_acc:96.3%, Train_loss:0.119, Test_acc:92.4%,Test_loss:0.289
[2022-10-10 16:41:47] Epoch:27, Train_acc:98.2%, Train_loss:0.052, Test_acc:92.9%,Test_loss:0.140
[2022-10-10 16:41:58] Epoch:28, Train_acc:99.0%, Train_loss:0.039, Test_acc:94.7%,Test_loss:0.137
[2022-10-10 16:42:09] Epoch:29, Train_acc:99.1%, Train_loss:0.027, Test_acc:94.2%,Test_loss:0.125
[2022-10-10 16:42:20] Epoch:30, Train_acc:99.7%, Train_loss:0.020, Test_acc:95.6%,Test_loss:0.119
[2022-10-10 16:42:31] Epoch:31, Train_acc:99.4%, Train_loss:0.025, Test_acc:93.8%,Test_loss:0.155
[2022-10-10 16:42:42] Epoch:32, Train_acc:98.7%, Train_loss:0.067, Test_acc:93.8%,Test_loss:0.198
[2022-10-10 16:42:53] Epoch:33, Train_acc:97.9%, Train_loss:0.056, Test_acc:94.2%,Test_loss:0.108
[2022-10-10 16:43:04] Epoch:34, Train_acc:99.7%, Train_loss:0.017, Test_acc:96.0%,Test_loss:0.103
[2022-10-10 16:43:16] Epoch:35, Train_acc:100.0%, Train_loss:0.010, Test_acc:94.7%,Test_loss:0.105
[2022-10-10 16:43:26] Epoch:36, Train_acc:99.9%, Train_loss:0.009, Test_acc:96.0%,Test_loss:0.102
[2022-10-10 16:43:37] Epoch:37, Train_acc:99.7%, Train_loss:0.016, Test_acc:93.8%,Test_loss:0.229
[2022-10-10 16:43:48] Epoch:38, Train_acc:100.0%, Train_loss:0.006, Test_acc:94.7%,Test_loss:0.101
[2022-10-10 16:43:59] Epoch:39, Train_acc:100.0%, Train_loss:0.004, Test_acc:95.1%,Test_loss:0.316
[2022-10-10 16:44:10] Epoch:40, Train_acc:99.8%, Train_loss:0.008, Test_acc:94.7%,Test_loss:0.104
[2022-10-10 16:44:22] Epoch:41, Train_acc:100.0%, Train_loss:0.005, Test_acc:95.1%,Test_loss:0.104
[2022-10-10 16:44:33] Epoch:42, Train_acc:99.7%, Train_loss:0.113, Test_acc:94.2%,Test_loss:0.116
[2022-10-10 16:44:44] Epoch:43, Train_acc:96.8%, Train_loss:0.110, Test_acc:94.2%,Test_loss:0.166
[2022-10-10 16:44:55] Epoch:44, Train_acc:98.0%, Train_loss:0.057, Test_acc:92.4%,Test_loss:0.202
[2022-10-10 16:45:06] Epoch:45, Train_acc:99.7%, Train_loss:0.022, Test_acc:94.2%,Test_loss:0.130
[2022-10-10 16:45:17] Epoch:46, Train_acc:99.7%, Train_loss:0.116, Test_acc:94.7%,Test_loss:0.132
[2022-10-10 16:45:28] Epoch:47, Train_acc:98.4%, Train_loss:0.048, Test_acc:93.3%,Test_loss:0.170
[2022-10-10 16:45:39] Epoch:48, Train_acc:99.9%, Train_loss:0.016, Test_acc:95.1%,Test_loss:0.122
[2022-10-10 16:45:50] Epoch:49, Train_acc:100.0%, Train_loss:0.008, Test_acc:94.7%,Test_loss:0.117
[2022-10-10 16:46:01] Epoch:50, Train_acc:99.3%, Train_loss:0.036, Test_acc:94.2%,Test_loss:0.139
Done

最终结果,训练集准确率达到99.3%,测试集准确率达到94.2%


五、预测&结果可视化

1.训练结果可视化

import matplotlib.pyplot as plt
import warnings


''' 结果可视化 '''
def displayResult(train_acc, test_acc, train_loss, test_loss, start_epoch, epochs, output=''):
    # 隐藏警告
    warnings.filterwarnings("ignore")                # 忽略警告信息
    plt.rcParams['font.sans-serif']    = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False       # 用来正常显示负号
    plt.rcParams['figure.dpi']         = 100         # 分辨率
    
    epochs_range = range(start_epoch, epochs)
    
    plt.figure('Result Visualization', 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.savefig(os.path.join(output, 'AccuracyLoss.png'))
    plt.show()


''' 绘制准确率&损失率曲线图 '''
displayResult(train_acc, test_acc, train_loss, test_loss, start_epoch, epochs, output)

365天深度学习训练营-第P3周:天气识别_第1张图片


2.预测本地图片

''' 预测 '''
classeNames = ['cloudy', 'rain', 'shine', 'sunrise']
num_classes = len(classeNames)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

model = Model().to(device)
model.load_state_dict(torch.load('./output/epoch50.pkl'))
model.eval()

img_path = './data/weather_photos/rain/rain28.jpg'
img = Image.open(img_path)
train_transforms = torchvision.transforms.Compose([
    torchvision.transforms.Resize([224, 224]),  # 将输入图片resize成统一尺寸
    torchvision.transforms.ToTensor(),          # 将PIL Image或numpy.ndarray转换为tensor,并归一化到[0,1]之间
    torchvision.transforms.Normalize(           # 标准化处理-->转换为标准正太分布(高斯分布),使模型更容易收敛
        mean=[0.485, 0.456, 0.406], 
        std=[0.229, 0.224, 0.225])
])
img = train_transforms(img)
img = torch.reshape(img, (1, 3, 224, 224))

output = model(img)
_, indices = torch.max(output, 1)
percentage = torch.nn.functional.softmax(output, dim=1)[0] * 100
perc = percentage[int(indices)].item()
result = classeNames[indices]
print('predicted:', result, perc)

运行预测程序,出现下面的报错信息:

RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same

修改如下:

# output = model(img)
output = model(img.cuda())

修改后的运行结果:

predicted: rain 99.97901153564453

六、总结

关于模型优化的过程:
初始模型只有前6层([卷积-BN-激活]→[卷积-BN-激活]→[池化]→[卷积-BN-激活]→[卷积-BN-激活]→[池化],不包含FC层),训练50轮之后准确率维持在92%上下;
第一次优化,增加了三层网络([卷积-BN-激活]→[卷积-BN-激活]→[池化]),使模型由原来的6层变为9层(不包含FC层),训练50轮之后,准确率依旧维持在93%上下,有一定优化效果,但依旧无法达到要求;
第二次优化,调整了学习率,初始为1e-4,先尝试修改为1e-3,发现每轮次后计算得到的Loss值在不断上下跳动,无法逐步收敛;然后再尝试了2e-4,Loss曲线的波折程度依然较大,尤其在训练到35轮后,准确率一直在85%到95%之间来回跳动;最后再调整为5e-5,Loss曲线虽然在稳步下降,但下降速度很慢,50轮后准确率才达到88%;放弃修改学习率参数,维持1e-4不变;
第三次优化,尝试修改优化器,初始为SGD(随机梯度下降),调整为Adam,在训练到第10轮的时候,测试集的准确率第一次达到了95%,50轮后稳定在了95%;
前文中展示的是最后的模型。

你可能感兴趣的:(365天深度学习训练记录,深度学习,python,pytorch)