5.1 层和块
为了实现复杂的网络,我们引入神经网络块的概念块可以描述单个层、多个层组成的组件或模型本身。使用块进行抽象的一个好处是可以将一些块组合成更大的组件,这一过程通常是递归的,如下图所示。通过定义代码来按需生成任意复杂度的块, 我们可以通过简洁的代码实现复杂的神经网络。
从编程角度看,块由类表示,它的任何子类都必须定义一个将其输入转化成输出的前向传播函数,并且存储任何必须的参数。 块必须具有反向传播函数。
下面的代码生成一个网络,其中包含一个具有256个单元和ReLU激活函数的全连接隐藏层, 然后是一个具有10个隐藏单元且不带激活函数的全连接输出层。
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)
在这个例子中,我们通过实例化nn.Sequential
来构建我们的模型, 层的执行顺序是作为参数传递的。 简而言之,nn.Sequential
定义了一种特殊的Module
, 即在PyTorch中表示一个块的类, 它维护了一个由Module
组成的有序列表。两个全连接层都是Linear
类的实例, Linear
类本身就是Module
的子类。
5.1.1 自定义块
简要总结每个块必须提供的基本功能:1.将输入数据作为其前向传播函数的参数。2.通过前向传播函数来生成输出。3.计算其输出关于输入的梯度。4.存储和访问前向传播计算所需的参数。5.根据需要初始化模型参数。
下面从零开始编写一个块。下面的MLP
类继承了表示块的类。 我们的实现只需要提供我们自己的构造函数(Python中的__init__函数)和前向传播函数。
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)))
块的一个主要优点是它的多功能性。 我们可以子类化块以创建层(如全连接层的类)、 整个模型(如上面的MLP
类)或具有中等复杂度的各种组件。
5.1.2 顺序块
Sequential的设计是为了把其他模块串起来。现在构建自己简化的MySequential:
class MySequential(nn.Module):
def __init__(self, *args):
super().__init__()
for idx, module in enumerate(args):
# 这里,module是Module子类的一个实例。我们把它保存在'Module'类的成员
# 变量_modules中。_module的类型是OrderedDict
self._modules[str(idx)] = module
def forward(self, X):
# OrderedDict保证了按照成员添加的顺序遍历它们
for block in self._modules.values():
X = block(X)
return X
5.1.3 在前向传播函数中执行代码
5.1.4 效率
一个块可以由许多层组成,一个块可以由许多块组成。
层和块的顺序连接由Sequential块处理
5.2 参数管理
5.2.1 参数访问
通过Sequential类定义模型时,可以通过索引来访问模型的任意层。
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))
print(net[2].state_dict())
"""
OrderedDict([('weight', tensor([[-0.0427, -0.2939, -0.1894, 0.0220, -0.1709, -0.1522, -0.0334, -0.2263]])), ('bias', tensor([0.0887]))])
"""
print(type(net[2].bias))
print(net[2].bias)
print(net[2].bias.data)
"""
<class 'torch.nn.parameter.Parameter'>
Parameter containing:
tensor([0.0887], requires_grad=True)
tensor([0.0887])
"""
此外,还可以访问每个参数的梯度,由于上面的网络还未调用反向传播,所以参数的梯度处于初始状态。
net[2].weight.grad == None
"""
True
"""
一次性访问所有参数
print(*[(name, param.shape) for name, param in net[0].named_parameters()])
print(*[(name, param.shape) for name, param in net.named_parameters()])
"""
('weight', torch.Size([8, 4])) ('bias', torch.Size([8]))
('0.weight', torch.Size([8, 4])) ('0.bias', torch.Size([8])) ('2.weight', torch.Size([1, 8])) ('2.bias', torch.Size([1]))
"""
net.state_dict()['2.bias'].data
"""
tensor([0.0887])
"""
将多个块互相嵌套
def block1():
return nn.Sequential(nn.Linear(4, 8), nn.ReLU(),
nn.Linear(8, 4), nn.ReLU())
def block2():
net = nn.Sequential()
for i in range(4):
# 在这里嵌套
net.add_module(f'block {i}', block1())
return net
rgnet = nn.Sequential(block2(), nn.Linear(4, 1))
rgnet(X)
"""
tensor([[0.2596],
[0.2596]], grad_fn=<AddmmBackward0>)
"""
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
"""
tensor([ 0.1999, -0.4073, -0.1200, -0.2033, -0.1573, 0.3546, -0.2141, -0.2483])
"""
5.2.2 参数初始化
调用内置的初始化器,下面的代码会将所有权重参数初始化为标准差0.01的高斯随机变量。
def init_normal(m):
if type(m) == nn.Linear:
nn.init.normal_(m.weight, mean=0, std=0.01)
nn.init.zeros_(m.bias)
net.apply(init_normal)
也可以指定常数
def init_constant(m):
if type(m) == nn.Linear:
nn.init.constant_(m.weight, 1)
nn.init.zeros_(m.bias)
net.apply(init_constant)
5.2.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)
# 检查参数是否相同
print(net[2].weight.data[0] == net[4].weight.data[0])
net[2].weight.data[0, 0] = 100
# 确保它们实际上是同一个对象,而不只是有相同的值
print(net[2].weight.data[0] == net[4].weight.data[0])
"""
tensor([True, True, True, True, True, True, True, True])
tensor([True, True, True, True, True, True, True, True])
"""
5.3 延后初始化
到目前为止,我们忽略了建立网络时需要做的以下这些事情:
定义了网络架构,但没有指定输入维度。
添加层时没有指定前一层的输出维度。
在初始化参数时,甚至没有足够的信息来确定模型应该包含多少参数。
延后初始化即直到数据第一次通过模型传递时,框架才会动态地推断出每个层的大小。在以后使用卷积神经网络时,由于输入维度(即图像的分辨率)将影响每个后续层的维数,现在编写代码时无需知道维度时什么就可以设置参数。
5.3.1 实例化网络
5.4 自定义层
5.4.1 不带参数的层
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()
现在可以将层作为组件合并到更复杂的模型中。
net = nn.Sequential(nn.Linear(8, 128), CenteredLayer())
5.4.2 带参数的层
class MyLinear(nn.Module):
def __init__(self, in_units, units):
super().__init__()
self.weight = nn.Parameter(torch.randn(in_units, units))
self.bias = nn.Parameter(torch.randn(units,))
def forward(self, X):
linear = torch.matmul(X, self.weight.data) + self.bias.data
return F.relu(linear)
可以使用自定义层直接执行前向传播计算
linear(torch.rand(2, 5))
5.5 读写文件
5.5.1 加载和保存张量
对于单个张量,我们可以直接调用load
和save
函数分别读写它们。 这两个函数都要求我们提供一个名称,save
要求将要保存的变量作为输入。
import torch
from torch import nn
from torch.nn import functional as F
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')
5.5.2 加载和保存模型参数
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.hidden = nn.Linear(20, 256)
self.output = nn.Linear(256, 10)
def forward(self, x):
return self.output(F.relu(self.hidden(x)))
net = MLP()
X = torch.randn(size=(2, 20))
Y = net(X)
将模型的参数存储在一个叫做mlp.params的文件中
torch.save(net.state_dict(), 'mlp.params')
为了恢复模型,我们实例化了原始多层感知机模型的一个备份。 这里我们不需要随机初始化模型参数,而是直接读取文件中存储的参数。
clone = MLP()
clone.load_state_dict(torch.load('mlp.params'))
clone.eval()
"""
MLP(
(hidden): Linear(in_features=20, out_features=256, bias=True)
(output): Linear(in_features=256, out_features=10, bias=True)
)
"""
5.6 GPU
5.6.1 计算设备
查询可用gpu的数量。
torch.cuda.device_count()
定义了两个方便的函数, 这两个函数允许我们在不存在所需所有GPU的情况下运行代码。
def try_gpu(i=0): #@save
"""如果存在,则返回gpu(i),否则返回cpu()"""
if torch.cuda.device_count() >= i + 1:
return torch.device(f'cuda:{i}')
return torch.device('cpu')
def try_all_gpus(): #@save
"""返回所有可用的GPU,如果没有GPU,则返回[cpu(),]"""
devices = [torch.device(f'cuda:{i}')
for i in range(torch.cuda.device_count())]
return devices if devices else [torch.device('cpu')]
5.6.2 张量与GPU
默认情况下,张量是在CPU上创建的。
x = torch.tensor([1, 2, 3])
x.device
"""
device(type='cpu')
"""
存储在GPU上
X = torch.ones(2, 3, device=try_gpu())
X
"""
tensor([[1., 1., 1.],
[1., 1., 1.]], device='cuda:0')
"""
假设我们至少有两个GPU,下面的代码将在第二个GPU上创建一个随机张量。
Y = torch.rand(2, 3, device=try_gpu(1))
Y
"""
tensor([[0.4860, 0.1285, 0.0440],
[0.9743, 0.4159, 0.9979]], device='cuda:1')
"""
5.6.3 神经网络与GPU
神经网络模型可以指定设备。 下面的代码将模型参数放在GPU上。
net = nn.Sequential(nn.Linear(3, 1))
net = net.to(device=try_gpu())