训练过程
代码
nn.py
import torch
import torchvision.datasets
from torch.nn import CrossEntropyLoss
from torch.optim import SGD
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from model import *
# 定义训练的设备
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# 1.获取数据
train_data = torchvision.datasets.CIFAR10('data', True, torchvision.transforms.ToTensor(), download=True)
test_data = torchvision.datasets.CIFAR10('data', False, torchvision.transforms.ToTensor(), download=True)
# 获取训练、测试数据的长度
train_data_size = len(train_data)
test_data_size = len(test_data)
# 2.加载数据
train_dataloader = DataLoader(train_data, 64)
test_dataloader = DataLoader(test_data, 64)
# 创建网络模型
tudui = Tudui()
tudui.to(device)
# 创建损失函数
loss_fn = CrossEntropyLoss()
loss_fn.to(device)
# 创建优化器
learning_rate = 0.01
optimizer = SGD(tudui.parameters(), lr=learning_rate)
'''
设置训练网络的一些参数
'''
# 记录训练的次数
total_train_step = 0
# 记录测试的次数
total_test_step = 0
# 训练的轮数
epoch = 10
# 添加tensorboard
writer = SummaryWriter('logs')
for i in range(epoch):
print('-------第{}轮训练开始-------'.format(i))
# 训练步骤开始
tudui.train()
for data in train_dataloader:
imgs, targets = data
imgs = imgs.to(device)
targets = targets.to(device)
outputs = tudui(imgs)
# 计算损失
loss = loss_fn(outputs, targets)
# 优化器优化模型
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 使用print和tensorboard显示效果
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)
# 测试步骤开始
tudui.eval()
total_test_loss = 0
total_accuracy = 0
with torch.no_grad():
for data in test_dataloader:
imgs, targets = data
imgs = imgs.to(device)
targets = targets.to(device)
outputs = tudui(imgs)
loss = loss_fn(outputs, targets) # tensor类型
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)
total_test_step += 1
# 整体一轮训练保存一次模型
torch.save(tudui, 'tudui_{}.pth'.format(i))
writer.close()
- model.py
import torch
from torch import nn
from torch.nn import Sequential, Conv2d, MaxPool2d, Flatten, Linear
class Tudui(nn.Module):
def __init__(self):
super(Tudui, self).__init__()
self.model = Sequential(
Conv2d(3, 32, 5, padding=2),
MaxPool2d(kernel_size=2),
Conv2d(32, 32, 5, padding=2),
MaxPool2d(kernel_size=2),
Conv2d(32, 64, 5, padding=2),
MaxPool2d(kernel_size=2),
Flatten(),
Linear(1024, 64),
Linear(64, 10)
)
def forward(self, input):
return self.model(input)
if __name__ == '__main__':
# 测试
tudui = Tudui()
input = torch.ones((64, 3, 32, 32))
output = tudui(input)
print(output)
- 最后我们可以在tensorboard上查看,则在Terminal控制台输入命令:
tensorboard --logdir "logs"
测试、验证
test.py
'''
模型验证
'''
import torch
import torchvision.transforms
from PIL import Image
from torch import nn
from torch.nn import Sequential, Conv2d, MaxPool2d, Linear, Flatten
# 准备测试的图片
img_path = 'imgs/airplane.png'
image = Image.open(img_path)
# print(image)
# torchvision.transforms.Resize((32,32)是为了与训练模型图片大小相对应
transform = torchvision.transforms.Compose([torchvision.transforms.Resize((32,32)),
torchvision.transforms.ToTensor()])
image = transform(image)
# print(image.shape)
# class Tudui(nn.Module):
# def __init__(self):
# super(Tudui, self).__init__()
# self.model = Sequential(
# Conv2d(3, 32, 5, padding=2),
# MaxPool2d(kernel_size=2),
# Conv2d(32, 32, 5, padding=2),
# MaxPool2d(kernel_size=2),
# Conv2d(32, 64, 5, padding=2),
# MaxPool2d(kernel_size=2),
# Flatten(),
# Linear(1024, 64),
# Linear(64, 10)
# )
# def forward(self, input):
# return self.model(input)
# 加载模型,已经训练好的模型,但由于训练次数少,可能结果不准确
# map_location:当我们训练模型使用GPU,此时使用CPU测试,则需要添加这个参数
model = torch.load('tudui_9.pth', map_location=torch.device('cpu'))
# print(model)
# 继续调图片格式
image = torch.reshape(image, (1, 3, 32, 32))
# 开始测试
model.eval()
with torch.no_grad():
output = model(image)
# print(output)
print(output.argmax(1))