《动手学深度学习》——深度学习计算
层和块
自定义快
- 我们的实现将严重依赖父类,只需要提供我们自己的构造函数(Python中的__init__函数)和正向传播函数。
注意,除非我们实现一个新的运算符,否则我们不必担心反向传播函数或参数初始化,系统将自动生成这些class MLP(nn.Module): # 用模型参数声明层。这里,我们声明两个全连接的层 def __init__(self): # 调用`MLP`的父类`Block`的构造函数来执行必要的初始化。 # 这样,在类实例化时也可以指定其他函数参数,例如模型参数`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()
顺序块
- 为了构建我们自己的简化的MySequential,我们只需要定义两个关键函数:
- 一种将块逐个追加到列表中的函数
- 一种正向传播函数,用于将输入按追加块的顺序传递给块组成的“链条”
class MySequential(nn.Module): def __init__(self, *args): super().__init__() for block in args: # 这里,`block`是`Module`子类的一个实例。我们把它保存在'Module'类的成员变量 # `_modules` 中。`block`的类型是OrderedDict。 self._modules[block] = block def forward(self, X): # OrderedDict保证了按照成员添加的顺序遍历它们 for block in self._modules.values(): X = block(X) return X net = MySequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10)) net(X)
在正向传播函数中执行代码
- 有时我们可能希望合并既不是上一层的结果也不是可更新参数的项。我们称之为常数参数(constant parameters)
在这个FixedHiddenMLP模型中,我们实现了一个隐藏层,其权重(self.rand_weight)在实例化时被随机初始化,之后为常量。这个权重不是一个模型参数,因此它永远不会被反向传播更新。然后,网络将这个固定层的输出通过一个全连接层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`和`dot`函数。 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()
参数管理
参数访问
- 当通过Sequential类定义模型时,我们可以通过索引来访问模型的任意层
print(net[2].state_dict()) OrderedDict([('weight', tensor([[ 0.2065, 0.1124, -0.1230, -0.0182, -0.0172, -0.3526, -0.2300, -0.3313]])), ('bias', tensor([-0.0957]))])
目标参数
- 要对参数执行任何操作,首先我们需要访问底层的数值
print(type(net[2].bias)) print(net[2].bias) print(net[2].bias.data) <class 'torch.nn.parameter.Parameter'> Parameter containing: tensor([-0.0957], requires_grad=True) tensor([-0.0957]) # 访问梯度 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]))
参数初始化
- 内置初始化
- 将所有权重参数初始化为标准差为0.01的高斯随机变量,且将偏置参数设置为0:
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) net[0].weight.data[0], net[0].bias.data[0] - 对某些块应用不同的初始化方法
def 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(xavier) net[2].apply(init_42) print(net[0].weight.data[0]) print(net[2].weight.data)
- 将所有权重参数初始化为标准差为0.01的高斯随机变量,且将偏置参数设置为0:
- 自定义初始化
- 我们实现了一个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) m.weight.data *= m.weight.data.abs() >= 5 net.apply(my_init) net[0].weight[:2]
- 我们实现了一个my_init函数来应用到net:
参数绑定
- 多个层间共享参数
# 我们需要给共享层一个名称,以便可以引用它的参数。 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])