【发布时间】:2021-09-30 22:21:55
【问题描述】:
从我的 LSTM 模型进行预测时,我收到错误 :: AttributeError: 'LSTMClassifier' object has no attribute 'log_softmax'。谁能解释我做错了什么?
class LSTMClassifier(nn.Module):
def __init__(self, input_dim, hidden_dim, layer_dim, output_dim):
super().__init__()
self.hidden_dim = hidden_dim
self.layer_dim = layer_dim
self.lstm = nn.LSTM(input_dim, hidden_dim, layer_dim, batch_first=True)
self.fc = nn.Linear(hidden_dim, output_dim)
self.batch_size = None
self.hidden = None
def forward(self, x):
h0, c0 = self.init_hidden(x)
out, (hn, cn) = self.lstm(x, (h0, c0))
out = self.fc(out[:, -1, :])
return out
def init_hidden(self, x):
h0 = torch.zeros(self.layer_dim, x.size(0), self.hidden_dim)
c0 = torch.zeros(self.layer_dim, x.size(0), self.hidden_dim)
print(x.size(0))
print(layer_dim)
return [t.to(device) for t in (h0, c0)]
test_dl = DataLoader(tst_data, batch_size=64, shuffle=False)
test = []
print('Predicting on test dataset')
for batch, _ in tst_data:
batch=batch.to(device)
print(batch.shape)
out = model.to(device)
y_hat = F.log_softmax(out, dim=1).argmax(dim=1) ### at this line I am getting error
test += y_hat.tolist()
提前谢谢你!
Error :: AttributeError: 'LSTMClassifier' 对象没有属性 'log_softmax'
回溯:::
AttributeError Traceback (most recent call last)
<ipython-input-74-df6f970f9b87> in <module>()
8 print(batch.shape)
9 out = model.to(device)
---> 10 y_hat = F.log_softmax(out, dim=1).argmax(dim=1)
11
12 test += y_hat.tolist()
1 frames
/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py in __getattr__(self, name)
1129 return modules[name]
1130 raise AttributeError("'{}' object has no attribute '{}'".format(
-> 1131 type(self).__name__, name))
1132
1133 def __setattr__(self, name: str, value: Union[Tensor, 'Module']) -> None:
AttributeError: 'LSTMClassifier' object has no attribute 'log_softmax'
【问题讨论】:
-
您是否检查了
F的值并确保它是torch.nn.functional?你能提供完整的错误跟踪吗? -
我已经在问题本身中添加了错误跟踪。
标签: pytorch lstm prediction tensor softmax