深度学习 Day25——使用Pytorch实现彩色图片识别

深度学习 Day25——使用Pytorch实现彩色图片识别

本次博客我是通过Notion软件写的,转md文件可能不太美观,大家可以去我的博客中查看:✨北天的 BLOG,持续更新中,另外这是我创建的编程算法竞赛学习小组频道,想一起学习的朋友可以一起!!!

一、前言

🍨 本文为🔗365天深度学习训练营 中的学习记录博客🍦 参考文章:365天深度学习训练营-第P2周:彩色识别🍖 原作者:K同学啊|接辅导、项目定制

上一次更新还是在上一次(年前),好久不见,本周是深度学习的第十五周,本期博客我们将学习如何使用Pytorch搭建CNN网络实现彩色图片识别。

好啦,废话不多说,我们开始本周的深度学习之旅!

二、我的环境

  • 电脑系统:Windows 11
  • 语言环境:Python 3.8.5
  • 编译器:DataSpell 2022
  • 深度学习环境:
    • torch 1.12.1+cu113
    • torchvision 0.13.1+cu113
  • 显卡及显存:RTX 3070 8G

三、前期工作

1、导入依赖项和设置GPU

我们通过识别判断,自动选择所支持的硬件配置,有GPU就使用,没有就使用CPU。

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")
device
device(type='cuda')

2、下载数据

在这里我们通过dataset从网上下载CIFAR10数据集,并划分好我们需要的训练集和测试集。

train_ds = torchvision.datasets.CIFAR10('data',
                                        train=True,
                                        transform=torchvision.transforms.ToTensor(), # 将数据类型转化为Tensor
                                        download=True)

test_ds  = torchvision.datasets.CIFAR10('data',
                                        train=False,
                                        transform=torchvision.transforms.ToTensor(), # 将数据类型转化为Tensor
                                        download=True)
Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to data\cifar-10-python.tar.gz
Output exceeds the size limit. Open the full output data in a text editor
2.1%IOPub message rate exceeded.
The notebook server will temporarily stop sending output
to the client in order to avoid crashing it.
To change this limit, set the config variable
`--NotebookApp.iopub_msg_rate_limit`.

Current values:
NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)
NotebookApp.rate_limit_window=3.0 (secs)

4.3%IOPub message rate exceeded.
The notebook server will temporarily stop sending output
to the client in order to avoid crashing it.
To change this limit, set the config variable
`--NotebookApp.iopub_msg_rate_limit`.

Current values:
NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)
NotebookApp.rate_limit_window=3.0 (secs)

6.7%IOPub message rate exceeded.
The notebook server will temporarily stop sending output
to the client in order to avoid crashing it.
To change this limit, set the config variable
`--NotebookApp.iopub_msg_rate_limit`.
...
NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)
NotebookApp.rate_limit_window=3.0 (secs)

100.0%
Extracting data\cifar-10-python.tar.gz to data
Files already downloaded and verified

3、加载数据

下载好数据之后,我们再使用dataloader加载数据,并设置好batch_size值。

batch_size = 32

train_dl = torch.utils.data.DataLoader(train_ds,
                                       batch_size=batch_size,
                                       shuffle=True)

test_dl  = torch.utils.data.DataLoader(test_ds,
                                       batch_size=batch_size)

在这里我们查看一个批次的数据格式。

# 数据的shape为:[batch_size, channel, height, weight]
# 其中batch_size为自己设定,channel,height和weight分别是图片的通道数,高度和宽度。
imgs, labels = next(iter(train_dl))
imgs.shape
torch.Size([32, 3, 32, 32])

4、数据可视化

我们可视化一部分我们加载进来的数据进行查看。

import numpy as np

# 指定图片大小,图像大小为20宽、5高的绘图(单位为英寸inch)
plt.figure(figsize=(20, 5))
for i, imgs in enumerate(imgs[:20]):
    # 维度缩减
    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')

在这里插入图片描述

四、构建CNN网络结构

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

下面我们首先介绍构建CNN网络的一些函数。

1、函数介绍

函数原型:

torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', device=None, dtype=None)

关键参数说明:

●in_channels ( int ) – 输入图像中的通道数

●out_channels ( int ) – 卷积产生的通道数

●kernel_size ( int or tuple ) – 卷积核的大小

●stride ( int or tuple , optional ) – 卷积的步幅。默认值:1

●padding ( int , tuple或str , optional ) – 添加到输入的所有四个边的填充。默认值:0

●padding_mode (字符串,可选) – ‘zeros’, ‘reflect’, ‘replicate’或’circular’. 默认:‘zeros’


