采用CIFAR10数据集
步骤:
1. 准备数据集
2. 运用dataloader下载数据
3. 搭建神经网络
4. 创建损失函数
5. 创建优化器
6. 设置训练轮数
实例:
# 神经网络——完整的模型训练套路
import torch
import torchvision
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from model import *
# 准备数据集
train_data = torchvision.datasets.CIFAR10("../pytorch_learn/dataset2", train=True, transform=torchvision.transforms.ToTensor(),
download=True)
test_data = torchvision.datasets.CIFAR10("../pytorch_learn/dataset2", train=False, transform=torchvision.transforms.ToTensor(),
download=True)
# 数据集长度
train_data_size = len(train_data) #50000
test_data_size = len(test_data) #10000
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)
# 搭建神经网络(CIFAR10是一个10分类的类别)存在model文件中
# 创建网络模型
test = Test()
# 创建损失函数
loss_fn = nn.CrossEntropyLoss()
# 优化器
learning_rate = 0.01
optimizer = torch.optim.SGD(params=test.parameters(), lr=learning_rate)
# 设置训练网络的一些参数
# 记录训练的次数
total_train_step = 0.0
# 记录测试的次数
total_test_step = 0.0
# 记录训练的轮数
epoch = 10
# 添加tensorboard
writer = SummaryWriter("logs_train")
for i in range(epoch):
print("--------第 {} 轮训练开始---------".format(i+1))
# 训练步骤开始
test.train()# 进入训练模式。(非必须)只对特定层起作用
for data in train_dataloader:
imgs, targets = data
output = test(imgs)
# 输出放入损失函数中
loss = loss_fn(output, 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)
# 测试步骤 # 进入测试模式。(非必须)只对特定层起作用
test.eval()
total_test_loss = 0.0
total_accuracy = 0.0
with torch.no_grad(): # 不生成梯度
for data in test_dataloader:
imgs, targets = data
output = test(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_size))
writer.add_scalar("test_loss", total_test_loss, total_test_step)
writer.add_scalar("test_accuracy", total_accuracy/test_data_size, total_test_step)
total_test_step = total_test_step + 1
# 保存模型
torch.save(test, "test_{}.pth".format(i))
print("第 {} 轮模型已保存".format(i + 1))
writer.close()
|