25

我收到以下错误。

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)

我收到上述错误。在这里,EmbeddingLayerandEncoderRNN是我编写的一个类,它nn.moduleQuestionClassifier类一样继承。

我在这里做错了什么?

4

3 回答 3

45

查看 的pytorch 源代码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在派生类中以相同的方式调用 's init:

super(QuestionClassifier, self).__init__()
于 2017-03-28T22:04:07.230 回答
5

Pytorch 会跟踪您将在自定义模块中编写的子模块( conv1、 )。conv2在引擎盖下,与您的模型对应的图形是自动构建的。

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

如果nn.Module.__init__不被调用(self._modules等于None),当试图添加一个模块时,它会引发一个错误(没有键可以添加到None)。见 源(L540-544)

灵感来自文档

 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 
于 2018-10-16T09:27:42.743 回答
1

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

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

这个 super 的 init 调用应该在这个类的 init 代码中。

于 2020-04-19T12:18:16.030 回答