语言环境:Python3.8
● 编辑器:pycharm
● 学习环境:Pytorch11.7
CIFAR10数据集有60000张彩色图像,图像为32*32*3,分为10类,每类各6000张
其中50000张用于训练,构成5个训练批次,每一批次10000张;
剩下10000张的用于测试,构成1个批次,取10类中的每一类,每一类随机1000张。
import torch
#nn为神经网络
import torch.nn as nn
import matplotlib.pyplot as plt
import torchvision
# 一、 数据准备
# --- 1、设置GPU ---
import torchvision.datasets
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# ---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=False)
#使用dataloader加载数据,并设置好基本的batch_size
#图片数为20张
batch_size = 20
train_dl = torch.utils.data.DataLoader(train_ds,
batch_size=batch_size,
shuffle=False)
test_dl = torch.utils.data.DataLoader(test_ds, batch_size=batch_size)
#随机获取一批数据
imgs, labels = next(iter(train_dl))
# ---3、数据可视化---
#随机获取一批数据
imgs, labels = next(iter(train_dl))
#指定图片大小,图像大小为20宽、5高的绘图(单位为英寸inch)
plt.figure(figsize=(32, 5))
for i, imgs in enumerate(imgs):
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.show()
知识点:
特征图尺寸的计算公式为:[(原图尺寸-卷积核尺寸)/步长]+1
import torch.nn.functional as F
num_classes = 10 # 图片的类别数
class Model(nn.Module):
def __init__(self):
super().__init__()
# 特征提取网络
# 卷积层1, 输出是32*32*3,计算(32-3)/1+1=30,那么通过conv1输出的结果为30*30*64
#input:3, output:64, kernel:3(卷积核)
self.conv1 = nn.Conv2d(3, 64, kernel_size=3)
#池化层1, 输入为30*30*64, 窗口为2*2,计算30/2=15, 通过max_pooll层输出结果是15*15*64
self.pool1 = nn.MaxPool2d(2)
#卷积层2, 输入是15*15*64, 计算(15-3)/1+1=13.那么通过conv2输出的结果为13*13*64
#input:64, output:64, kernel:3
self.conv2 = nn.Conv2d(64, 64, kernel_size=3)
#池化层2, 输入为13*13*64, 窗口为2*2,计算13/2=6, 通过max_pooll层输出结果是6*6*64
self.pool2 = nn.MaxPool2d(2)
# 卷积层3, 输出是6*6*64,计算(6-3)/1+1=4,那么通过conv1输出的结果为4*4*128
#input:64, output:128, kernel:3
self.conv3 = nn.Conv2d(64, 128, kernel_size=3)
#池化层3, 输入为4*4*128, 窗口为2*2,计算4/2=2, 通过max_pooll层输出结果是2*2*128
self.pool3 = nn.MaxPool2d(2)
# 分类网络
#全连接层1
#input:512, output:256
self.fc1 = nn.Linear(512, 256)
self.fc2 = nn.Linear(256, num_classes)
# 前向传播
def forward(self, x):
#卷积1:32*32*3——30*30*64——15*15*64
x = self.pool1(F.relu(self.conv1(x)))
#卷积2:15*15*64——13*13*64——6*6*64
x = self.pool2(F.relu(self.conv2(x)))
#卷积3:6*6*64——4*4*128——2*2*128
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
打印并加载模型
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
=================================================================
#三、训练模型
#设置超参数
loss_fn = nn.CrossEntropyLoss() # 创建损失函数
learn_rate = 1e-2 # 学习率
opt = torch.optim.SGD(model.parameters(),lr=learn_rate) # 优化器
#训练循环
def train(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset) # 训练集的大小,一共60000张图片
num_batches = len(dataloader) # 批次数目,3000(60000/20)
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
#编写测试函数
def test(dataloader, model, loss_fn):
size = len(dataloader.dataset) # 测试集的大小,一共10000张图片
num_batches = len(dataloader) # 批次数目,500(10000/20=500)
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
#正式训练
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')
#结果可视化
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()
=================================================================
Epoch: 1, Train_acc:18.0%, Train_loss:2.194, Test_acc:24.7%,Test_loss:2.002
Epoch: 2, Train_acc:31.3%, Train_loss:1.860, Test_acc:39.4%,Test_loss:1.655
Epoch: 3, Train_acc:42.0%, Train_loss:1.582, Test_acc:45.7%,Test_loss:1.489
Epoch: 4, Train_acc:48.2%, Train_loss:1.434, Test_acc:50.4%,Test_loss:1.363
Epoch: 5, Train_acc:53.2%, Train_loss:1.314, Test_acc:54.5%,Test_loss:1.271
Epoch: 6, Train_acc:56.7%, Train_loss:1.217, Test_acc:57.5%,Test_loss:1.199
Epoch: 7, Train_acc:60.1%, Train_loss:1.135, Test_acc:60.5%,Test_loss:1.125
Epoch: 8, Train_acc:62.9%, Train_loss:1.064, Test_acc:62.5%,Test_loss:1.072
Epoch: 9, Train_acc:65.4%, Train_loss:1.002, Test_acc:63.9%,Test_loss:1.033
Epoch:10, Train_acc:67.2%, Train_loss:0.945, Test_acc:65.4%,Test_loss:0.999
Done