我正在基于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__
函数。除此之外,提供的代码运行正常。