user3668129
user3668129

Reputation: 4810

Why I'm getting error: "Boolean value of Tensor with more than one value is ambiguous"

I'm trying to run the following code:

l = torch.tensor([0, 1, 1, 1], requires_grad=False)
r = torch.rand(4, 2)

torch.nn.CrossEntropyLoss(r, l)

And I'm getting error:

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

I looked here: Bool value of Tensor with more than one value is ambiguous in Pytorch but didn't understand the answers.

What do I need to change in order to run the code ?

Upvotes: 2

Views: 5805

Answers (1)

Ivan
Ivan

Reputation: 40628

The object you are manipulating, torch.nn.CrossEntropyLoss, is a PyTorch module class, not a function.

Therefore, you should either intialize it beforehand:

>>> ce_loss = nn.CrossEntropyLoss()
>>> cel_loss(r, l)

Or use the functional interface, i.e. torch.nn.functional.cross_entropy:

>>> F.cross_entropy(r, l)

Upvotes: 5

Related Questions