AttributeError: 无法在 Module.__init__() 调用之前分配模块 [英] AttributeError: cannot assign module before Module.__init__() call

查看:25
本文介绍了AttributeError: 无法在 Module.__init__() 调用之前分配模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误.

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)

因此,当我运行以下行时:

So, when I run the following line:

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

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

I get the above mentioned error. Here, EmbeddingLayer and EncoderRNN is a class written by me which inherits nn.module like the QuestionClassifier class.

我在这里做错了什么?

推荐答案

pytorch Module 的源代码,我们在文档字符串中看到一个从 Module 派生的例子,包括:

Looking at the pytorch source code for Module, we see in the docstring an example of deriving from Module includes:

 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:

So you probably want to call Module's init the same way in your derived class:

super(QuestionClassifier, self).__init__()

这篇关于AttributeError: 无法在 Module.__init__() 调用之前分配模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