Pytorch 入门理论

一、PyTorch 第一步

1、tensor

Tensor是PyTorch中重要的数据结构,可认为是一个高维数组。它可以是一个数(标量)、一维数组(向量)、二维数组(矩阵)以及更高维的数组。Tensor和Numpy的ndarrays类似,但Tensor可以使用GPU进行加速。Tensor的使用和Numpy及Matlab的接口十分相似,下面通过几个例子来看看Tensor的基本使用。

import sys
print(sys.executable)
/opt/anaconda3/bin/python
from __future__ import print_function
import torch as t
t.__version__
'1.4.0'
# 构建 5x3 矩阵,只是分配了空间,未初始化
x = t.Tensor(5, 3)

x = t.Tensor([[1,2],[3,4]])
x
tensor([[1., 2.],
        [3., 4.]])
# 使用[0,1]均匀分布随机初始化二维数组
x = t.rand(5, 3)  
x
tensor([[7.7643e-01, 7.1436e-04, 6.7820e-01],
        [8.5539e-01, 4.8096e-01, 1.3477e-01],
        [4.7888e-01, 1.8185e-01, 1.2813e-01],
        [3.8182e-01, 8.8343e-01, 6.9805e-01],
        [9.6493e-01, 2.1723e-01, 2.2802e-01]])
print(x.size()) # 查看x的形状
x.size()[1], x.size(1) # 查看列的个数, 两种写法等价
torch.Size([5, 3])





(3, 3)
y = t.rand(5, 3)
# 加法的第一种写法
x + y
tensor([[1.3587, 0.4693, 1.6303],
        [1.8240, 1.2567, 0.7243],
        [1.0698, 0.9648, 0.8577],
        [0.6523, 1.2708, 1.1431],
        [1.0530, 0.8957, 1.1123]])
# 加法的第二种写法
t.add(x, y)
tensor([[1.3587, 0.4693, 1.6303],
        [1.8240, 1.2567, 0.7243],
        [1.0698, 0.9648, 0.8577],
        [0.6523, 1.2708, 1.1431],
        [1.0530, 0.8957, 1.1123]])
print('最初y')
print(y)

print('第一种加法,y的结果')
y.add(x) # 普通加法,不改变y的内容
print(y)

print('第二种加法,y的结果')
y.add_(x) # inplace 加法,y变了
print(y)
最初y
tensor([[0.5823, 0.4686, 0.9521],
        [0.9686, 0.7758, 0.5895],
        [0.5909, 0.7830, 0.7295],
        [0.2705, 0.3874, 0.4451],
        [0.0880, 0.6785, 0.8843]])
第一种加法,y的结果
tensor([[0.5823, 0.4686, 0.9521],
        [0.9686, 0.7758, 0.5895],
        [0.5909, 0.7830, 0.7295],
        [0.2705, 0.3874, 0.4451],
        [0.0880, 0.6785, 0.8843]])
第二种加法,y的结果
tensor([[1.3587, 0.4693, 1.6303],
        [1.8240, 1.2567, 0.7243],
        [1.0698, 0.9648, 0.8577],
        [0.6523, 1.2708, 1.1431],
        [1.0530, 0.8957, 1.1123]])

注意,函数名后面带下划线_ 的函数会修改Tensor本身。例如,x.add_(y)和x.t_()会改变 x,但x.add(y)和x.t()返回一个新的Tensor, 而x不变。

# Tensor的选取操作与Numpy类似
x[:, 1]
tensor([7.1436e-04, 4.8096e-01, 1.8185e-01, 8.8343e-01, 2.1723e-01])

Tensor还支持很多操作,包括数学运算、线性代数、选择、切片等等,其接口设计与Numpy极为相似。 Tensor和Numpy的数组之间的互操作非常容易且快速。对于Tensor不支持的操作,可以先转为Numpy数组处理,之后再转回Tensor。

a = t.ones(5) # 新建一个全1的Tensor
a
tensor([1., 1., 1., 1., 1.])
b = a.numpy() # Tensor -> Numpy
b
array([1., 1., 1., 1., 1.], dtype=float32)
import numpy as np
a = np.ones(5)
b = t.from_numpy(a) # Numpy->Tensor
print(a)
print(b)
[1. 1. 1. 1. 1.]
tensor([1., 1., 1., 1., 1.], dtype=torch.float64)

