模型训练步骤
- 准备数据集
- 获取数据集长度(包括训练集和测试集)
- 利用DataLoader来加载数据集
- 搭建网络模型
- 创建网络模型
- 定义损失函数
- 定义优化器
- 设置训练参数(记录训练次数、记录测试次数、训练的轮数)
- 训练步骤开始
- 将训练集添加到网络模型中
- 计算损失函数
- 梯度归零
- 优化器优化模型
- 反向传播,计算每个参数梯度值
- 通过梯度下降执行一步梯度更新
- 测试步骤开始
- 设置无梯度
- 将测试集添加到网络模型中
- 计算损失函数
- 计算每行最大值,取得正确率
- 保存网络模型
Argmax方法详解
Argmax 比较一组元素中最大值所在的索引
outputs = [0.1, 0.2]
[0.05, 0.4]
output.argmax(1) 横向比较 输出[1, 1] 第一行第1个元素,第二行第1个元素
output.argmax(0) 纵向比较 输出[0, 1] 第一列第0个元素,第二列第1个元素
preds = outputs.argmax(1)
targets = torch.tensor([0, 1])
print(preds == targets) 输出tensor([False, True])
print((preds == target).sum()) 输出tensor(1)
具体代码
搭建神经网络
import torch
from torch import nn
# 搭建神经网络
class TestNN(nn.Module):
def __init__(self):
super(TestNN, self).__init__()
self.model1 = nn.Sequential(
nn.Conv2d(3, 32, 5, 1, padding=2),
nn.MaxPool2d(2),
nn.Conv2d(32, 32, 5, 1, padding=2),
nn.MaxPool2d(2),
nn.Conv2d(32, 64, 5, 1, padding=2),
nn.MaxPool2d(2),
nn.Flatten(),
nn.Linear(64*4*4, 64),
nn.Linear(64, 10)
)
def forward(self, x):
x = self.model1(x)
return x
if __name__ == '__main__':
tnn = TestNN()
inputData = torch.ones((64, 3, 32, 32))
output = tnn(inputData)
print(output.shape)
执行模型训练
import torchvision
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from test_model import *
from torch import nn
import torch
import time
# 准备数据集
train_data = torchvision.datasets.CIFAR10(root="./dataset", train=True, transform=torchvision.transforms.ToTensor(),
download=True)
test_data = torchvision.datasets.CIFAR10(root="./dataset", train=False, transform=torchvision.transforms.ToTensor(),
download=True)
# length长度
train_data_length = len(train_data)
test_data_length = len(test_data)
print("训练数据集长度为:{}".format(train_data_length))
print("测试数据集长度为:{}".format(test_data_length))
# DataLoader加载数据集
train_dataLoader = DataLoader(train_data, batch_size=64)
test_dataLoader = DataLoader(test_data, batch_size=64)
# 创建网络模型
tnn = TestNN()
# 损失函数
loss_fn = nn.CrossEntropyLoss()
# 优化器
# learning_rate = 0.01
# 1e-2 = 1 × (10)^(-2) = 1 / 100 = 0.01
learning_rate = 1e-2
optimizer = torch.optim.SGD(tnn.parameters(), lr=learning_rate)
# 设置训练网络的一些参数
# 记录训练的次数
total_train_step = 0
# 记录测试的次数
total_test_step = 0
# 训练的轮数
epoch = 10
writer = SummaryWriter("logs")
start_time = time.time()
for i in range(epoch):
print("-----第{}轮训练开始-----".format(i + 1))
# 训练步骤开始
tnn.train()
for data in train_dataLoader:
imgs, targets = data
outputs = tnn(imgs)
loss = loss_fn(outputs, targets)
# 优化器优化模型
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_train_step = total_train_step + 1
if total_train_step % 100 == 0:
end_time = time.time()
print(end_time - start_time)
print("训练次数:{},Loss:{}".format(total_train_step, loss.item()))
writer.add_scalar("train_loss", loss.item(), total_train_step)
# 测试步骤开始
tnn.eval()
total_test_loss = 0
total_accuracy = 0 # 整体正确的个数
with torch.no_grad(): # 设置无梯度
for data in test_dataLoader:
imgs, targets = data
output = tnn(imgs)
loss = loss_fn(output, targets)
total_test_loss = total_test_loss + loss.item()
accuracy = (output.argmax(1) == targets).sum()
total_accuracy = total_accuracy + accuracy
print("整体测试集上的Loss:{}".format(total_test_loss))
print("整体测试集上的正确率:{}".format(total_accuracy / test_data_length))
writer.add_scalar("test_loss", total_test_loss, total_test_step)
writer.add_scalar("test_accuracy", total_accuracy / test_data_length, total_test_step)
total_test_step = total_test_step + 1
# torch.save(tnn, "tnn_{}.pth".format(i))
# torch.save(tnn.state_dic(), "tnn_{}.pth".format(i))
print("模型已保存")
writer.close()