完整地模型训练套路
【摘要】 本程序主要介绍完整地模型训练套路,当loss为nan, 解决办法为减小学习速率
import torch.optim
import torchvision.datasets
from torch import nn
from torch.nn import Sequential, Conv2d, MaxPool2d, Flatten, Linear
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
# dataset, input
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)
# 输出数据集长度
train_data_size = len(train_data)
print("训练数据集的长度为: {}".format(train_data_size))
test_data_size = len(test_data)
print("测试数据集的长度为: {}".format(test_data_size))
# dataloader
train_dataloader = DataLoader(dataset=train_data, batch_size=64)
test_dataloader = DataLoader(dataset=test_data, batch_size=64)
# 搭建神经网络
class Tao(nn.Module):
def __init__(self):
super(Tao, self).__init__()
self.model = Sequential(
Conv2d(in_channels=3, out_channels=32, kernel_size=5, stride=1, padding=2),
MaxPool2d(kernel_size=2),
Conv2d(in_channels=32, out_channels=32, kernel_size=5, stride=1, padding=2),
MaxPool2d(kernel_size=2),
Conv2d(in_channels=32, out_channels=64, kernel_size=5, stride=1, padding=2),
MaxPool2d(kernel_size=2),
Flatten(),
Linear(in_features=64 * 4 * 4, out_features=64),
Linear(in_features=64, out_features=10)
)
def forward(self, x):
x = self.model(x)
return x
# 创建网络模型
tao = Tao()
# 创建损失函数
loss_fn = nn.CrossEntropyLoss()
# 定义优化器
learning_rate = 1e-4
optim = torch.optim.SGD(tao.parameters(), lr=learning_rate) # 随机梯度下降
# 设置训练网络的一些参数
# 记录训练的次数
total_train_step = 0
# 记录测试的次数
total_test_step = 0
# 训练的轮数
epoch = 10
# 使用tensorboard记录
writer = SummaryWriter('../logs_train')
for i in range(epoch):
print("-----第{}轮训练开始-----".format(i+1))
# 训练步骤开始
for data in train_dataloader:
imgs, targets = data
output = tao(imgs)
loss = loss_fn(output, targets) # 计算损失值
# 优化器优化模型
loss_fn.zero_grad() # 梯度清零
loss.backward() # 损失值进行反向传播
optim.step() # 优化器进行优化模型
total_train_step += 1
if total_train_step % 100 == 0:
print("训练次数: {}, Loss: {}".format(total_train_step, loss.item())) # item()挺好用的, 去掉类型, 只保留值
writer.add_scalar('train_loss', loss.item(), total_train_step)
# 测试步骤开始
total_test_loss = 0
total_accuracy = 0
with torch.no_grad():
for data in test_dataloader:
imgs, targets = data
output = tao(imgs)
loss = loss_fn(output, targets)
total_test_loss += loss.item()
# 添加正确率判断 argmax(1):横向, argmax(0):纵向
accuracy = (output.argmax(1) == targets).sum()
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 += 1
# 保存模型
torch.save(tao.state_dict(), 'tao_{}.pth'.format(i))
print('模型已保存')
writer.close()
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)