完整的模型训练套路
一般把model放到单独的.py文件中,并在文件中对模型的正确性进行验证。
import torch
from torch import nn
# 搭建神经网络
class Ceshi(nn.Module):
def __init__(self):
super(Ceshi, self).__init__()
self.model = nn.Sequential(
nn.Conv2d(3, 32, 5, 1, 2),
nn.MaxPool2d(2),
nn.Conv2d(32, 32, 5, 1, 2),
nn.MaxPool2d(2),
nn.Conv2d(32, 64, 5, 1, 2),
nn.MaxPool2d(2),
nn.Flatten(),
nn.Linear(1024, 64),
nn.Linear(64, 10)
)
def forward(self, x):
x = self.model(x)
return x
if __name__ == '__main__':
ceshi = Ceshi()
# 验证模型的正确性
input = torch.ones((64, 3, 32, 32))
output = ceshi(input)
print(output.shape)
训练代码如下:
import torchvision
from torch.utils.data import DataLoader
# 引入model
from torch.utils.tensorboard import SummaryWriter
from model import *
# 准备数据集
train_data = torchvision.datasets.CIFAR10("./data1", train=True, transform=torchvision.transforms.ToTensor(), download=True)
test_data = torchvision.datasets.CIFAR10("./data1", train=False, transform=torchvision.transforms.ToTensor(), download=True)
# 加载数据集
train_dataloader = DataLoader(train_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)
# 创建网络模型
ceshi = Ceshi()
# 损失函数
loss_fn = nn.CrossEntropyLoss()
# 优化器
learning_rate = 1e-2
optimaize = torch.optim.SGD(ceshi.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))
# 训练步骤开始
ceshi.train()
for data in train_dataloader:
imgs, targets = data
outputs = ceshi(imgs)
loss = loss_fn(outputs, targets)
# 优化器优化模型
optimaize.zero_grad()
loss.backward()
optimaize.step()
total_train_step += 1
if total_train_step % 100 == 0:
print("训练次数:{} 损失函数:{}".format(total_train_step, loss.item()))
writer.add_scalar("train_loss", loss.item(), total_train_step)
# 测试步骤开始
ceshi.eval()
total_test_loss = 0
total_accuracy = 0
with torch.no_grad():
for data in test_dataloader:
imgs, targets = data
outputs = ceshi(imgs)
loss = loss_fn(outputs, targets)
total_test_loss += loss.item()
accuracy = (outputs.argmax(1) == targets).sum()
total_accuracy += accuracy
print("整体测试集上的Loss:{}".format(total_test_loss))
print("整体测试集上的正确率:{}".format(total_accuracy/len(test_data)))
writer.add_scalar("test_loss", total_test_loss, total_test_step)
writer.add_scalar("test_accuracy", total_accuracy/len(test_data), total_test_step)
total_test_step += 1
if i == 9:
torch.save(ceshi, "ceshi_{}.pth".format(i))
print("模型已保存")
writer.close()
训练结果如下:
保存的模型:
可视化结果如下:
下面解释下train()和eval():
使用model.train()的作用是把网络设置成训练的模式,它只对部分的网络层有作用,比如Dropout层。当网络模型中有Dropout等这些层的时候可以调用model.train():
eval()的作用是把网络设置成验证的模式,同样只对部分网络层有作用: