《动手学深度学习》——深度学习计算

参考资料:

5.1 层和块

为了实现这些复杂的网络,我们引入了神经网络块的概念。块(block)可以描述单个层、由多个层组成的组件或整个模型本身。

从编程的角度来看,块由类(class)表示。它的任何子类都必须定义一个将其输入转换为输出的前向传播函数,并且必须存储任何必需的参数。

5.1.1 自定义块

每个块的基本工作:

  1. 将输入数据作为其前向传播函数的参数。
  2. 通过前向传播函数来生成输出。请注意,输出的形状可能与输入的形状不同。例如,我们上面模型中的第一个全连接的层接收一个 20 维的输入,但是返回一个维度为 256 的输出。
  3. 计算其输出关于输入的梯度,可通过其反向传播函数进行访问。通常这是自动发生的。
  4. 存储和访问前向传播计算所需的参数。
  5. 根据需要初始化模型参数。

下面,我们将自定义一个多层感知机,具有 256 个隐藏单元的隐藏层和一个 10 维输出层:

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

5.1.2 顺序块

为了构建我们自己的简化的 MySequential ,我们只需要定义两个关键函数:

  1. 一种将块逐个追加到列表中的函数;
  2. 一种前向传播函数,用于将输入按追加块的顺序传递给块组成的“链条”。
class MySequential(nn.Module):
    def __init__(self, *args):
        super().__init__()
        # enumerate()用于将一个可遍历的数据对象组合为一个带索引的序列
        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 在前向传播中执行代码

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

5.2 参数管理

5.2.1 参数访问

当通过 Sequential 类定义模型时,我们可以通过索引来访问模型的任意层。这就像模型是一个列表一样,每层的参数都在其属性中:

print(net[2].state_dict())
# OrderedDict([('weight', tensor([[-0.0037,  0.2380,  0.0952, -0.2980, -0.0466,  0.1882,  0.1031, -0.0204]])), ('bias', tensor([-0.1572]))])

5.2.1.1 目标参数

每个参数都表示为参数类的一个实例,包含值、梯度和额外信息:

print(type(net[2].bias))
print(net[2].bias)
print(net[2].bias.data)
# <class 'torch.nn.parameter.Parameter'>
# Parameter containing:
# tensor([-0.1572], requires_grad=True)
# tensor([-0.1572])

5.2.1.2 一次性访问所有参数

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

从 0 直接跳到 2 的原因:ReLU层没有参数

这为我们提供了另一种访问网络参数的方式,如下所示:

net.state_dict()['2.bias'].data

5.2.1.3 从嵌套块收集参数

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)
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)
# )
print(*[(name, param.shape) for name, param in rgnet.named_parameters()])
# ('0.block 0.0.weight', torch.Size([8, 4])) ('0.block 0.0.bias', torch.Size([8])) ('0.block 0.2.weight', torch.Size([4, 8])) ('0.block 0.2.bias', torch.Size([4])) ('0.block 1.0.weight', torch.Size([8, 4])) ('0.block 1.0.bias', torch.Size([8])) ('0.block 1.2.weight', torch.Size([4, 8])) ('0.block 1.2.bias', torch.Size([4])) ('0.block 2.0.weight', torch.Size([8, 4])) ('0.block 2.0.bias', torch.Size([8])) ('0.block 2.2.weight', torch.Size([4, 8])) ('0.block 2.2.bias', torch.Size([4])) ('0.block 3.0.weight', torch.Size([8, 4])) ('0.block 3.0.bias', torch.Size([8])) ('0.block 3.2.weight', torch.Size([4, 8])) ('0.block 3.2.bias', torch.Size([4])) ('1.weight', torch.Size([1, 4])) ('1.bias', torch.Size([1]))

从上面的代码中可以很容易地看出块之间的分层嵌套结构,所以,我们可按照如下方式访问参数:

rgnet[0][1][0].bias.data
rgnet.state_dict()['0.block 1.0.bias'].data

5.2.2 参数初始化

对不同层使用不同的初始化方法。

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)

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)

上述的神经网络中,第三层和第五层的参数是绑定的,如果改变其中一个参数,另一个也会改变。

5.3 延后初始化

5.4 自定义层

5.4.1 不带参数的层

# 该层实现了从其输入中减去均值
class CenteredLayer(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, X):
        return X - X.mean()

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)

5.5 读写文件

5.5.1 加载和保存张量

# 保存、加载张量
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')

# 保存、加载张量字典
mydict = {
    
    'x': x, 'y': y}
torch.save(mydict, 'mydict')
mydict2 = torch.load('mydict')

5.5.2 加载和保存模型参数

我们可以通过参数字典保存和加载网络的全部参数;保存架构必须在代码中完成,而不是在参数中完成:

# 保存参数
torch.save(net.state_dict(), 'mlp.params')
# 保存架构
clone = MLP()
# 加载参数
clone.load_state_dict(torch.load('mlp.params'))

5.6 GPU

5.6.1 计算设备

默认情况下,张量是在内存中创建的,然后使用CPU计算它。

在 PyTorch 中,CPU 和 GPU 可以用 torch.device('cpu')torch.device('cuda') 表示。应该注意的是,cpu 设备意味着所有物理 CPU 和内存,这意味着 PyTorch 的计算将尝试使用所有 CPU 核心。然而,gpu 设备只代表一个卡和相应的显存。如果有多个 GPU,我们使用 torch.device(f'cuda:{i}') 来表示第 i i i 块 GPU( i i i 从 0 开始)。另外,cuda:0 cuda 是等价的。

我们可以查询可用 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')]

try_gpu(), try_gpu(10), try_all_gpus()

5.6.2 张量与GPU

我们可以查询张量所在的设备:

x = torch.tensor([1, 2, 3])
x.device
# device(type='cpu')

需要注意的是,无论何时我们要对多个项进行操作, 它们都必须在同一个设备上。

5.6.2.1 存储在GPU上

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

5.6.2.2 复制

5.6.3 神经网络与GPU

net = nn.Sequential(nn.Linear(3, 1))
net = net.to(device=try_gpu())

猜你喜欢

转载自blog.csdn.net/MaTF_/article/details/131585716