0

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?

Dylan Kerler
  • 2,007
  • 1
  • 8
  • 23
  • This error should be impossible, according to what you've shown. (`MSELoss` returns a tensor, not a list.) Please provide enough code to reproduce the issue—a [mre]. – Arya McCarthy Feb 28 '21 at 16:50
  • Ah yeh the comment was on the wrong line. Probably could have inferred that from context but oh well. – Dylan Kerler Feb 28 '21 at 16:56
  • Now that you've edited the question, it is a duplicate of [this one](https://stackoverflow.com/q/59043534/7802200). – Arya McCarthy Feb 28 '21 at 17:13

1 Answers1

0

By using torch.stack I could fix my issue:

predictions = torch.stack(predictions)
loss = self.loss_fn(predictions, targets)
Dylan Kerler
  • 2,007
  • 1
  • 8
  • 23