PyTorch入门

2017-11-30  本文已影响0人  wendy_要努力努力再努力

一、什么是PyTorch?

import torch
x = torch.Tensor(5, 3)  #uninitialized
x = torch.rand(5, 3)    #randomly initialized 
y = torch.rand(5, 3)
# 第一种加法
result = torch.Tensor(5, 3)
torch.add(x, y, out=result)
print(result)
# 第二种加法
y.add_(x)                     # 原地改变张量的操作需加“_”后缀
print(y)

torch Tensor和 numpy array之间的互相转换

# 如果是赋值,一个的值发生变化,另一个的值也会发生变化
import torch
a = torch.ones(5)
b = a.numpy()

import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)

image.png

二、Autograd自动求导机制

每个 Variable有两个标签:requires_grad and volatile(不稳定性);允许在梯度计算中排除子图的微调
在一个操作中如果有一个输入需要梯度,那他的输出也需要梯度。所有变量不需要梯度时,在子图中就不会进行逆向运算。一部分参数冻结,最后一层全连接的参数在用来微调。

model = torchvision.models.resnet18(pretrained=True)  #创建模型
for param in model.parameters():
    param.requires_grad = False
# Replace the last fully-connected layer
# Parameters of newly constructed modules have requires_grad=True by default
model.fc = nn.Linear(512, 100)       #全连接层  默认需要梯度

# Optimize only the classifier
optimizer = optim.SGD(model.fc.parameters(), lr=1e-2, momentum=0.9)

volatile决定了require_grad is False(不需要梯度)
要有backward()操作,才能读取变量的梯度


三、神经网络

重要的类

更新权重

import torch.optim as optim

# create your optimizer
optimizer = optim.SGD(net.parameters(), lr=0.01)  # 更新方式Nesterov-SGD, Adam, RMSProp

# in your training loop:
optimizer.zero_grad()   # zero the gradient buffers
output = net(input)  #net()是定义神经网络的类 class Net()
criterion = nn.MSELoss()    # loss function
loss = criterion(output, target) 
loss.backward()    # backprop
optimizer.step()    # Does the update   e.g 【weight = weight - learning_rate * gradient】

四、训练分类器

预处理数据

load数据时,要从numpy array类型转换成tensor类型的数据;我们可以直接用torchvision的库来导入常用的数据集

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))])  # PILImage[0,1]将它转换为归一化的【-1,1】的Tensor

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

定义网络

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

在GPU上训练

for epoch in range(2):  # loop over the dataset multiple times  多少epoch由自己决定

    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()) #####代表将数据也搬到GPU上

        # zero the parameter gradients
        optimizer.zero_grad()

        # forward + backward + optimize
        net.cuda()  ####代表将模型搬到GPU上运行
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        # print statistics
        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')

五、数据并行

model.gpu()
mytensor = my_tensor.gpu() #tensor需要指定新的tensor在GPU上运行
model = nn.DataParallel(model)

随机化初始数据,定义模型,创建模型并并行化,运行整个模型。

上一篇下一篇

猜你喜欢

热点阅读