码迷,mamicode.com
首页 > 其他好文 > 详细

[深度学习] Pytorch学习(二)—— torch.nn 实践:训练分类器(含多GPU训练CPU加载预测的使用方法)

时间:2019-10-20 10:45:43      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:down   可能性   函数   utils   htm   doc   conv2   als   ==   

Learn From:

Pytroch 官方Tutorials
Pytorch 官方文档

环境:python3.6 CUDA10 pytorch1.3 vscode+jupyter扩展

#%%
#%%
# 1.Loading and normalizing CIFAR10

import torch 
import torchvision
import torchvision.transforms as transforms

batch_size = 16

transform = transforms.Compose( [transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))] )
# 对图像的预处理,用在加载数据时,当作函数传给transform参数

trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
                                download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
                                shuffle=True, num_workers=0)
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
                                download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,
                                shuffle=False, num_workers=0)
classes = ('plane', 'car', 'bird', 'cat',
           'deer', 'dog', 'frog', 'horse', 'ship', 'truck')


#%%
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()
    print( npimg.shape )
    plt.imshow(np.transpose(npimg, (1, 2, 0)))
    print( np.transpose( npimg, (1, 2, 0) ).shape )
    plt.show()
# get some random training images
dataiter = iter(trainloader)
# images torch.Size([16, 3, 32, 32]). labels torch.Size([16])
images, labels = dataiter.next()
# show images
imshow(torchvision.utils.make_grid(images))
# print labels
print(' '.join('%5s' % classes[labels[j]] for j in range(batch_size)))

#%%
# 2.Define a Convolutional Neural Network

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, 16, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(16, 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()
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
net = nn.DataParallel(net)  # 多GPU
net.to(device)  #GPU

#%%
# 3.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)

#%%
# 4.Train the network

for epoch in range(2):
    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        inputs, labels = data   # torch.Size([16, 3, 32, 32])
        # GPU
        inputs, labels = inputs.to(device), labels.to(device)
        # zero the parameter gradients
        optimizer.zero_grad()
        # forward + backward + optimize
        outputs = net(inputs)   
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        if i % 500 == 499:
            print('[%d ,%5d] loss: %.3f' %
                    (epoch+1, i+1, running_loss/2000))
            running_loss = 0.0
print("Finished Training")
# save trained model:
PATH = 'cifar_net.pth'
torch.save(net.module.state_dict(), PATH)
# 这样保存到模型就可以在CPU下运行

#%%
# 5.Test the network on the test data
# 为了练习多GPU训练模型,单CPU环境测试、运行模型,以下测试都是CPU的使用方法
dataiter = iter(testloader)
images, labels = dataiter.next()
imshow(torchvision.utils.make_grid(images))
print('GroundTruth: ', 
        ''.join('%5s' % classes[labels[j]] for j in range(batch_size)))

net = Net()
net.load_state_dict(torch.load(PATH))    # 加载 CPU模型
# 输出的是能量能量越大的 是这个类的可能性越大
outputs = net(images)
# 按行取最大值
_, predicted = torch.max(outputs, 1)    
print('Predicted: ', 
        ''.join('%5s' % classes[predicted[j]] for j in range(batch_size)))


# Let us look at how the network performs on the whole dataset
correct = 0
total = 0
with torch.no_grad():
    for data in testloader:
        images, labels = data
        # GPU
        # images, labels = images.to(device), labels.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))

# what are the classes that performed well, 
# and the classes that did not perform well
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
        # images, labels = images.to(device), labels.to(device)
        outputs = net(images)
        _, predicted = torch.max(outputs, 1)
        c = (predicted == labels).squeeze()
        for i in range(batch_size):
            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]))

结果:

技术图片
技术图片
技术图片

[深度学习] Pytorch学习(二)—— torch.nn 实践:训练分类器(含多GPU训练CPU加载预测的使用方法)

标签:down   可能性   函数   utils   htm   doc   conv2   als   ==   

原文地址:https://www.cnblogs.com/importGPX/p/11706720.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!