Tensor和numpy对象共享内存,所以他们之间的转换很快,而且几乎不会消耗什么资源。但这也意味着,如果其中一个变了,另外一个也会随之改变。

b.add_(1) # 以`_`结尾的函数会修改自身
print(a)
print(b) # Tensor和Numpy共享内存
[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)

如果你想获取某一个元素的值,可以使用scalar.item。 直接tensor[idx]得到的还是一个tensor: 一个0-dim 的tensor,一般称为scalar.

scalar = b[0]
scalar
tensor(2., dtype=torch.float64)
scalar.size() #0-dim
torch.Size([])
scalar.item() # 使用scalar.item()能从中取出python对象的数值
2.0
tensor = t.tensor([2]) # 注意和scalar的区别
tensor,scalar
(tensor([2]), tensor(2., dtype=torch.float64))
tensor.size(),scalar.size()
(torch.Size([1]), torch.Size([]))
# 只有一个元素的tensor也可以调用`tensor.item()`
tensor.item(), scalar.item()
(2, 2.0)

此外在pytorch中还有一个和np.array 很类似的接口: torch.tensor, 二者的使用十分类似。

tensor = t.tensor([3,4]) # 新建一个包含 3,4 两个元素的tensor
scalar = t.tensor(3)
scalar
tensor(3)
old_tensor = tensor
new_tensor = old_tensor.clone()
new_tensor[0] = 1111
old_tensor, new_tensor
(tensor([3, 4]), tensor([1111,    4]))

需要注意的是,t.tensor()或者tensor.clone()总是会进行数据拷贝,新tensor和原来的数据不再共享内存。所以如果你想共享内存的话,建议使用torch.from_numpy()或者tensor.detach()来新建一个tensor, 二者共享内存。

new_tensor = old_tensor.detach()
new_tensor[0] = 1111
old_tensor, new_tensor
(tensor([1111,    4]), tensor([1111,    4]))
# 在不支持CUDA的机器下,下一步还是在CPU上运行
device = t.device("cuda:0" if t.cuda.is_available() else "cpu")
x = x.to(device)
y = y.to(x.device)
z = x+y

2、autograd: 自动微分

深度学习的算法本质上是通过反向传播求导数,而PyTorch的autograd模块则实现了此功能。在Tensor上的所有操作,autograd都能为它们自动提供微分,避免了手动计算导数的复杂过程。

# 为tensor设置 requires_grad 标识,代表着需要求导数
# pytorch 会自动调用autograd 记录操作
x = t.ones(2, 2, requires_grad=True)

# 上一步等价于
# x = t.ones(2,2)
# x.requires_grad = True

x
tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
y = x.sum()
y
tensor(4., grad_fn=<SumBackward0>)
y.grad_fn
<SumBackward0 at 0x12a0813d0>
y.backward() # 反向传播,计算梯度
# y = x.sum() = (x[0][0] + x[0][1] + x[1][0] + x[1][1])
# 每个值的梯度都为1
x.grad
tensor([[1., 1.],
        [1., 1.]])
y.backward()
x.grad
tensor([[2., 2.],
        [2., 2.]])
y.backward()
x.grad
tensor([[3., 3.],
        [3., 3.]])
# 以下划线结束的函数是inplace操作,会修改自身的值,就像add_
x.grad.data.zero_()
tensor([[0., 0.],
        [0., 0.]])
y.backward()
x.grad
tensor([[1., 1.],
        [1., 1.]])

3、神经网络

一个典型的神经网络训练过程包括以下几点:

  1. 定义一个包含可训练参数的神经网络
  2. 迭代整个输入
  3. 通过神经网络处理输入
  4. 计算损失(loss)
  5. 反向传播梯度到神经网络的参数
  6. 更新网络的参数,典型的用一个简单的更新方法:weight = weight - learning_rate *gradient

定义网络

