logo

Solving 'RuntimeError: Boolean value of Tensor with more than one value is ambiguous' Error in PyTorch 📂Machine Learning

Solving 'RuntimeError: Boolean value of Tensor with more than one value is ambiguous' Error in PyTorch

Error

When using the loss function nn.MESLoss(), the following error occurred.

RuntimeError                              Traceback (most recent call last)
<ipython-input-75-8c6e9ea829d4> in <module>
----> 1 nn.MSELoss(y_pred, y)

2 frames
/usr/local/lib/python3.8/dist-packages/torch/nn/_reduction.py in legacy_get_string(size_average, reduce, emit_warning)
     33         reduce = True
     34 
---> 35     if size_average and reduce:
     36         ret = 'mean'
     37     elif reduce:

RuntimeError: Boolean value of Tensor with more than one value is ambiguous

Solution1

The code can be fixed by changing it as follows.

nn.MSELoss(y_pred, y) $\to$ nn.MSELoss()(y_pred, y)

Environment

  • Colab
  • Version: Python 3.8.10, PyTorch1.13.1+cu116