pytorch官网的教程 https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html
import torch
import torchvision
import torchvision.transforms as transforms
transform = transforms.Compose(
[transforms.ToTensor(), #转为tensor
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))#归一化
])
#训练集
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
# 训练数据加载器
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,
shuffle=True, num_workers=2)
#测试集
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform)
# 测试数据加载器
testloader = torch.utils.data.DataLoader(testset, batch_size=4,
shuffle=False, num_workers=2)
# cifar10 分类索引
classes = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
CIFAR-10中的图像尺寸为3×32×32,即尺寸为32×32像素的3通道彩色图像
dataiter = iter(trainloader)
images, labels = dataiter.next()
images.shape
torch.Size([64, 3, 32, 32]) B,C,H,W
import matplotlib.pyplot as plt
import numpy as np
# functions to show an image
def imshow(img):
#输入数据:类型(torch.tensor[c,h,w]:[通道,高度,宽度])
img = img / 2 + 0.5 #反归一处理
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0))) #图像进行转置,变为[h,w,c]
plt.show()
# get some random training images
dataiter = iter(trainloader)#加载一个mini batch
images, labels = dataiter.next()
# show images
imshow(torchvision.utils.make_grid(images))
# print labels
print(' '.join('%5s' % classes[labels[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(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5) #输入深度:3 输出深度(卷积核个数):6 3x3卷积核
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(trainloader, 0):
# 输入数据
inputs, labels = data
# 梯度清零
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
#更新参数
optimizer.step()
# print statistics
running_loss += loss.item()
if i % 2000 == 1999: # print every 2000 mini-batches
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 2000))
running_loss = 0.0
print('Finished Training')
[1, 2000] loss: 2.208
[1, 4000] loss: 1.887
[1, 6000] loss: 1.702
[1, 8000] loss: 1.607
[1, 10000] loss: 1.530
[1, 12000] loss: 1.473
[2, 2000] loss: 1.410
[2, 4000] loss: 1.371
[2, 6000] loss: 1.324
[2, 8000] loss: 1.311
[2, 10000] loss: 1.316
[2, 12000] loss: 1.289
Finished Training
PATH = './cifar_net.pth'
torch.save(net.state_dict(), PATH)
# 查看数据,取一组batch
dataiter = iter(testloader)
images, labels = dataiter.next()
# print images
imshow(torchvision.utils.make_grid(images))
print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))
#加载模型
net = Net()
net.load_state_dict(torch.load(PATH))
outputs = net(images)
_, 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 testloader: # 循环每一个batch
images, labels = data
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():# 以batch为单位
for data in testloader:
images, labels = data
outputs = net(images)
_, predicted = torch.max(outputs, 1)
c = (predicted == labels).squeeze()
for i in range(4):# 每个batch都有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]))