定义网络时,需要继承nn.Module,并实现它的forward方法,把网络中具有可学习参数的层放在构造函数__init__中。如果某一层(如ReLU)不具有可学习的参数,则既可以放在构造函数中,也可以不放,但建议不放在其中,而在forward中使用nn.functional代替。

import torch
import torch.nn as nn # 各种层类型的实现
import torch.nn.functional as F # 各中级函数的实现,与层类型对应,如卷积函数、池化函数、归一化函数等

# 自定义 Net 类并实例化
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        # 初始化层类型
        # 1 input image channel, 6 output channels, 5x5 square convolution kernel
        self.conv1 = nn.Conv2d(1, 6, 5) # 1个输入图像、6个输出图像、5*5的卷积核
        self.conv2 = nn.Conv2d(6, 16, 5)
        # an affine operation: y = Wx + b
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x): # 定义前向传播
        # Max pooling over a (2, 2) window
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        # If the size is a square you can only specify a single number
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        x = x.view(-1, self.num_flat_features(x))
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

    def num_flat_features(self, x):
        size = x.size()[1:]  # all dimensions except the batch dimension
        num_features = 1
        for s in size:
            num_features *= s
        return num_features


net = Net()
print(net)
Net(
  (conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))
  (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
  (fc1): Linear(in_features=400, out_features=120, bias=True)
  (fc2): Linear(in_features=120, out_features=84, bias=True)
  (fc3): Linear(in_features=84, out_features=10, bias=True)
)

只要在定义了forward函数,backward函数就会自动被实现(利用autograd)。

网络的可学习参数通过net.parameters()返回,net.named_parameters可同时返回可学习的参数及名称。

params = list(net.parameters())
print(len(params))
print(params[0].size())  # conv1's .weight
10
torch.Size([6, 1, 5, 5])

让我们尝试一个32x32随机输入。注意:此网络的预期输入大小(LeNet)为32x32。要在MNIST数据集上使用此网络,请将图像从数据集中调整为32x32。

import torch
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
tensor([[-8.5570e-02,  2.8983e-05, -1.8597e-02,  1.6849e-01,  1.2567e-01,
          1.5280e-01,  2.1988e-01,  5.1768e-02, -2.4432e-02,  1.6020e-02]],
       grad_fn=<AddmmBackward>)

用随机梯度将所有参数和反向传播器的梯度缓冲区归零:

net.zero_grad()
out.backward(torch.randn(1, 10))
for name,parameters in net.named_parameters():
    print(name,':',parameters.size())
conv1.weight : torch.Size([6, 1, 5, 5])
conv1.bias : torch.Size([6])
conv2.weight : torch.Size([16, 6, 5, 5])
conv2.bias : torch.Size([16])
fc1.weight : torch.Size([120, 400])
fc1.bias : torch.Size([120])
fc2.weight : torch.Size([84, 120])
fc2.bias : torch.Size([84])
fc3.weight : torch.Size([10, 84])
fc3.bias : torch.Size([10])
input = torch.randn(1, 1, 32, 32)
out = net(input)
out.size()
torch.Size([1, 10])
net.zero_grad() # 所有参数的梯度清零
out.backward(torch.ones(1,10)) # 反向传播
output = net(input)
target = torch.randn(10)  # a dummy target, for example
target = target.view(1, -1)  # make it the same shape as output
criterion = nn.MSELoss()

loss = criterion(output, target)
print(loss)
tensor(0.7851, grad_fn=<MseLossBackward>)
print(loss.grad_fn)  # MSELoss
print(loss.grad_fn.next_functions[0][0])  # Linear
print(loss.grad_fn.next_functions[0][0].next_functions[0][0])
<MseLossBackward object at 0x1040dab10>
<AddmmBackward object at 0x1040da090>
<AccumulateGrad object at 0x1040dab10>
net.zero_grad()     # zeroes the gradient buffers of all parameters

print('conv1.bias.grad before backward')
print(net.conv1.bias.grad)

loss.backward()

print('conv1.bias.grad after backward')
print(net.conv1.bias.grad)
conv1.bias.grad before backward
tensor([0., 0., 0., 0., 0., 0.])
conv1.bias.grad after backward
tensor([-0.0033, -0.0239, -0.0223, -0.0204, -0.0001, -0.0284])