天天看点

pyTorch 使用多GPU训练

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((, , ), (, , ))]) #均值,标准差

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=,
                                          shuffle=True, num_workers=)

testset = torchvision.datasets.CIFAR10(root='./data', train=False,
                                       download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=,
                                         shuffle=False, num_workers=)

classes = ('plane', 'car', 'bird', 'cat',
           'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
#---------------------------------------------------functions to show an image----------------------------

def imshow(img):
    img = img /  +      # unnormalize # 反正则变到0-1
    npimg = img.numpy()
    #print(npimg)
    plt.imshow(np.transpose(npimg, (, , ))) #之前的第三维转为第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()))


#----------------------------------------------------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(, , )
        self.pool = nn.MaxPool2d(, )
        self.conv2 = nn.Conv2d(, , )
        self.fc1 = nn.Linear( *  * , )
        self.fc2 = nn.Linear(, )
        self.fc3 = nn.Linear(, )

    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(-,  *  * )
        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=, momentum=)

#-------------------------------------------------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() > :
  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():  # loop over the dataset multiple times
# 0, 1
    running_loss = 
    for i, data in enumerate(trainloader, ):
        # 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[]
        if i %  == :    # print every 2000 mini-batches
            print('[%d, %5d] loss: %.3f' %
                  (epoch + , i + , running_loss / ))
            running_loss = 


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()))

#output
outputs = net(Variable(images.cuda()))

_, predicted = torch.max(outputs.data, )

print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
                              for j in range()))

#test on the whole test-dataset
correct = 
total = 
for data in testloader:
    images, labels = data
    outputs = net(Variable(images.cuda()))
    _, predicted = torch.max(outputs.data, )
    total += labels.size()
    correct += (predicted == labels.cuda()).sum()


print('Accuracy of the network on the 10000 test images: %d %%' % (
     * correct / total))

#
class_correct = list( for i in range())
class_total = list( for i in range())
for data in testloader:
    images, labels = data
    outputs = net(Variable(images.cuda()))
    _, predicted = torch.max(outputs.data, )
    c = (predicted.cuda() == labels.cuda()).squeeze()
    for i in range():
        label = labels[i]
        class_correct[label] += c[i]
        class_total[label] += 


for i in range():
    print('Accuracy of %5s : %2d %%' % (
        classes[i],  * class_correct[i] / class_total[i]))

           

运行结果:

pyTorch 使用多GPU训练

继续阅读