pytorch 基础系列(四)——nn.module

torch.nn的核心数据结构是Module,它是一个抽象概念,既可以表示神经网络中的某个层(layer),也可以表示一个包含很多层的神经网络。无需纠结variable和tensor了,0.4版本已经将两个类彻底合并了。

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

  • 自定义层Linear必须继承nn.Module,并且在其构造函数中需调用nn.Module的构造函数,即super(Linear, self).__init__()nn.Module.__init__(self),推荐使用第一种用法。
  • 在构造函数__init__中必须自己定义可学习的参数并封装成Parameter,你比如 _FasterRcnn类init中定义了  self.RCNN_loss_cls = 0  和 self.RCNN_loss_bbox = 0  还有在本例中我们把wb封装成parameterparameter是一种特殊的Variable,但其默认需要求导(requires_grad = True)。
  • forward函数实现前向传播过程,其输入可以是一个或多个variable,对x的任何操作也必须是variable支持的操作。
  • 无需写反向传播函数,因其前向传播都是对variable进行操作,nn.Module能够利用autograd自动实现反向传播,这点比Function简单许多。 faster rcnn等中反向传播直接写pass的原因。
  • 使用时,直观上可将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实现的更为简单,因其不再需要写反向传播函数。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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

 

 

  • 8
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这段代码定义了一个名为`RestNetBasicBlock`的类,它是ResNet中的基本残差块。下面是对代码的逐行解释: ```python import torch import torch.nn as nn from torch.nn import functional as F ``` 首先导入了PyTorch库及其相关模块。 ```python class RestNetBasicBlock(nn.Module): def __init__(self, in_channels, out_channels, stride): super(RestNetBasicBlock, self).__init__() self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1) self.bn1 = nn.BatchNorm2d(out_channels) self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=stride, padding=1) self.bn2 = nn.BatchNorm2d(out_channels) ``` 接下来定义了一个名为`RestNetBasicBlock`的类,它继承自`nn.Module`类。构造函数`__init__`接受三个参数:`in_channels`表示输入特征图的通道数,`out_channels`表示输出特征图的通道数,`stride`表示卷积层的步长。 在构造函数中,定义了两个卷积层(`conv1`和`conv2`)和两个批归一化层(`bn1`和`bn2`)。这些层用于构建基本残差块。 ```python def forward(self, x): output = self.conv1(x) output = F.relu(self.bn1(output)) output = self.conv2(output) output = self.bn2(output) return F.relu(x + output) ``` `forward`方法定义了正向传播过程。给定输入`x`,首先通过第一个卷积层`conv1`进行卷积操作,得到`output`。然后将`output`通过批归一化层`bn1`和ReLU激活函数进行处理。 接下来,将处理后的特征图`output`再次通过第二个卷积层`conv2`进行卷积操作,得到最终的输出特征图。然后再将输出特征图通过批归一化层`bn2`进行处理。 最后,将输入特征图`x`与输出特征图相加,并通过ReLU激活函数进行处理,得到最终的输出。 这个基本残差块的设计遵循了ResNet的思想,通过跳跃连接将输入与输出相加,并使用ReLU激活函数来引入非线性。这样可以解决网络训练中的梯度消失问题,使得更深的网络能够更容易地训练和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值