AttributeError: cannot assign module before Module.__init__() call(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)
我收到上述错误.这里EmbeddingLayer和EncoderRNN是我写的一个类,它继承了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__() 调用之前分配模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:AttributeError: 无法在 Module.__init__() 调用之前分配模
基础教程推荐
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
