以上问题报错的地方是冒号后面的代码,请求给出修改方法: def forward(self, x): h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) x = x.view(-1, self.look_back, 1) out, _ = self.lstm1(x, (h0, c0)) out, _ = self.lstm2(out, (h0, c0)) out = self.fc(out[:, -1, :]) return out
时间: 2023-11-25 20:07:55 浏览: 323
pytorch:torch.mm()和torch.matmul()的使用
从你提供的代码来看,问题依旧出现在 `to()` 方法的调用上。为了解决这个问题,需要确保 `device` 变量在 `forward()` 方法中得以定义,并且能够正确地传递给 `to()` 方法。
一种简单的解决方法是将 `device` 作为 `forward()` 方法的参数传递进来,例如:
```
def forward(self, x, device):
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
x = x.view(-1, self.look_back, 1)
out, _ = self.lstm1(x, (h0, c0))
out, _ = self.lstm2(out, (h0, c0))
out = self.fc(out[:, -1, :])
return out
```
这样,在调用 `forward()` 方法时,可以将 `device` 变量传递进去,例如:
```
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = MyModel(...)
x = torch.randn(10, 5, 1)
y_pred = model.forward(x, device=device)
```
这样就可以避免 `'int' object is not callable` 的错误了。
阅读全文