『PyTorch』第七弹_nn.Module扩展层

本文详细介绍了如何在PyTorch中自定义神经网络层,包括继承nn.Module类、定义可学习参数及前向传播过程。同时展示了如何构建多层感知机。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有下面代码可以看出torch层函数(nn.Module)用法,使用超参数实例化层函数类(常位于网络class的__init__中),而网络class实际上就是一个高级的递归的nn.Module的class。

 

通常

torch.nn的核心数据结构是Module,它是一个抽象概念,既可以表示神经网络中的某个层(layer),也可以表示一个包含很多层的神经网络。

在实际使用中,最常见的做法是继承nn.Module,撰写自己的网络/层。

  • 自定义层Linear必须继承nn.Module,并且在其构造函数中需调用nn.Module的构造函数,即super(Linear, self).__init__()nn.Module.__init__(self),推荐使用第一种用法。
  • 在构造函数__init__中必须自己定义可学习的参数,并封装成Parameter,如在本例中我们把wb封装成parameterparameter是一种特殊的Variable,但其默认需要求导(requires_grad = True)。
  • forward函数实现前向传播过程,其输入可以是一个或多个variable,对x的任何操作也必须是variable支持的操作。
  • 无需写反向传播函数,因其前向传播都是对variable进行操作,nn.Module能够利用autograd自动实现反向传播,这点比Function简单许多。
  • 使用时,直观上可将layer看成数学概念中的函数,调用layer(input)即可得到input对应的结果。它等价于layers.__call__(input),在__call__函数中,主要调用的是 layer.forward(x),另外还对钩子做了一些处理。所以在实际使用中应尽量使用layer(x)而不是使用layer.forward(x)
  • Module中的可学习参数可以通过named_parameters()或者parameters()返回迭代器,前者会给每个parameter都附上名字,使其更具有辨识度。

Module能够自动检测到自己的Parameter,并将其作为学习参数。

可见利用Module实现的全连接层,比利用Function实现的更为简单,因其不再需要写反向传播函数。

import torch as t
from torch import nn
from torch.autograd import Variable as V

class Linear(nn.Module):
    def __init__(self, in_features, out_features):
        # nn.Module.__init__(self)
        super(Linear, self).__init__()
        self.w = nn.Parameter(t.randn(in_features, out_features)) # nn.Parameter是特殊Variable
        self.b = nn.Parameter(t.randn(out_features))
        
    def forward(self, x):
        x = x.mm(self.w)
        return x + self.b

layer = Linear(4, 3)
input = V(t.randn(2, 4))
output = layer(input)
print(output)

for name, Parameter in layer.named_parameters():
    print(name, Parameter)

Variable containing:
 4.1151  2.4139  3.5544
-0.4792 -0.9400 -7.6010
[torch.FloatTensor of size 2x3]

w Parameter containing:
 1.1856  0.9246  1.1707
 0.2632 -0.1697  0.7543
-0.4501 -0.2762 -3.1405
-1.1943  1.2800  1.0712
[torch.FloatTensor of size 4x3]

b Parameter containing:
 1.9577
 1.8570
 0.5249
[torch.FloatTensor of size 3]

 

递归

除了parameter之外,Module还包含子Module,主Module能够递归查找子Module中的parameter

  • 构造函数__init__中,可利用前面自定义的Linear层(module),作为当前module对象的一个子module,它的可学习参数,也会成为当前module的可学习参数。
  • 在前向传播函数中,我们有意识地将输出变量都命名成x,是为了能让Python回收一些中间层的输出,从而节省内存。但并不是所有都会被回收,有些variable虽然名字被覆盖,但其在反向传播仍需要用到,此时Python的内存回收模块将通过检查引用计数,不会回收这一部分内存。

module中parameter的命名规范:

  • 对于类似self.param_name = nn.Parameter(t.randn(3, 4)),命名为param_name
  • 对于子Module中的parameter,会其名字之前加上当前Module的名字。如对于self.sub_module = SubModel(),SubModel中有个parameter的名字叫做param_name,那么二者拼接而成的parameter name 就是sub_module.param_name

下面再来看看稍微复杂一点的网络,多层感知机:

class Perceptron (nn.Module):
    def __init__(self, in_features, hidden_features, out_features):
        nn.Module.__init__(self)
        self.layer1 = Linear(in_features, hidden_features)
        self.layer2 = Linear(hidden_features, out_features)
        
    def forward(self, x):
        x = self.layer1(x)
        x = t.sigmoid(x)
        return self.layer2(x)

per = Perceptron(3, 4, 1)
for name, param in per.named_parameters():
    print(name, param.size())
('layer1.w', torch.Size([3, 4]))
('layer1.b', torch.Size([4]))
('layer2.w', torch.Size([4, 1]))
('layer2.b', torch.Size([1]))

 

# 4. PreNormTransformerEncoderLayer class PreNormTransformerEncoderLayer(nn.Module): def __init__(self, d_model: int, nhead: int, dim_feedforward: int = 2048, dropout: float = 0.1, batch_first: bool = True, activation: nn.Module = nn.GELU(), bias: bool = False): super().__init__() self.self_attn = nn.MultiheadAttention( embed_dim=d_model, num_heads=nhead, dropout=dropout, batch_first=batch_first, bias=bias ) self.norm1 = nn.LayerNorm(d_model) self.norm2 = nn.LayerNorm(d_model) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) # 激活函数处理 if isinstance(activation, str): activation = activation.lower() if activation == "relu": self.activation = nn.ReLU() elif activation == "gelu": self.activation = nn.GELU() else: raise ValueError(f"Unsupported activation: {activation}") else: self.activation = activation # 前馈网络 self.feedforward = nn.Sequential( nn.Linear(d_model, dim_feedforward, bias=bias), self.activation, nn.Dropout(dropout), nn.Linear(dim_feedforward, d_model, bias=bias) ) self._reset_parameters() def _reset_parameters(self): # 自注意力参数初始化 nn.init.xavier_uniform_(self.self_attn.in_proj_weight) if self.self_attn.in_proj_bias is not None: nn.init.constant_(self.self_attn.in_proj_bias, 0.) nn.init.xavier_uniform_(self.self_attn.out_proj.weight) if self.self_attn.out_proj.bias is not None: nn.init.constant_(self.self_attn.out_proj.bias, 0.) # 前馈网络改进初始化 nn.init.kaiming_uniform_( # 改为Kaiming初始化 self.feedforward[0].weight, nonlinearity='gelu' if isinstance(self.activation, nn.GELU) else 'relu' ) if self.feedforward[0].bias is not None: nn.init.constant_(self.feedforward[0].bias, 0.) nn.init.xavier_uniform_(self.feedforward[-1].weight) # 最后一保持Xavier if self.feedforward[-1].bias is not None: nn.init.constant_(self.feedforward[-1].bias, 0.) def forward(self, src: Tensor, src_mask: Optional[Tensor] = None, src_key_padding_mask: Optional[Tensor] = None) -> Tensor: # 复用LayerNorm计算结果 normed_src = self.norm1(src) attn_output = self.self_attn( normed_src, normed_src, normed_src, attn_mask=src_mask, key_padding_mask=src_key_padding_mask, need_weights=False )[0] src = src + self.dropout1(attn_output) # Feedforward normed_src2 = self.norm2(src) ff_output = self.feedforward(normed_src2) src = src + self.dropout2(ff_output) return src
最新发布
03-19
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值