- 🍨 本文為🔗365天深度學習訓練營 中的學習紀錄博客
- 🍖 原作者:K同学啊 | 接輔導、項目定制
一、前期准备
1. 设置device
# import the necessary libraries
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchinfo import summary
import torchvision
import numpy as np
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 #分辨率
# 设置硬件设备,如果有GPU则使用,没有则使用cpu
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device
2. 导入数据
使用dataset下载CIFAR10数据集,并划分好训练集与测试集
# load the data
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)
print('Number of training examples: ', len(train_ds))
print('Number of testing examples: ', len(test_ds))
使用dataloader加载数据,并设置好基本的batch_size
# Data loader
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分别是图片的通道数,高度和宽度。
"""
The iter() function is used to get an iterator from the data loader (train_dl).
An iterator is an object that allows you to loop through a container (in this case, the data loader) one element at a time.
next() retrieves the next item from the iterator, which, in this context, is the next batch of data from the data loader.
"""
imgs, labels = next(iter(train_dl))
imgs.shape
3. 数据可视化
transpose((1, 2, 0))
详解:
- 作用是对NumPy数组进行轴变换,
transpose
函数的参数是一个元组,定义了新轴的顺序。原始PyTorch张量通常是以(C, H, W)
的格式存储的,其中:
C
是通道数(例如,RGB图像有3个通道)。H
是图像的高度。W
是图像的宽度。
transpose((1, 2, 0))
将轴的顺序从(C, H, W)
转换为(H, W, C)
,这使得数据格式更适合可视化和处理。
# Visualize the data
# Specify the figure size (width=20 inches, height=5 inches)
plt.figure(figsize=(20, 5))
# Iterate over the first 20 images
for i, img in enumerate(imgs[:20]):
# Convert the tensor to a numpy array and remove any singleton dimensions
npimg = img.numpy().squeeze().transpose((1, 2, 0)) # Ensures the shape is (32, 32, 3)
# Create a subplot grid (2 rows, 10 columns) and plot each image
plt.subplot(2, 10, i + 1)
plt.imshow(npimg, cmap=plt.cm.binary)
plt.axis('off') # Turn off the axis
plt.tight_layout()
plt.show()
二、构建简单的CNN网络
1. torch.nn.Conv2d()
详解
函数原型:
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
- dilation (int or tuple, optional) - 扩张操作:控制kernel点(卷积核点)的间距,默认值:1。
- groups(int,可选):将输入通道分组成多个子组,每个子组使用一组卷积核来处理。默认值为 1,表示不进行分组卷积。
- padding_mode (字符串,可选) – 'zeros', 'reflect', 'replicate'或'circular'. 默认:'zeros'
2. torch.nn.Linear()详解
函数原型:
torch.nn.Linear(in_features, out_features, bias=True, device=None, dtype=None)
关键参数说明:
- in_features:每个输入样本的大小
- out_features:每个输出样本的大小
3. torch.nn.MaxPool2d()详解
函数原型:
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:控制窗口中元素步幅的参数
4. 关于卷积层、池化层的计算:
1. 卷积层参数计算
对于一个卷积层,有以下几个重要参数需要确定:
- 输入尺寸(Height, Width, Depth)
- 卷积核尺寸(Kernel Size,
)
- 步长(Stride,
)
- 填充(Padding,
)
输出特征图的尺寸计算
假设输入特征图尺寸为, 输出特征图的尺寸
的计算公式如下:
参数数量
卷积层的参数数量由以下公式计算:
其中 是每个卷积核的参数数量,加上一个偏置项,再乘以卷积核的数量
2. 池化层参数计算
池化层用于减少特征图的尺寸,主要参数包括:
- 池化核尺寸(
)
- 步长(Stride,
)
常见的池化操作包括最大池化(Max Pooling)和平均池化(Average Pooling)。
输出特征图的尺寸计算
池化层通常不改变,只是减小了宽度和高度。
3. 本文模型尺寸详细计算
输入数据
- 输入尺寸: (3,32,32)
- 输入深度: 3
经过卷积层 1
- 卷积核数量: 64
- 卷积核尺寸: (3,3)
- 步长: 1
- 填充: 0
输出尺寸计算:
池化层1输出尺寸:
卷积层2输出尺寸:
池化层2输出尺寸:
卷积层3输出尺寸:
池化层3输出尺寸:
# Define the model
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
加载并打印模型
# Load and print the model
# 将模型转移到GPU中, 此处没有GPU,所以使用CPU
model = Model().to(device)
summary(model)
三、训练模型
1. 设置超参数
# Define the loss function and optimizer
loss_fn = nn.CrossEntropyLoss() # 创建损失函数
learn_rate = 1e-2 # 学习率
opt = torch.optim.SGD(model.parameters(),lr=learn_rate)
2. 编写训练函数
# Train the model
def train(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset) # 训练集的大小,一共50000张图片
num_batches = len(dataloader) # 批次数目,1563(50000/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. 编写测试函数
测试函数和训练函数大致相同,但是由于不进行梯度下降对网络权重进行更新,所以不需要传入优化器
# Test the model
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. 正式训练
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')
四、结果可视化
# Visualize the training and testing accuracy
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()