CIFAR10数据集介绍: 数据集中每张图片的尺寸是3 * 32 * 32, 代表彩色3通道
CIFAR10数据集总共有10种不同的分类, 分别是"airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck".
import torch
import torchvision
import torchvision.transforms as transforms
# 对下载的数据集图片进行调整,torchvision数据集的输出是PILImage格式,把数据域格式[0,1]改为标准数据域[-1,1]的张量格式
transform = transforms.Compose(
[transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]
)
train_set = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
train_loader = torch.utils.data.DataLoader(train_set, batch_size=4, shuffle=True, num_workers=2)
test_set = torchvision.datasets.CIFAR10(root='./data', train=False, download=False, transform=transform)
test_loader = torch.utils.data.DataLoader(test_set, batch_size=4, shuffle=False, num_workers=2)
classes = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
# 展示若干训练集的图片
# 导入画图包和numpy
import matplotlib.pyplot as plt
import numpy as np
# 构建展示图片的函数
def img_show(img):
img = img / 2 + 0.5
np_img = img.numpy()
plt.imshow(np.transpose(np_img, (1, 2, 0)))
plt.show()
# 从数据迭代器中读取一张图片
dataiter = iter(train_loader)
images, labers = dataiter.next()
# 展示图片
img_show(torchvision.utils.make_grid(images))
# 打印标签label
print(" ".join("%5s" % classes[labers[j]] for j in range(4)))
# 定义卷积神经网络
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
# 定义损失函数
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
for epoch in range(2): # # loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(train_loader, 0):
# data中包含输入图像张量inputs, 标签张量labels
inputs, labers = data
# 首先将优化器梯度归零
optimizer.zero_grad()
# 输入图像张量进网络,得到输出张量outputs
outputs = net(inputs)
# 利用网络的输出outputs和标签labels计算损失
loss = criterion(outputs, labers)
# 反向传播+参数更新,是标准代码的标准流程
loss.backward()
optimizer.step()
# 打印轮次和损失值
running_loss += loss.item()
if (i+1) % 2000 == 0:
print('[%d, %5d] loss: %.3f' % (epoch + 1, i+1, running_loss / 2000))
running_loss = 0.0
print("Finished Training!")
输出结果:
# 设定模型的保存路径
PATH = './path/cifar_net.pth'
# 保存模型的状态字典
torch.save(net.state_dict(), PATH)
# 测试模型
# 在测试集中取出一个批次的数据,做图像和标签的展示
dataiter = iter(test_loader)
images, labers = dataiter.next()
# 打印原始图片
img_show(torchvision.utils.make_grid(images))
# 打印真实的标签
print('GroundTrueh:', " ".join('%5s' % classes[labers[j]] for j in range(4)))
# 加载模型并对测试图片进行预测
# 实例化模型的类对象
net = Net()
# 加载训练阶段保存好的模型的状态字典
net.load_state_dict(torch.load(PATH))
# 利用模型对图片进行预测
outputs = net(images)
# 共有10个类别, 采用模型计算出的概率最大的作为预测的类别
_, predicted = torch.max(outputs, 1)
# 打印预测标签的结果
print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] for j in range(4)))
# 接下来看一下在全部测试集上的表现
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labers = data
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labers.size(0)
correct += (predicted == labers).sum().item()
print("Accuracy of the network on the 10000 test images: %d %%" % (100 * correct / total))
# 在不同类别上分别进行准确率计算
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
with torch.no_grad():
for data in test_loader:
images, labers = data
outputs = net(images)
_, predicted = torch.max(outputs, 1)
c = (predicted == labers).squeeze()
for i in range(4):
label = labers[i]
class_correct[label] += c[i].item()
class_total[label] += 1
for i in range(10):
print("Accuracy of %5s: %2d %%" % (classes[i], 100 * class_correct[i] / class_total[i]))
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
# 将模型转移到GPU上
net.to(device)
# 将输入的图片张量和标签张量转移到GPU上
inputs, labels = data[0].to(device), data[1].to(device)
全部代码:
# 导入库
import torch
import torchvision
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
# 对下载的数据集图片进行调整,torchvision数据集的输出是PILImage格式,把数据域格式[0,1]改为标准数据域[-1,1]的张量格式
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
train_set = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
train_loader = torch.utils.data.DataLoader(train_set, batch_size=4, shuffle=True, num_workers=0)
test_set = torchvision.datasets.CIFAR10(root='./data', train=False, download=False, transform=transform)
test_loader = torch.utils.data.DataLoader(test_set, batch_size=4, shuffle=False, num_workers=0)
# 分类标签
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
# 构建展示图片的函数
def img_show(img):
img = img / 2 + 0.5
np_img = img.numpy()
plt.imshow(np.transpose(np_img, (1, 2, 0)))
plt.show()
# 从数据迭代器中读取一张图片
dataiter = iter(train_loader)
images, labels = dataiter.next()
# 展示图片
img_show(torchvision.utils.make_grid(images))
# 打印标签label
print(" ".join("%5s" % classes[labels[j]] for j in range(4)))
# 定义卷积神经网络
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
# 实例化模型的类对象
net = Net()
# 在GPU上训练模型
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
# 将模型转移到GPU上
net.to(device)
# 定义损失函数
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# 模型训练
for epoch in range(2): # # loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(train_loader, 0):
# # data中包含输入图像张量inputs, 标签张量labels
# inputs, labels = data
# 将输入的图片张量和标签张量转移到GPU上
inputs, labels = data[0].to(device), data[1].to(device)
# 首先将优化器梯度归零
optimizer.zero_grad()
# 输入图像张量进网络,得到输出张量outputs
outputs = net(inputs)
# 利用网络的输出outputs和标签labels计算损失
loss = criterion(outputs, labels)
# 反向传播+参数更新,是标准代码的标准流程
loss.backward()
optimizer.step()
# 打印轮次和损失值
running_loss += loss.item()
if (i + 1) % 2000 == 0:
print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000))
running_loss = 0.0
print("Finished Training!")
# 设定模型的保存路径
PATH = './path/cifar_net2.pth'
# 保存模型的状态字典
# torch.save(net.state_dict(), PATH)
# 测试模型
# 在测试集中取出一个批次的数据,做图像和标签的展示
dataiter = iter(test_loader)
images, labels = dataiter.next()
# 打印原始图片
img_show(torchvision.utils.make_grid(images))
# 打印真实的标签
print('GroundTrueh:', " ".join('%5s' % classes[labels[j]] for j in range(4)))
# 加载模型并对测试图片进行预测
# 实例化模型的类对象
# net = Net()
# 加载训练阶段保存好的模型的状态字典
net.load_state_dict(torch.load(PATH))
# 利用模型对图片进行预测
outputs = net(images)
# 共有10个类别, 采用模型计算出的概率最大的作为预测的类别
_, predicted = torch.max(outputs, 1)
# 打印预测标签的结果
print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] for j in range(4)))
# 接下来看一下在全部测试集上的表现
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
# images, labels = data
# 将输入的图片张量和标签张量转移到GPU上
images, labels = data[0].to(device), data[1].to(device)
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print("Accuracy of the network on the 10000 test images: %d %%" % (100 * correct / total))
# 在不同类别上分别进行准确率计算
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
with torch.no_grad():
for data in test_loader:
# images, labels = data
# 将输入的图片张量和标签张量转移到GPU上
images, labels = data[0].to(device), data[1].to(device)
outputs = net(images)
_, predicted = torch.max(outputs, 1)
c = (predicted == labels).squeeze()
for i in range(4):
label = labels[i]
class_correct[label] += c[i].item()
class_total[label] += 1
for i in range(10):
print("Accuracy of %5s: %2d %%" % (classes[i], 100 * class_correct[i] / class_total[i]))