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__() 调用之前分配模
基础教程推荐
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
