`- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊`
前期准备
运行环境
- 语言环境:Python 3.10
- 编译器:Google Colab
- 深度学习环境:
- torch==2.3.1+cu121
- torchvision==0.18.1+cu121
模块导入
# Import package
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import torchvision
import numpy as np
import torch.nn.functional as F
from torchinfo import summary
如果设备上支持GPU就使用GPU,否则使用CPU。
# Training our model using GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
导入数据
使用dataset下载CIFAR10数据集,并划分好训练集与测试集。
# Download 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)
使用dataloader加载数据,并设置好基本的batch_size。
# Load data
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分别是图片的通道数,高度和宽度。
# Check the data format of a batch
# Data shape: [batch_size, channels, height, width]
imgs, labels = next(iter(train_dl))
imgs.shape
数据可视化
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),这使得数据格式更适合可视化和处理。
- PyTorch 默认图像格式为
(C, H, W)
,而 Matplotlib 的imshow
需要(H, W, C)
,因此需要用transpose
调整轴顺序以正确显示图像。
# Specify the image size; create a plot with a figure size of 20 inches wide and 5 inches tall.
plt.figure(figsize=(20, 5))
for i, imgs in enumerate(imgs[:20]):
# Perform axis transformation
npimg = imgs.numpy().transpose((1, 2, 0))
# Divide the figure into 2 rows and 10 columns, and plot the (i+1)-th subplot.
plt.subplot(2, 10, i+1)
plt.imshow(npimg, cmap=plt.cm.binary)
plt.axis('off') # Turn off the axis display
构建简单的CNN网络
对于一般的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. 关于卷积层、池化层的计算:
下面的网络数据shape变化过程为:
3, 32, 32(输入数据) -> 64, 30, 30(经过卷积层1)-> 64, 15, 15(经过池化层1) -> 64, 13, 13(经过卷积层2)-> 64, 6, 6(经过池化层2) -> 128, 4, 4(经过卷积层3) -> 128, 2, 2(经过池化层3) -> 512 -> 256 -> num_classes(10)
num_classes = 10 # Number of image categories/classes
class Model(nn.Module):
def __init__(self):
super().__init__()
# Feature extraction network
self.conv1 = nn.Conv2d(3, 64, kernel_size=3) # First convolutional layer with a 3x3 kernel
self.pool1 = nn.MaxPool2d(kernel_size=2) # Pooling layer with a 2x2 kernel
self.conv2 = nn.Conv2d(64, 64, kernel_size=3) # Second convolutional layer with a 3x3 kernel
self.pool2 = nn.MaxPool2d(kernel_size=2) # Second pooling layer with a 2x2 kernel
self.conv3 = nn.Conv2d(64, 128, kernel_size=3) # Third convolutional layer with a 3x3 kernel
self.pool3 = nn.MaxPool2d(kernel_size=2) # Third pooling layer with a 2x2 kernel
# Classification network
self.fc1 = nn.Linear(512, 256) # Fully connected layer: 512 input units to 256 output units
self.fc2 = nn.Linear(256, num_classes) # Fully connected layer: 256 input units to `num_classes` output units
# Forward pass
def forward(self, x):
x = self.pool1(F.relu(self.conv1(x))) # Apply the first convolution, ReLU activation, and pooling
x = self.pool2(F.relu(self.conv2(x))) # Apply the second convolution, ReLU activation, and pooling
x = self.pool3(F.relu(self.conv3(x))) # Apply the third convolution, ReLU activation, and pooling
x = torch.flatten(x, start_dim=1) # Flatten the feature maps into a 1D tensor for the fully connected layers
x = F.relu(self.fc1(x)) # Apply the first fully connected layer with ReLU activation
x = self.fc2(x) # Apply the final fully connected layer for classification
return x # Return the output (logits) for each class
加载并打印模型。
# Move the model to the GPU (all model computations will be performed on the GPU)
model = Model().to(device) # Display a summary of the model architecture summary(model)
训练模型
设置超参数
loss_fn = nn.CrossEntropyLoss() # Create the loss function (Cross-Entropy Loss)
learn_rate = 1e-2 # Set the learning rate
opt = torch.optim.SGD(model.parameters(), lr=learn_rate) # Define the optimizer (Stochastic Gradient Descent) with the specified learning rate
编写训练函数
- 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()方法产生的。
# Training loop
def train(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset) # Total size of the training dataset
num_batches = len(dataloader) # Number of batches
train_loss, train_acc = 0, 0 # Initialize training loss and accuracy
for X, y in dataloader: # Iterate over batches, retrieving images (X) and their labels (y)
X, y = X.to(device), y.to(device) # Move data and labels to the specified device (e.g., GPU)
# Compute prediction error
pred = model(X) # Model output (predictions)
loss = loss_fn(pred, y) # Calculate the loss between the predictions and the true labels (targets)
# Backpropagation
optimizer.zero_grad() # Reset gradients to zero
loss.backward() # Perform backpropagation to compute gradients
optimizer.step() # Update model parameters using the computed gradients
# Record accuracy and loss
train_acc += (pred.argmax(1) == y).type(torch.float).sum().item() # Count correct predictions
train_loss += loss.item() # Accumulate the loss value
train_acc /= size # Average accuracy over the entire dataset
train_loss /= num_batches # Average loss over all batches
return train_acc, train_loss # Return training accuracy and loss
编写测试函数
测试函数和训练函数大致相同,但是由于不进行梯度下降对网络权重进行更新,所以不需要传入优化器。
def test(dataloader, model, loss_fn):
size = len(dataloader.dataset) # Total size of the test dataset, e.g., 10,000 images
num_batches = len(dataloader) # Number of batches, e.g., 313 (10,000/32, rounded up)
test_loss, test_acc = 0, 0 # Initialize test loss and accuracy
# Disable gradient calculation to save memory and computation during testing
with torch.no_grad():
for imgs, target in dataloader: # Iterate over test batches, retrieving images and their labels
imgs, target = imgs.to(device), target.to(device) # Move data and labels to the specified device (e.g., GPU)
# Compute loss
target_pred = model(imgs) # Model output (predictions)
loss = loss_fn(target_pred, target) # Calculate the loss between predictions and true labels
test_loss += loss.item() # Accumulate the loss value
test_acc += (target_pred.argmax(1) == target).type(torch.float).sum().item() # Count correct predictions
test_acc /= size # Average accuracy over the entire dataset
test_loss /= num_batches # Average loss over all batches
return test_acc, test_loss # Return test accuracy and loss
正式训练
- 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')
结果可视化
epochs_range = range(epochs) # Define the range of epochs for plotting
plt.figure(figsize=(12, 3)) # Set the figure size (width=12, height=3)
# Plot Training and Validation Accuracy
plt.subplot(1, 2, 1) # Create a subplot in a 1x2 grid (1 row, 2 columns), position 1
plt.plot(epochs_range, train_acc, label='Training Accuracy') # Plot training accuracy
plt.plot(epochs_range, test_acc, label='Test Accuracy') # Plot test accuracy
plt.legend(loc='lower right') # Add a legend in the lower-right corner
plt.title('Training and Validation Accuracy') # Add a title
# Plot Training and Validation Loss
plt.subplot(1, 2, 2) # Create a subplot in a 1x2 grid, position 2
plt.plot(epochs_range, train_loss, label='Training Loss') # Plot training loss
plt.plot(epochs_range, test_loss, label='Test Loss') # Plot test loss
plt.legend(loc='upper right') # Add a legend in the upper-right corner
plt.title('Training and Validation Loss') # Add a title
plt.show() # Display the plots