我对PyTorch还不熟悉,为什么即使在NeuralNet类中添加了super(ClassName,self).__init__()后仍然会出现属性错误?

我正在基于PyTorch开发一个聊天机器人,即使在NeuralNet类中添加了super,我仍然无法找出属性错误的原因。我使用的是Jupyter Notebook进行这个项目。

这是我目前的代码,来自model.ipynb和train.ipynb的部分内容

class NeuralNet(nn.Module):    def __init__(self, input_size, hidden_size, num_classes):        super().__init__()        self.l1 = nn.Linear(input_size, hidden_size)         self.l2 = nn.Linear(hidden_size, hidden_size)         self.l3 = nn.Linear(hidden_size, num_classes)        self.relu = nn.ReLU()        #Trainimport torchimport torch.nn as nnfrom torch.utils.data import Dataset, DataLoaderfrom ipynb.fs.full.model import NeuralNetclass ChatDataset(Dataset):    def __init__(self):        self.n_samples = len(x_train)        self.x_data = x_train        self.y_data = y_train    #hyperParametersbatch_size = 8hidden_size = 8output_size = len(tags)input_size = len(all_words)# print(input_size, len(all_words))# print(output_size, tags)learning_rate = 0.001num_epochs = 1000    dataset = ChatDataset()train_loader = DataLoader(dataset = dataset , batch_size=batch_size, shuffle=True, num_workers=2)  model = NeuralNet(input_size, hidden_size, output_size)``` ERROR:~\Untitled Folder\model.ipynb in __init__(self, input_size, hidden_size, num_classes)      9    "source": [     10     "import torch\n",---> 11     "import torch.nn as nn"     12    ]     13   },~\anaconda3a\lib\site-packages\torch\nn\modules\module.py in __setattr__(self, name, value)   1234             if isinstance(value, Module):   1235                 if modules is None:-> 1236                     raise AttributeError(   1237                         "cannot assign module before Module.__init__() call")   1238                 remove_from(self.__dict__, self._parameters, self._buffers, self._non_persistent_buffers_set)AttributeError: cannot assign module before Module.__init__() call

回答:

这很可能是由于你在NeuralNet的__init__函数中没有在注册子模块之前调用super().__init__。请参阅这里获取更多详细信息。

唯一缺少的部分是ChatDataset类上的__len__函数。除此之外,提供的代码运行正常。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注