代码:
import torch.nn as nnclass Model(nn.Module):def __init__(self, input_dim, output_dim):self.linear = nn.Linear(input_dim, output_dim) def forward(self, x):out = self.linear(x)return outmodel = Model(1, 1)
报错:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[20], line 118 out = self.linear(x)9 return out
---> 11 model = Model(1, 1)Cell In[20], line 5, in Model.__init__(self, input_dim, output_dim)4 def __init__(self, input_dim, output_dim):
----> 5 self.linear = nn.Linear(input_dim, output_dim)File C:\PyCode\venv_ai\lib\site-packages\torch\nn\modules\module.py:1214, in Module.__setattr__(self, name, value)1212 if isinstance(value, Module):1213 if modules is None:
-> 1214 raise AttributeError(1215 "cannot assign module before Module.__init__() call")1216 remove_from(self.__dict__, self._parameters, self._buffers, self._non_persistent_buffers_set)1217 modules[name] = valueAttributeError: cannot assign module before Module.__init__() call
原因:
这个错误信息表明在Model类的构造函数中,你试图在调用父类nn.Module的构造函数之前就赋值一个模块(nn.Linear)。在PyTorch中,你应该首先调用父类的构造函数,然后再定义子类的属性。
修改:
import torch.nn as nnclass Model(nn.Module):def __init__(self, input_dim, output_dim):super().__init__() # 调用父类的构造函数self.linear = nn.Linear(input_dim, output_dim) # 然后定义子类的属性def forward(self, x):out = self.linear(x)return outmodel = Model(1, 1)