如何将张量数组传递到 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)