完整的模型训练套路
1.准备数据集
2.准备dataloader
3.创建网络模型
4.创建损失函数、优化器
5.设置训练参数
6.设置训练轮数
7.使网络进入训练状态
8.从dataloader中不断取数据
9.计算误差
10.利用优化器进行优化
11.特定步数训练结果进行输出
12.使网络进入测试状态
13.梯度清零
14.从测试数据集中取数据
15.计算loss
16.构建特殊评价指标并计算
17.输出训练效果
18.将某一轮的模型进行保存
代码实现:
import torch
outputs = torch.tensor([[0.1, 0.2],
[0.3, 0.4]])
# argmax(1)表示以行为单位看,得出结果。0为以列为单位看
print(outputs.argmax(1))
preds = outputs.argmax(1)
targets = torch.tensor([0, 1])
print((preds == targets).sum())
结果:
import torchvision
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
# 将model文件夹中有的东西都引入过来
from model import *
# 准备数据集
train_data = torchvision.datasets.CIFAR10("data", train=True, transform=torchvision.transforms.ToTensor(),
download=True)
test_data = torchvision.datasets.CIFAR10("data", train=False, transform=torchvision.transforms.ToTensor(),
download=True)
# 看一下训练数据集和测试数据集有多少张 len-length 长度
train_data_size = len(train_data)
test_data_size = len(test_data)
# python中常用的写法:字符串格式化
print("训练数据集的长度为:{}".format(train_data_size))
print("测试数据集的长度为:{}".format(test_data_size))
# 用DataLoader加载数据集
train_dataloader = DataLoader(train_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)
# 创建网络模型
peipei = Peipei()
# 创建损失函数
loss_fn = nn.CrossEntropyLoss()
# 定义优化器
# 1e-2 = 0.01
learning_rate = 1e-2
optimizer = torch.optim.SGD(peipei.parameters(), lr=learning_rate)
# 设置训练网络的一些参数
# 记录训练次数
total_train_step = 0
# 记录测试次数
total_test_step = 0
# 训练的轮数
epoch = 10
# 添加tensorboard
writer = SummaryWriter("logs_train")
# i从0-9
for i in range(epoch):
print("--------------------第{}轮训练开始--------------------".format(i + 1))
# 训练步骤开始
# 使模型进入训练状态,但只对特定层(Dropout,BatchNorm层)起作用
peipei.train()
for data in train_dataloader:
imgs, targets = data
outputs = peipei(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:
print("训练次数:{},loss:{}".format(total_train_step, loss.item()))
writer.add_scalar("train_loss", loss.item(), total_train_step)
# 测试步骤开始
# 使模型进入验证状态,但只对特定层(Dropout,BatchNorm层)起作用
peipei.eval()
total_test_loss = 0
totel_accuracy = 0
with torch.no_grad():
for data in test_dataloader:
imgs, targets = data
outputs = peipei(imgs)
loss = loss_fn(outputs, targets)
# 计算整体测试集损失函数
total_test_loss = total_test_loss + loss.item()
# 计算整体正确率
accuracy = (outputs.argmax(1) == targets).sum()
totel_accuracy = totel_accuracy + accuracy
print("整体测试集上的Loss:{}".format(total_test_loss))
print("整体测试集上的正确率:{}".format(totel_accuracy / test_data_size))
writer.add_scalar("test_loss", total_test_loss, total_test_step)
writer.add_scalar("test_accuracy", totel_accuracy / test_data_size, total_test_step)
total_test_step = total_test_step + 1
# 对每轮训练完的模型保存
torch.save(peipei, "peipei_{}.pth".format(i))
writer.close()
结果:
Files already downloaded and verified
Files already downloaded and verified
训练数据集的长度为:50000
测试数据集的长度为:10000
--------------------第1轮训练开始--------------------
训练次数:100,loss:2.290673017501831
训练次数:200,loss:2.2843034267425537
训练次数:300,loss:2.272620677947998
训练次数:400,loss:2.2246286869049072
训练次数:500,loss:2.1384975910186768
训练次数:600,loss:2.045639753341675
训练次数:700,loss:2.023395538330078
整体测试集上的Loss:317.1579200029373
整体测试集上的正确率:0.27239999175071716
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
--------------------第10轮训练开始--------------------
训练次数:7100,loss:1.279011845588684
训练次数:7200,loss:1.0039513111114502
训练次数:7300,loss:1.131661295890808
训练次数:7400,loss:0.870675265789032
训练次数:7500,loss:1.250161051750183
训练次数:7600,loss:1.2308332920074463
训练次数:7700,loss:0.8774276375770569
训练次数:7800,loss:1.242829442024231
整体测试集上的Loss:198.48021519184113
整体测试集上的正确率:0.5526000261306763