Search code examples
machine-learningneural-networkpytorchgradient-descent

How do I pass an array of tensors into the criterion/loss function in PyTorch?


My loss function gives an error:

self.loss_fn = nn.MSELoss()

#### -- Snip ####

loss = self.loss_fn(predictions, targets) # Error here: 'list' object has no attribute 'size'
loss.backward()

My predictions are an array of tensors as follows:

predictions = []
for _ in range(100):
   prediction = MyNeuralNet(inputs)
   predictions.append(prediction)

How can I pass an array of tensors into my loss criterion function without getting the above error?


Solution

  • By using torch.stack I could fix my issue:

    predictions = torch.stack(predictions)
    loss = self.loss_fn(predictions, targets)