一、CIFAR10数据集介绍
CIFAR10数据集共有十个类别,分别是airplane、automobile、bird、cat、deer、dog、frog、horse、ship、truck
二、模型训练
模型代码:
class Net(nn.Module):
def __init__(self):
super(Net, 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 x
gpu训练代码:(使用gpu训练速度很快,几分钟就可以完成,30轮训练完成后,准确率在百分之60多)
import torchvision
from model import *
# 准备数据集
from torch import nn
from torch.utils.data import DataLoader
import torch
from torch import nn
# 定义训练的设备
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
train_data = torchvision.datasets.CIFAR10("./CDataset", train=True,
transform=torchvision.transforms.ToTensor(), download=True)
test_data = torchvision.datasets.CIFAR10("./CDataset", train=False,
transform=torchvision.transforms.ToTensor(), download=True)
train_data_size = len(train_data)
test_data_size = len(test_data)
# 利用Dataloader加载数据集
train_dataloader = DataLoader(train_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)
# 创建网络模型
net = Net()
net = net.to(device)
# 创建损失函数
loss_fn = nn.CrossEntropyLoss()
loss_fn = loss_fn.to(device)
# 优化器
learning_rate = 1e-2
optimizer = torch.optim.SGD(net.parameters(), lr=learning_rate )
# 设置训练网络的参数
# 记录训练的次数
total_train_step = 0
# 记录测试的次数
total_test_step = 0
# 训练轮数
epoch = 30
for i in range(epoch):
print("第{}轮训练开始".format(i + 1))
# 训练步骤开始
net.train() #可删除
for data in train_dataloader:
imgs, targets = data
imgs = imgs.to(device)
targets = targets.to(device)
output = net(imgs)
loss = loss_fn(output, targets)
# 优化器优化模型
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_train_step = total_train_step + 1
if total_train_step % 100 == 0:
print("训练次数:{},Loss:{}".format(total_train_step, loss))
# 测试步骤开始
net.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 = net(imgs)
loss = loss_fn(outputs, targets)
total_test_loss = total_test_loss + loss
accuracy = (outputs.argmax(1) == targets).sum()
total_accuracy = total_accuracy + accuracy
print("整体测试集上的Loss:{}".format(total_test_loss))
print("整体测试集上的正确率{}".format(total_accuracy / test_data_size))
torch.save(net, "./net.pth")
测试代码:
import torch
import torchvision
from PIL import Image
from torch import nn
# 测试图片的相对路径
image_path = "./image/deer.png"
image = Image.open(image_path)
# 如果是png图片需要转换为3通道的RGB图片
image = image.convert('RGB')
transform = torchvision.transforms.Compose([
torchvision.transforms.Resize((32, 32)),
torchvision.transforms.ToTensor()]
)
image = transform(image)
# 采用torch.save()方法保存训练好的模型,这一模型不是pytorch中的,因此需要将模型的代码粘贴在这里
class Net(nn.Module):
def __init__(self):
super(Net, 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 x
# 模型是在Gpu上训练的,因此这里可以将模型加载到cpu上,也可以使用.cuda()将数据放到gpu上
model = torch.load("net.pth", map_location=torch.device('cpu'))
image = torch.reshape(image, (1, 3, 32, 32))
# image = image.cuda()
model.eval()
with torch.no_grad():
output = model(image)
Classification = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
# 获取tensor中只有一个值的具体值
type = output.argmax(1)[0].item()
print(Classification[type])
|