函数原型:

torch.nn.Linear(in_features, out_features, bias=True, device=None, dtype=None)

关键参数说明:

●in_features:每个输入样本的大小

●out_features:每个输出样本的大小


函数原型:

torch.nn.MaxPool2d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)

关键参数说明:

●kernel_size:最大的窗口大小

●stride:窗口的步幅,默认值为kernel_size

●padding:填充值,默认为0

●dilation:控制窗口中元素步幅的参数

2、构建CNN并打印模型

import torch.nn.functional as F

num_classes = 10  # 图片的类别数

class Model(nn.Module):
    def __init__(self):
        super().__init__()
        # 特征提取网络
        self.conv1 = nn.Conv2d(3, 64, kernel_size=3)   # 第一层卷积,卷积核大小为3*3
        self.pool1 = nn.MaxPool2d(kernel_size=2)       # 设置池化层,池化核大小为2*2
        self.conv2 = nn.Conv2d(64, 64, kernel_size=3)  # 第二层卷积,卷积核大小为3*3
        self.pool2 = nn.MaxPool2d(kernel_size=2)
        self.conv3 = nn.Conv2d(64, 128, kernel_size=3) # 第二层卷积,卷积核大小为3*3
        self.pool3 = nn.MaxPool2d(kernel_size=2)

        # 分类网络
        self.fc1 = nn.Linear(512, 256)
        self.fc2 = nn.Linear(256, num_classes)
    # 前向传播
    def forward(self, x):
        x = self.pool1(F.relu(self.conv1(x)))
        x = self.pool2(F.relu(self.conv2(x)))
        x = self.pool3(F.relu(self.conv3(x)))

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

        x = F.relu(self.fc1(x))
        x = self.fc2(x)

        return x

该网络定义了三个卷积层(conv1、conv2、conv3),每个卷积层后面都跟了一个最大池化层(MaxPool2d),卷积层和池化层的目的是对输入图像进行特征提取。

然后它定义了两个全连接层(fc1、fc2),这两个层被称为分类网络,它们的目的是对特征提取的结果进行分类。

最后它定义了一个前向传播函数(forward),前向传播函数的作用是定义一个从输入到输出的网络。它首先通过三个卷积层、三个最大池化层进行特征提取,然后将提取的特征拉平,最后经过两个全连接层完成分类任务。

激活函数使用的是ReLU,分类的最终结果在最后一个全连接层的输出中。

我们打印它的模型:

from torchinfo import summary
# 将模型转移到GPU中(我们模型运行均在GPU中进行)
model = Model().to(device)

summary(model)
=================================================================
Layer (type:depth-idx)                   Param #
=================================================================
Model                                    --
├─Conv2d: 1-1                            1,792
├─MaxPool2d: 1-2                         --
├─Conv2d: 1-3                            36,928
├─MaxPool2d: 1-4                         --
├─Conv2d: 1-5                            73,856
├─MaxPool2d: 1-6                         --
├─Linear: 1-7                            131,328
├─Linear: 1-8                            2,570
=================================================================
Total params: 246,474
Trainable params: 246,474
Non-trainable params: 0
=================================================================

3、可视化模型结构

在这里我们试一下使用PyTorchViz 库来可视化模型的结构,可以更加方便直观的查看我们的模型结构。

from torchviz import make_dot

model = Model()
vis_graph = make_dot(model(torch.randn(1, 3, 32, 32)), params=dict(model.named_parameters()))
vis_graph.render("model_structure", format="png")

在这里插入图片描述

通过上述图片我们可以更加清楚的看见网络中每一步的实现过程。

PyTorchViz是一个可视化PyTorch模型结构的库,它使用Graphviz软件作为后端,使用简单,代码简洁。通过PyTorchViz,可以方便地将PyTorch模型的结构可视化,对于调试和理解模型设计非常有帮助。使用PyTorchViz库,需要安装Graphviz,可以直接使用pip/conda来安装。

如果你运行代码报错:ExecutableNotFound: failed to execute WindowsPath(‘dot’), make sure the Graphviz executables are on your systems’ PATH’,那你需要将安装的Graphviz包的bin目录添加到环境变量里面,以便PyTorchViz能够找到Graphviz的可执行文件。

五、训练模型

1、设置损失函数,学习率

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

2、编写训练函数

在编写训练函数之前我们需要了解一下其中使用的一些函数介绍。

  • optimizer.zero_grad()

