【问题标题】:Why not super().__init__(Model,self) in Pytorch为什么不在 Pytorch 中使用 super().__init__(Model,self)
【发布时间】:2020-04-18 11:19:10
【问题描述】:

对于torch.nn.Module()

根据官方文档: 所有神经网络模块的基类。 你的模型也应该继承这个类。 模块还可以包含其他模块,允许将它们嵌套在树结构中。您可以将子模块分配为常规属性。

import torch.nn as nn
import torch.nn.functional as F

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.conv1 = nn.Conv2d(1, 20, 5)
        self.conv2 = nn.Conv2d(20, 20, 5)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        return F.relu(self.conv2(x))

它使用了super(Model, self).__init__() 为什么不super().__init__(Model, self)

【问题讨论】:

  • 因为第二个会调用一个带有 2 个参数的 init 函数?
  • 对于super(Model, self).__init__() 是不是真的和super().__init__()一样
  • 但是您的问题列出了super().__init__(Model, self),这是不同的。而super() 仅在 Python 3 之后才有效,因此大概文档希望向后兼容 Python 2
  • 有道理,谢谢!

标签: python class oop inheritance pytorch


【解决方案1】:

这个结构:

super().__init__(self)

仅在 Python 3.x 中有效,而以下构造,

super(Model, self).__init__()

适用于 Python 2.x 和 Python 3.x。因此,PyTorch 开发人员不想通过强制执行 Python 3.x syntax of super() 来破坏所有用 Python 2.x 编写的代码,因为在这种情况下,这两种结构本质上都是做同样的事情,即初始化以下变量:

    self.training = True
    self._parameters = OrderedDict()
    self._buffers = OrderedDict()
    self._backward_hooks = OrderedDict()
    self._forward_hooks = OrderedDict()
    self._forward_pre_hooks = OrderedDict()
    self._state_dict_hooks = OrderedDict()
    self._load_state_dict_pre_hooks = OrderedDict()
    self._modules = OrderedDict()

详情请看PyTorch论坛上的相关讨论,is-there-a-reason-why-people-use-super-class-self-init-instead-of-super-init?

【讨论】:

    【解决方案2】:

    还有另一种方法在 Python 2.x 和 3.x 中都可用。它不使用复杂的super() 函数,它的含义很清楚,如果涉及两个超类,则不会产生误导。你可以直接调用超类的构造函数:

    class Model(nn.Module):
        def __init__(self):
            nn.Module.__init__(self)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 2012-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多