1.在pyTorch中模型使用GPU训练很方便,直接使用model.gpu()
。
2.使用多GPU训练,model = nn.DataParallel(model)
3.注意训练/测试过程中 inputs和labels均需加载到GPU中
inputs, labels = Variable(inputs.cuda()), Variable(labels.cuda())
具体使用参考 pytorch tutorials
实例:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''''''''''''''''''''''''''''''''
# @Time : 2018/4/15 16:51
# @Author : Awiny
# @Site :
# @File : cifar10.py
# @Software: PyCharm
# @Github : https://github.com/FingerRec
# @Blog : http://fingerrec.github.io
'''''''''''''''''''''''''''''''''
import scipy.io
import os
import torch
import torchvision
import torchvision.transforms as transforms
import numpy as np
import matplotlib.pyplot as plt
#os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' #close the warning
#---------------------------------------------------download and load dataset---------------------------------
#正则化
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)
#The output of torchvision datasets are PILImage images of range [0, 1].
#We transform them to Tensors of normalized range [-1, 1].
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')
#---------------------------------------------------functions to show an image----------------------------
def imshow(img):
img = img / 2 + 0.5 # unnormalize # 反正则变到0-1
npimg = img.numpy()
#print(npimg)
plt.imshow(np.transpose(npimg, (1, 2, 0))) #之前的第三维转为第2,第2为第1,第1维为第3
#高维数组切片?
# get some random training images
dataiter = iter(trainloader)
images, labels = dataiter.next()
# show images
imshow(torchvision.utils.make_grid(images))
plt.axis('off') # 不显示坐标轴
plt.show()
# print labels
print(' '.join('%5s' % classes[labels[j]] for j in range(4)))
#----------------------------------------------------define an convolutional neural network---------------------
from torch.autograd import Variable
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):
y = 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)
print(" In Model: input size", y.size(),
"output size", x.size())
return x
net = Net()
#net.cuda()
#--------------------------------------------------Define a Loss function and optimizer------------------------------
import torch.optim as optim
criterion = nn.CrossEntropyLoss() #交叉熵
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
#-------------------------------------------------Training on GPU-------------------------------------
#you transfer the neural net onto the GPU. This will recursively go over all modules and convert their parameters and buffers to CUDA tensors:
#net.cuda()
#have to send the inputs and targets at every step to the GPU too:
#inputs, labels = Variable(inputs.cuda()), Variable(labels.cuda())
#----------------------------------------------------Training on Multiple GPU-------------------
if torch.cuda.device_count() > 1:
print("Let's use", torch.cuda.device_count(), "GPUs!")
# dim = 0 [30, xxx] -> [10, ...], [10, ...], [10, ...] on 3 GPUs
net = nn.DataParallel(net)
if torch.cuda.is_available():
net.cuda()
#pytorch中CrossEntropyLoss是通过两个步骤计算出来的,第一步是计算log softmax,第二步是计算cross entropy(或者说是negative log likehood)
#---------------------------------------------------Training the network------------------------------------------------
for epoch in range(2): # loop over the dataset multiple times
# 0, 1
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# get the inputs
inputs, labels = data
# wrap them in Variable
inputs, labels = Variable(inputs.cuda()), Variable(labels.cuda())
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs) # forward
loss = criterion(outputs, labels)
loss.backward() # backward
optimizer.step()
# print statistics
print("Outside: input size", images.size(), "output_size", outputs.size())
running_loss += loss.data[0]
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')
#----------------------------------------------------Test the model------------------------------------------------
dataiter = iter(testloader)
images, labels = dataiter.next()
labels.cuda()
# print images
imshow(torchvision.utils.make_grid(images))
print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))
#output
outputs = net(Variable(images.cuda()))
_, predicted = torch.max(outputs.data, 1)
print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
for j in range(4)))
#test on the whole test-dataset
correct = 0
total = 0
for data in testloader:
images, labels = data
outputs = net(Variable(images.cuda()))
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels.cuda()).sum()
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))
for data in testloader:
images, labels = data
outputs = net(Variable(images.cuda()))
_, predicted = torch.max(outputs.data, 1)
c = (predicted.cuda() == labels.cuda()).squeeze()
for i in range(4):
label = labels[i]
class_correct[label] += c[i]
class_total[label] += 1
for i in range(10):
print('Accuracy of %5s : %2d %%' % (
classes[i], 100 * class_correct[i] / class_total[i]))
运行结果: