【动手学深度学习】笔记(基础篇)

【动手学深度学习】笔记(基础篇)

oyxy2019 354 2023-03-18

基础篇

【16 PyTorch 神经网络基础】 https://www.bilibili.com/video/BV1AK4y1P7vs

5.1 层和块

块(block)可以描述单个层、由多个层组成的组件或整个模型本身。使用块的好处是我们可以随意组装、搭配、嵌套我们的模型。

经典nn.Sequential
import torch
from torch import nn
from torch.nn import functional as F

net = nn.Sequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))

X = torch.rand(2, 20)
net(X)
自定义块
class MLP(nn.Module):
    # 用模型参数声明层。这里,我们声明两个全连接的层
    def __init__(self):
        # 调用MLP的父类Module的构造函数来执行必要的初始化。
        # 这样,在类实例化时也可以指定其他函数参数,例如模型参数params(稍后将介绍)
        super().__init__()
        self.hidden = nn.Linear(20, 256)  # 隐藏层
        self.out = nn.Linear(256, 10)  # 输出层

    # 定义模型的前向传播,即如何根据输入X返回所需的模型输出
    def forward(self, X):
        # 注意,这里我们使用ReLU的函数版本,其在nn.functional模块中定义。
        return self.out(F.relu(self.hidden(X)))
    
net = MLP()
net(X)
自定义块2-在前向传播函数中执行代码
class FixedHiddenMLP(nn.Module):
    def __init__(self):
        super().__init__()
        # 不计算梯度的随机权重参数。因此其在训练期间保持不变
        self.rand_weight = torch.rand((20, 20), requires_grad=False)
        self.linear = nn.Linear(20, 20)

    def forward(self, X):
        X = self.linear(X)
        # 使用创建的常量参数以及relu和mm函数
        X = F.relu(torch.mm(X, self.rand_weight) + 1)
        # 复用全连接层。这相当于两个全连接层共享参数
        X = self.linear(X)
        # 控制流
        while X.abs().sum() > 1:
            X /= 2
        return X.sum()
    
net = FixedHiddenMLP()
net(X)
自定义块3-混合搭配各种组合块的方法
class NestMLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.net = nn.Sequential(nn.Linear(20, 64), nn.ReLU(),
                                 nn.Linear(64, 32), nn.ReLU())
        self.linear = nn.Linear(32, 16)

    def forward(self, X):
        return self.linear(self.net(X))

chimera = nn.Sequential(NestMLP(), nn.Linear(16, 20), FixedHiddenMLP())
chimera(X)

注:nn.ReLU()和F.relu()的区别:两种方法都是使用relu激活,只是使用的场景不一样。F.relu()是函数调用,一般使用在foreward函数。nn.ReLU()是模块调用,一般在定义网络层的时候使用。

5.2 参数管理

首先定义一个具有单隐藏层的多层感知机

import torch
from torch import nn

net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 1))
X = torch.rand(size=(2, 4))
net(X)

1. 查看参数

如何查看nn中任意层的权重值。如下所示,我们可以检查第二个全连接层的参数。

print(net[2].state_dict())

输出:OrderedDict([(‘weight’, tensor([[ 0.3016, -0.1901, -0.1991, -0.1220, 0.1121, -0.1424, -0.3060, 0.3400]])), (‘bias’, tensor([-0.0291]))])

可以看到nn.Linear(8, 1)这一层的 ‘weight’ 和 ‘bias’ 。

目标参数

可以具体获取某个参数的值

print(net[2].bias.data)

除了值之外,我们还可以访问每个参数的梯度。

net[2].weight.grad
查看嵌套块的参数

定义了一个网络rgnet,print查看其结构

print(rgnet)

输出:

Sequential(
  (0): Sequential(
    (block 0): Sequential(
      (0): Linear(in_features=4, out_features=8, bias=True)
      (1): ReLU()
      (2): Linear(in_features=8, out_features=4, bias=True)
      (3): ReLU()
    )
    (block 1): Sequential(
      (0): Linear(in_features=4, out_features=8, bias=True)
      (1): ReLU()
      (2): Linear(in_features=8, out_features=4, bias=True)
      (3): ReLU()
    )
    (block 2): Sequential(
      (0): Linear(in_features=4, out_features=8, bias=True)
      (1): ReLU()
      (2): Linear(in_features=8, out_features=4, bias=True)
      (3): ReLU()
    )
    (block 3): Sequential(
      (0): Linear(in_features=4, out_features=8, bias=True)
      (1): ReLU()
      (2): Linear(in_features=8, out_features=4, bias=True)
      (3): ReLU()
    )
  )
  (1): Linear(in_features=4, out_features=1, bias=True)
)

然后可以通过索引访问它们:

rgnet[0][1][0].bias.data

2. 参数初始化

内置初始化

PyTorch的nn.init模块提供了多种预置初始化方法。

下面的代码将所有权重参数m.weight初始化为标准差为0.01的高斯随机变量, 且将偏置参数m.bias设置为0。

def init_normal(m):
    if type(m) == nn.Linear:
        nn.init.normal_(m.weight, mean=0, std=0.01)		# 右下划线表示inplace操作
        nn.init.zeros_(m.bias)
net.apply(init_normal)
net[0].weight.data[0], net[0].bias.data[0]

还可以将所有参数初始化为给定的常数,比如初始化为1。

nn.init.constant_(m.weight, 1)

使用Xavier初始化方法初始化第一个神经网络层

def init_xavier(m):
    if type(m) == nn.Linear:
        nn.init.xavier_uniform_(m.weight)
def init_42(m):
    if type(m) == nn.Linear:
        nn.init.constant_(m.weight, 42)

net[0].apply(init_xavier)
net[2].apply(init_42)
print(net[0].weight.data[0])
print(net[2].weight.data)
自定义初始化

在下面的例子中,我们使用以下的分布为任意权重参数w定义初始化方法:

\begin{split}\begin{aligned} w \sim \begin{cases} U(5, 10) & \text{ 可能性 } \frac{1}{4} \\ 0 & \text{ 可能性 } \frac{1}{2} \\ U(-10, -5) & \text{ 可能性 } \frac{1}{4} \end{cases} \end{aligned}\end{split}

同样,我们实现了一个my_init函数来应用到net。

def my_init(m):
    if type(m) == nn.Linear:
        print("Init", *[(name, param.shape)
                        for name, param in m.named_parameters()][0])
        nn.init.uniform_(m.weight, -10, 10)	# 根据[-10, 10]均匀分布生成一个值
        m.weight.data *= m.weight.data.abs() >= 5	# 如果值在[-5, 5]则改为0

net.apply(my_init)
net[0].weight[:2]

注意,我们始终可以直接设置参数。

net[0].weight.data[:] += 1
net[0].weight.data[0, 0] = 42
net[0].weight.data[0]

3. 参数绑定

有时我们希望在多个层间共享参数: 我们可以定义一个稠密层,然后使用它的参数来设置另一个层的参数。

# 我们需要给共享层一个名称,以便可以引用它的参数
shared = nn.Linear(8, 8)
net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(),
                    shared, nn.ReLU(),
                    shared, nn.ReLU(),
                    nn.Linear(8, 1))
net(X)

此时,net[2]net[4]参数是同一个对象。如果改变其中一个参数,另一个参数也会改变。参数绑定后,在反向传播期间,梯度也会直接加在一起。

5.3 延后初始化

torch.nn.LazyLinear()

5.4 自定义层

不带参数的层
import torch
import torch.nn.functional as F
from torch import nn

class CenteredLayer(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, X):
        return X - X.mean()		# 可以使输出向量的均值为0

layer = CenteredLayer()
layer(torch.FloatTensor([1, 2, 3, 4, 5]))

输出:tensor([-2., -1., 0., 1., 2.])

# 可以像pytorch内置(自带)的层那样使用
net = nn.Sequential(nn.Linear(8, 128), CenteredLayer())
带参数的层
class MyLinear(nn.Module):
    def __init__(self, in_units, units):
        super().__init__()
        # 实例化一个weight,shape为(in_units, units)
        self.weight = nn.Parameter(torch.randn(in_units, units))
        # 实例化bias
        self.bias = nn.Parameter(torch.randn(units,))
    def forward(self, X):
        linear = torch.matmul(X, self.weight.data) + self.bias.data	# W*X+b
        return F.relu(linear)

# 实例化MyLinear类并访问其模型参数
linear = MyLinear(5, 3)
linear.weight

输出:Parameter containing:
tensor([[ 1.9094, -0.8244, -1.6846],
[ 0.6850, 0.8366, -1.3837],
[ 0.0289, 2.0976, 1.3855],
[-0.8574, -0.3557, -0.4109],
[ 2.2963, -1.3008, 1.2173]], requires_grad=True)

X = torch.rand(2, 5)
linear(X)

输出:tensor([[0.0984, 0.5687, 2.8316],
[2.2558, 0.0000, 1.8880]])

同样可以像使用内置的全连接层一样使用自定义层:

net = nn.Sequential(MyLinear(64, 8), MyLinear(8, 1))
net(torch.rand(2, 64))

5.5 加载和保存

张量
x = torch.arange(4)
torch.save(x, 'x-file')
x2 = torch.load('x-file')
存储列表
y = torch.zeros(4)
torch.save([x, y],'x-files')
x2, y2 = torch.load('x-files')
(x2, y2)
存储词典
mydict = {'x': x, 'y': y}
torch.save(mydict, 'mydict')
mydict2 = torch.load('mydict')
mydict2
加载和保存模型参数
torch.save(net.state_dict(), 'mlp.params')
net_clone = MLP()
net_clone.load_state_dict(torch.load('mlp.params'))
net_clone.eval()

5.6 GPU

1. 设备device

在PyTorch中,CPU和GPU可以用torch.device('cpu')torch.device('cuda')表示(默认为0)。

import torch
from torch import nn

torch.device('cpu'), torch.device('cuda'), torch.device('cuda:1')

判断GPU是否可用:

torch.cuda.is_available()

查询可用gpu的数量:

torch.cuda.device_count()

尝试使用gpu:

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)

2. 张量与GPU

查询张量所在设备:

x.device

初始化张量在GPU上:

X = torch.ones(2, 3, device=device)

将张量复制到1号GPU上:

Z = X.cuda(1)

3. 神经网络与GPU

nn模型也可以指定设备,可以将模型参数放在GPU上:

net = net.to(device=device)

但是,要保证所有的数据和参数都在同一个设备上,否则会因为总线传输速度的限制而降低性能。