这三个视频介绍了如何完整的的训练模型,一数据集CIFAR10为例
1.准备数据集,测试数据集和训练数据集
#准备训练数据集和测试数据集
train_data = torchvision.datasets.CIFAR10(root='./data', train=True, download=True,
transform=torchvision.transforms.ToTensor())
test_data = torchvision.datasets.CIFAR10(root='./data', train=False, download=True,
transform=torchvision.transforms.ToTensor())
2.看看数据集长度,这个数据集相对来说比较短
#length 长度
train_data_size = len(train_data)
test_data_size = len(test_data)
#train_data_size =10,训练数据集的长度为:10
print("训练数据集的长度为:{}".format(train_data_size))
print("测试数据集的长度为:{}".format(test_data_size))
3.DataLoader加载数据集
#用DataLoader 来加载数据集
train_loader = DataLoader(train_data, batch_size=64, shuffle=True)
test_loader = DataLoader(test_data, batch_size=64, shuffle=True)
4.建立网络模型,一般网络模型在一个单独的py文件当中
model.py
#搭建 神经网络
from torch import nn
class Tudui(nn.Module):
def __init__(self):
super(Tudui, self).__init__()
self.model1 = nn.Sequential(
nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, padding=2),
nn.MaxPool2d(kernel_size=2),
nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, padding=2),
nn.MaxPool2d(kernel_size=2),
nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, padding=2),
nn.MaxPool2d(kernel_size=2),
# 展现数据
nn.Flatten(),
nn.Linear(in_features=1024, out_features=64),
nn.Linear(in_features=64, out_features=10)
)
def forward(self, x):
x = self.model1(x)
return x
在主文件当中引入model.py
#引入网络模型文件
from model import *
#网络模型 (单独的model.py 文件)
tudui = Tudui()
5.计算损失函数
#损失函数
loss_fu = nn.CrossEntropyLoss()
6.设置优化器优化模型
#优化器优化模型
#1e-2 = (10)^(-2) = 1/100 =0.01
learing_rate = 1e-2
optimizer = torch.optim.SGD(tudui.parameters(), lr=learing_rate)
7.设置训练模型的一些参数
#设置训练网络的一些参数
#记录训练的次数
total_train_step = 0
#记录测试的次数
total_test_step = 0
#训练轮数
epoch = 10
#添加tensorboard
writer = SummaryWriter('./logs_train')
for i in range(epoch):
print("第{}轮训练开始".format(i+1))
8.开始训练
# 训练开始
for data in train_loader:
imgs, targets = data
ouputs = tudui(imgs)
loss = loss_fu(ouputs, 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)
9.测试,保存模型
在PyTorch中,torch.no_grad()
是一个上下文管理器,它用于在执行代码块时暂时将所有张量(Tensor)的.requires_grad
属性设置为False
。这主要用于推理(inference)模式,即当你不需要计算梯度时,比如模型评估或部署时。使用torch.no_grad()
可以显著提高计算速度和减少内存消耗,因为它避免了在不需要时跟踪梯度。
#测试步骤开始
total_test_loss = 0.0
with torch.no_grad():
for data in test_loader:
imgs,targets = data
outputs = tudui(imgs)
loss = loss_fu(outputs, targets)
total_test_loss += loss.item()
print("整体测试集上的Loss:{}".format(total_test_loss))
writer.add_scalar('test_loss', total_test_loss, total_test_step)
total_test_step += 1
#保存模型
torch.save(tudui, 'tudui_{}.pth'.format(i))
print("模型已保存")
10.测试正确率
#正确率
total_accuracy = 0.0
for data in test_loader:
imgs,targets = data
outputs = tudui(imgs)
loss = loss_fu(outputs, targets)
total_test_loss += loss.item()
accuracy = (outputs.argmax(1) == targets).sum()
total_accuracy += accuracy
print("测试集上的正确率:{}".format(total_accuracy/test_data_size))
writer.add_scalar("test_accuracy", total_accuracy/test_data_size, total_test_step)
完整代码:
import torch
import torchvision
from torch import nn
from torch.utils.tensorboard import SummaryWriter
#引入网络模型文件
from model import *
from torch.utils.data import DataLoader
#准备训练数据集和测试数据集
train_data = torchvision.datasets.CIFAR10(root='./data', train=True, download=True,
transform=torchvision.transforms.ToTensor())
test_data = torchvision.datasets.CIFAR10(root='./data', train=False, download=True,
transform=torchvision.transforms.ToTensor())
#length 长度
train_data_size = len(train_data)
test_data_size = len(test_data)
#train_data_size =10,训练数据集的长度为:10
print("训练数据集的长度为:{}".format(train_data_size))
print("测试数据集的长度为:{}".format(test_data_size))
#用DataLoader 来加载数据集
train_loader = DataLoader(train_data, batch_size=64, shuffle=True)
test_loader = DataLoader(test_data, batch_size=64, shuffle=True)
#网络模型 (单独的model.py 文件)
tudui = Tudui()
#损失函数
loss_fu = nn.CrossEntropyLoss()
#优化器优化模型
#1e-2 = (10)^(-2) = 1/100 =0.01
learing_rate = 1e-2
optimizer = torch.optim.SGD(tudui.parameters(), lr=learing_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_loader:
imgs, targets = data
ouputs = tudui(imgs)
loss = loss_fu(ouputs, 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)
#测试步骤开始
total_test_loss = 0.0
#正确率
total_accuracy = 0.0
with torch.no_grad():
for data in test_loader:
imgs,targets = data
outputs = tudui(imgs)
loss = loss_fu(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/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(tudui, 'tudui_{}.pth'.format(i))
print("模型已保存")
writer.close()