本文主要是Pytorch官网的tutorial的一些理解,如有错误之处,请批评指正
CPU计算:
(参考耗时:
CPU代码:1m32s
GPU代码:1m38s)
# 1 加载和标准化CIFAR10
# 使用torchvision加载CIFAR10数据集
import torch
import torchvision
import torchvision.transforms as transforms
transform = transforms.Compose(
[transforms.ToTensor(),
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)
classes = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
#结果应该是:
#Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ./data/cifar-10-python.tar.gz
#Extracting ./data/cifar-10-python.tar.gz to ./data
#Files already downloaded and verified
#如果下载实在太慢,可以用
#https://blog.csdn.net/weixin_43085694/article/details/104139311
#里面的解决方案
# 下面这个环节不是必须的,只是体验一下CIFAR10
#以及了解图片如何output
import matplotlib.pyplot as plt
import numpy as np
# functions to show an image
def imshow(img):
img = img / 2 + 0.5 # unnormalize
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
# get some random training images
dataiter = iter(trainloader)
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)))
# 结果会出现一张随机图片
#然后是四个名称, 如:deer horse deer bird
# 2 定义CNN
#这个类也可以放在另一个文件中
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)
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()
# 3 定义损失函数和optimizer(不知道怎么翻译毕竟好)
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# 4 训练模型(最耗时)
for epoch in range(2): # loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# get the inputs; data is a list of [inputs, labels]
inputs, labels = data
# zero the parameter gradients
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.195
#[1, 4000] loss: 1.868
#[1, 6000] loss: 1.666
#[1, 8000] loss: 1.569
#[1, 10000] loss: 1.499
#[1, 12000] loss: 1.471
#[2, 2000] loss: 1.397
#[2, 4000] loss: 1.377
#[2, 6000] loss: 1.363
#[2, 8000] loss: 1.331
#[2, 10000] loss: 1.304
#[2, 12000] loss: 1.300
#Finished Training
# 保存训练好的模型
PATH = './cifar_net.pth'
torch.save(net.state_dict(), PATH)
# 5 在测试集上测试
# 展示数据集答案
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:
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():
for data in testloader:
images, labels = data
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]))
GPU计算:(参考耗时:2m18s)
# 1 加载和标准化CIFAR10
# 使用torchvision加载CIFAR10数据集
import torch
import torchvision
import torchvision.transforms as transforms
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
trainset = torchvision.datasets.CIFAR10(root='./data/CIFAR10',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/CIFAR10', train=False,download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=4,
shuffle=False, num_workers=2)
classes = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
#结果应该是:
#Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ./data/cifar-10-python.tar.gz
#Extracting ./data/cifar-10-python.tar.gz to ./data
#Files already downloaded and verified
#如果下载实在太慢,可以用
#https://blog.csdn.net/weixin_43085694/article/details/104139311
#里面的解决方案
# 下面这个环节不是必须的,只是体验一下CIFAR10
#以及了解图片如何output
import matplotlib.pyplot as plt
import numpy as np
# functions to show an image
def imshow(img):
img = img / 2 + 0.5 # unnormalize
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
# get some random training images
dataiter = iter(trainloader)
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)))
# 结果会出现一张随机图片
#然后是四个名称, 如:deer horse deer bird
# 2 定义CNN
#这个类也可以放在另一个文件中
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)
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()
# training on GPU
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Assuming that we are on a CUDA machine, this should print a CUDA device:
print(device)
net.to(device)
# 3 定义损失函数和optimizer(不知道怎么翻译毕竟好)
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# 4 训练模型(最耗时)
for epoch in range(2): # loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# get the inputs; data is a list of [inputs, labels]
#inputs, labels = data
# GPU version
inputs, labels = data[0].to(device), data[1].to(device)
# zero the parameter gradients
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.195
#[1, 4000] loss: 1.868
#[1, 6000] loss: 1.666
#[1, 8000] loss: 1.569
#[1, 10000] loss: 1.499
#[1, 12000] loss: 1.471
#[2, 2000] loss: 1.397
#[2, 4000] loss: 1.377
#[2, 6000] loss: 1.363
#[2, 8000] loss: 1.331
#[2, 10000] loss: 1.304
#[2, 12000] loss: 1.300
#Finished Training
# 保存训练好的模型
PATH = './model/cifar_net.pth'
torch.save(net.state_dict(), PATH)
# 5 在测试集上测试
# 展示数据集答案
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:
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():
for data in testloader:
images, labels = data
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]))
2020.2.6 更新:
google colab测试:
CPU版:大约3min
GPU版:1min30s
注意事项:
- 数据集下载过慢,Pytorch下载CIFAR10数据集过慢问题的解决
- 训练数据集比较费时间,如果要重复使用训练好的模型,则将保存好的模型放在指定位置,并且将torch.save(net.state_dict(), PATH)去掉,以防overwirte
- 在terminal的anaconda环境中出现的报错:
OMP: Error #15: Initializing libiomp5.dylib, but found libomp.dylib already initialized.
解决方法:在开头加上
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
- CPU vs GPU
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Assuming that we are on a CUDA machine, this should print a CUDA device:
print(device)
如果连接上GPU服务器,那么输出cuda:0
如果没有连上,输出cpu