【问题标题】:AttributeError: cannot assign module before Module.__init__() callAttributeError:无法在 Module.__init__() 调用之前分配模块
【发布时间】:2017-08-22 04:16:21
【问题描述】:

我收到以下错误。

Traceback (most recent call last):
  File "main.py", line 63, in <module>
    question_classifier = QuestionClassifier(corpus.dictionary, embeddings_index, corpus.max_sent_length, args)
  File "/net/if5/wua4nw/wasi/academic/research_with_prof_chang/projects/question_answering/duplicate_question_detection/source/question_classifier.py", line 26, in __init__
    self.embedding = EmbeddingLayer(len(dictionary), args.emsize, args.dropout)
  File "/if5/wua4nw/anaconda3/lib/python3.5/site-packages/torch/nn/modules/module.py", line 255, in __setattr__
    "cannot assign module before Module.__init__() call")
AttributeError: cannot assign module before Module.__init__() call

我有一堂课如下。

class QuestionClassifier(nn.Module):

     def __init__(self, dictionary, embeddings_index, max_seq_length, args):
         self.embedding = EmbeddingLayer(len(dictionary), args.emsize, args.dropout)
         self.encoder = EncoderRNN(args.emsize, args.nhid, args.model, args.bidirection, args.nlayers, args.dropout)
         self.drop = nn.Dropout(args.dropout)

所以,当我运行以下行时:

question_classifier = QuestionClassifier(corpus.dictionary, embeddings_index, corpus.max_sent_length, args)

我收到上述错误。这里EmbeddingLayerEncoderRNN是我写的一个类,继承nn.module就像QuestionClassifier类。

我在这里做错了什么?

【问题讨论】:

  • 你能发布完整的堆栈跟踪吗?
  • 我已经发布了。我相信我错过了一些东西,但不知道是什么!
  • 我不熟悉torch,但也许您必须在派生类__init__ 中调用nn.Module.__init__(),然后才能修改任何属性...
  • 其实我就是这么做的!!
  • 在您的代码中?在分配给属性之前?我不知道在哪里......

标签: python pytorch


【解决方案1】:

查看pytorchsource code for Module,我们在文档字符串中看到从Module 派生的示例包括:

 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)

所以你可能想在你的派生类中以同样的方式调用Module的init:

super(QuestionClassifier, self).__init__()

【讨论】:

  • super().__init__() 工作吗?
  • @CharlieParker 是的,它们是等价的(除非出于某种原因,您仍在使用 Python 2)
【解决方案2】:

Pytorch 会跟踪您将在自定义模块中编写的子模块(conv1conv2)。在后台,与您的模型对应的图表是自动构建的。

嵌套的模块将被添加到 OrderedDict _modules(在 nn.Module.__init__ 中初始化)参见 source(L69)

如果不调用nn.Module.__init__self._modules 等于None),尝试添加模块时,将引发错误(无法向None 添加键)。看 source(L540-544)

灵感来自doc

 class CustomModule(nn.Module):
        def __init__(self):
            super(CustomModule, self).__init__() # Initialize self._modules as OrderedDict
            self.conv1 = nn.Conv2d(1, 20, 5)     # Add key conv1 to self._modules
            self.conv2 = nn.Conv2d(20, 20, 5)    # Add key conv2 to self._modules 

【讨论】:

  • super().__init__() 工作吗?
【解决方案3】:

这通常发生在未调用超类的 init 时。在这种情况下,应该使用 super.__init__() 调用来开始他们的神经网络类。代码如下所示:

class QuestionClassifier(nn.Module):
    def __init__(self, dictionary, embeddings_index, max_seq_length, args):
       super().__init__()

这个超级的初始化调用应该在这个类的初始化代码中。

【讨论】:

  • super().__init__() 工作吗?
猜你喜欢
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-16
  • 2020-07-02
  • 2022-10-05
  • 1970-01-01
相关资源
最近更新 更多