本篇自学笔记来自于b站《PyTorch深度学习快速入门教程(绝对通俗易懂!)【小土堆】》,Up主讲的非常通俗易懂,文章下方有视频连接,如有需要可移步up主讲解视频,如有侵权,实非故意,深表歉意,请与我联系,删除相关内容!
本节主要展示完整的网络模型训练套路和验证套路。
训练套路:1.准备数据集(以CIFAR10为例)
2.加载数据集(DataLoader)
3.搭建神经网络(使用之前第六讲搭建好的)
4.创建网络模型
5.定义损失函数(使用交叉熵损失函数)
6.定义优化器(使用SGD)
7.设置训练过程中的一些参数
8.开始训练:
取数据-->将数据放入网络模型-->计算loss-->梯度清零-->反向传播-->优化
以下为代码展示:
import torch
import torchvision
from test_seq_net import *
#准备数据集
from torch.utils.data import DataLoader
train_dataset = torchvision.datasets.CIFAR10(root='dataset',train=True,transform=torchvision.transforms.ToTensor(),download=True)
test_dataset = torchvision.datasets.CIFAR10(root='dataset',train=False,transform=torchvision.transforms.ToTensor(),download=True)
#加载数据集
train_loader = DataLoader(dataset=train_dataset,batch_size=64)
test_loader = DataLoader(dataset=test_dataset,batch_size=64)
#搭建神经网络
#此处采用的网络模型为之前以CIFAR10的model搭建的网络,直接引入
#创建网络模型
model = Model()
#定义损失函数
Loss = nn.CrossEntropyLoss()
#定义优化器
lr = 0.01
optim = torch.optim.SGD(model.parameters(),lr=lr)
#设置一些网络训练的参数
#训练次数
train_num = 0
#测试次数
test_num = 0
#训练轮数
epochs = 10
#训练集损失
every_epoch_loss = 0
#测试集损失
test_loss = 0
total_accuracy = 0
writer = SummaryWriter("logs")
#开始训练步骤
for epoch in range(epochs):
for data in train_loader:
imgs,targets = data
outputs = model(imgs)
loss = Loss(outputs,targets)
optim.zero_grad()
loss.backward()
optim.step()
train_num += 1
every_epoch_loss += loss
if train_num % 100 == 0:
print("------第 {} 次训练,loss为:{}".format(train_num,loss))
writer.add_scalar("tran_loss",loss,train_num)
print("----第{}个epoch的loss为:{}".format(epoch+1,every_epoch_loss))
#测试步骤
with torch.no_grad():
for data in test_loader:
imgs,targets = data
outputs = model(imgs)
loss = Loss(outputs,targets)
test_loss += loss
accuracy = (outputs.argmax(1)==targets).sum()
total_accuracy += accuracy
test_num += 1
print("---测试集整体loss:{}---".format(test_loss))
print("---在测试集上准确率为:{}---".format(total_accuracy/len(test_dataset)))
writer.add_scalar("test_loss",test_loss,test_num)
writer.add_scalar("test_acc",total_accuracy/len(test_dataset),epoch+1)
#torch.save(model,"model_{}.pth".format(epoch))
writer.close()
验证套路:1.读取验证数据
2.加载训练好的网络模型
3.with torch.no_grad()
4.把数据放入模型得到输出,输出output.argmax(1)得到概率最大的位置即为输出 ·· 的图片类别。
#完整的模型验证套路
#获取数据
import os
import torch
import torchvision
from PIL import Image
from torch import nn
from torch.utils.data import Dataset
class Dataread(Dataset):
def __init__(self,img_path):
self.img_path = img_path
self.img = os.listdir(self.img_path)
def __getitem__(self, item):
img_name = self.img[item]
img_info = os.path.join(self.img_path,img_name)
img = Image.open(img_info)
return img
def __len__(self):
return len(self.img)
class Model(nn.Module):
def __init__(self):
super().__init__()
self.model = 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):
output = self.model(x)
return output
img_path = "dataset/test_img"
img = Dataread(img_path)
img_num = len(img)
transform = torchvision.transforms.Compose([torchvision.transforms.Resize((32,32)),
torchvision.transforms.ToTensor()])
model = torch.load("train_model/model_20.pth")
for i in range(img_num):
data = img[i]
data = data.convert('RGB')
data = transform(data)
data = torch.reshape(data,(1,3,32,32))
with torch.no_grad():
output = model(data)
print(output.argmax(1))
附视频地址:PyTorch深度学习快速入门教程(绝对通俗易懂!)【小土堆】_哔哩哔哩_bilibili