以 CIFAR10 数据集为例,分类问题(10分类)
model.py
import torch
from torch import nn# 搭建神经网络
class MyNN(nn.Module):def __init__(self):super(MyNN, 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(64 * 4 * 4, 64),nn.Linear(64, 10))def forward(self, x):x = self.model(x)return xif __name__ == '__main__':# 验证网络的正确性mynn = MyNN()input = torch.ones(64,3,32,32)output = mynn(input)print(output)
运行结果:torch.Size([64,10])
返回64行数据,每一行数据有10个数据,代表每一张图片在10个类别中的概率
train.py
import torchvision
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
# model.py必须和train.py在同一个文件夹下
from model import *# 准备数据集(CIFAR10 数据集是PIL Image,要转换为tensor数据类型)
train_data = torchvision.datasets.CIFAR10(root="../datasets",train=True,transform=torchvision.transforms.ToTensor(),download=False)
test_data = torchvision.datasets.CIFAR10(root="../datasets",train=False,transform=torchvision.transforms.ToTensor(),download=False)# 获得数据集的长度
train_data_size = len(train_data)
test_data_size = len(test_data)
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)# 创建网络模型
mynn = MyNN()
# 损失函数
loss_function = nn.CrossEntropyLoss()
# 优化器
learning_rate = 1e-2
optimizer = torch.optim.SGD(mynn.parameters(), lr=learning_rate) # SGD 随机梯度下降# 设置训练网络的一些参数
total_train_step = 0 # 记录训练次数
total_test_step = 0 # 记录测试次数
epoch = 10 # 训练的轮数# 添加tensorboard
writer = SummaryWriter("../logs_train")for i in range(epoch):print("----------第{}轮训练开始----------".format(i+1))# 训练步骤开始mynn.train()for data in train_dataloader:imgs,targets = dataoutputs = mynn(imgs)loss = loss_function(outputs, targets)# 优化器优化模型optimizer.zero_grad() # 首先要梯度清零loss.backward() # 反向传播得到每一个参数节点的梯度optimizer.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)# 测试步骤开始mynn.eval()total_test_loss = 0total_accuracy = 0# 无梯度,不进行调优with torch.no_grad():for data in test_dataloader:imgs,targets = dataoutputs = mynn(imgs)loss = loss_function(outputs, targets)total_test_loss += loss# 即便得到整体测试集上的 loss,也不能很好说明在测试集上的表现效果# 在分类问题中可以用正确率表示accuracy = (outputs.argmax(1) == targets).sum()total_accuracy += accuracyprint("整体测试集上的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(mynn,"mynn_{}.pth".format(i))# torch.save(mynn.state_dict(),"mynn_{}.pth".format(i))print("模型已保存")writer.close()
关于正确率的计算:
方式1:
import torchoutputs = torch.tensor([[0.1,0.2],[0.3,0.4]]) target = torch.tensor([0,1])predict = outputs.argmax(1) print(predict)print(predict == target) print((predict == target).sum())
方式2:
import torchoutputs = torch.tensor([[0.1,0.2],[0.3,0.4]]) target = torch.tensor([0,1])predict = torch.max(outputs, dim=1)[1] print(predict)print(torch.eq(predict,target)) print(torch.eq(predict,target).sum()) print(torch.eq(predict,target).sum().item())
关于mynn.train()和mynn.eval():
这两句不写网络依然可以运行,它们的作用是:
这个案例没有 Dropout 层或 BatchNorm 层,所以有没有这两行都无所谓。但如果有这些特殊层,一定要调用。