该函数会遍历模型的所有参数,通过内置方法截断反向传播的梯度流,再将每个参数的梯度值设为0,即上一次的梯度记录被清空。

  • loss.backward()

PyTorch的反向传播(即tensor.backward())是通过autograd包来实现的,autograd包会根据tensor进行过的数学运算来自动计算其对应的梯度。

具体来说,torch.tensor是autograd包的基础类,如果你设置tensor的requires_grads为True,就会开始跟踪这个tensor上面的所有运算,如果你做完运算后使用tensor.backward(),所有的梯度就会自动运算,tensor的梯度将会累加到它的.grad属性里面去。

更具体地说,损失函数loss是由模型的所有权重w经过一系列运算得到的,若某个w的requires_grads为True,则w的所有上层参数(后面层的权重w)的.grad_fn属性中就保存了对应的运算,然后在使用loss.backward()后,会一层层的反向传播计算每个w的梯度值,并保存到该w的.grad属性中。

如果没有进行tensor.backward()的话,梯度值将会是None,因此loss.backward()要写在optimizer.step()之前。

  • optimizer.step()

step()函数的作用是执行一次优化步骤,通过梯度下降法来更新参数的值。因为梯度下降是基于梯度的,所以在执行optimizer.step()函数前应先执行loss.backward()函数来计算梯度。

注意:optimizer只负责通过梯度下降进行优化,而不负责产生梯度,梯度是tensor.backward()方法产生的。

# 训练循环
def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)  # 训练集的大小,一共60000张图片
    num_batches = len(dataloader)   # 批次数目,1875(60000/32)

    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)  # 测试集的大小,一共10000张图片
    num_batches = len(dataloader)          # 批次数目,313(10000/32=312.5,向上取整)
    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.train()的作用是启用 Batch Normalization 和 Dropout。

如果模型中有BN层(Batch Normalization)和Dropout,需要在训练时添加model.train()。model.train()是保证BN层能够用到每一批数据的均值和方差。对于Dropout,model.train()是随机取一部分网络连接来训练更新参数。

  • model.eval()

model.eval()的作用是不启用 Batch Normalization 和 Dropout。

如果模型中有BN层(Batch Normalization)和Dropout,在测试时添加model.eval()。model.eval()是保证BN层能够用全部训练数据的均值和方差,即测试过程中要保证BN层的均值和方差不变。对于Dropout,model.eval()是利用到了所有网络连接,即不进行随机舍弃神经元。

训练完train样本后,生成的模型model要用来测试样本。在model(test)之前,需要加上model.eval(),否则的话,有输入数据,即使不训练,它也会改变权值。这是model中含有BN层和Dropout所带来的的性质。

epochs = 10
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*100, epoch_train_loss, epoch_test_acc*100, epoch_test_loss))
print('Done')

训练的结果是:

Epoch: 1, Train_acc:14.2%, Train_loss:2.297, Test_acc:20.6%,Test_loss:2.276
Epoch: 2, Train_acc:23.6%, Train_loss:2.079, Test_acc:29.2%,Test_loss:1.944
Epoch: 3, Train_acc:31.8%, Train_loss:1.859, Test_acc:36.0%,Test_loss:1.763
Epoch: 4, Train_acc:40.0%, Train_loss:1.650, Test_acc:42.5%,Test_loss:1.564
Epoch: 5, Train_acc:44.3%, Train_loss:1.528, Test_acc:45.3%,Test_loss:1.488
Epoch: 6, Train_acc:48.1%, Train_loss:1.435, Test_acc:42.4%,Test_loss:1.647
Epoch: 7, Train_acc:51.4%, Train_loss:1.355, Test_acc:51.2%,Test_loss:1.342
Epoch: 8, Train_acc:54.2%, Train_loss:1.285, Test_acc:55.2%,Test_loss:1.263
Epoch: 9, Train_acc:56.7%, Train_loss:1.222, Test_acc:56.8%,Test_loss:1.207
Epoch:10, Train_acc:58.8%, Train_loss:1.167, Test_acc:57.5%,Test_loss:1.196
Done

六、结果可视化

在最后我们将训练之后的结果进行画图可视化。

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

在这里插入图片描述

七、最后我想说

pytorch中有很多可视化的工具,我们不仅可以可视化网络结构,还可以可视化训练过程,其中网络结构可视化的库有:HiddenLayer,PyTorchViz,训练过程可视化的库有:tensorboardX,HiddenLayer,Visdom,感兴趣的朋友可以去尝试一下。结合这些可视化工具可以让我们更容易的理解深度学习的网络构建和训练过程。

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

-北天-

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值