如何将张量数组传递给 PyTorch 中的 criterion/loss 函数?
How do I pass an array of tensors into the criterion/loss function in PyTorch?
我的损失函数报错:
self.loss_fn = nn.MSELoss()
#### -- Snip ####
loss = self.loss_fn(predictions, targets) # Error here: 'list' object has no attribute 'size'
loss.backward()
我的预测是张量数组,如下所示:
predictions = []
for _ in range(100):
prediction = MyNeuralNet(inputs)
predictions.append(prediction)
如何在不出现上述错误的情况下将张量数组传递到我的损失准则函数中?
通过使用 torch.stack
我可以解决我的问题:
predictions = torch.stack(predictions)
loss = self.loss_fn(predictions, targets)
我的损失函数报错:
self.loss_fn = nn.MSELoss()
#### -- Snip ####
loss = self.loss_fn(predictions, targets) # Error here: 'list' object has no attribute 'size'
loss.backward()
我的预测是张量数组,如下所示:
predictions = []
for _ in range(100):
prediction = MyNeuralNet(inputs)
predictions.append(prediction)
如何在不出现上述错误的情况下将张量数组传递到我的损失准则函数中?
通过使用 torch.stack
我可以解决我的问题:
predictions = torch.stack(predictions)
loss = self.loss_fn(predictions, targets)