Tag Archives: Pytoch nn.CrossEntropyLoss Error

[Solved] Pytoch nn.CrossEntropyLoss Error: RuntimeError: expected scalar type Long but found Float

When I want to test, NN. Crossentropyloss() is an error, as follows:

>>> x = torch.rand(64, 4)
>>> y = torch.rand(64)
>>> criterion(x, y)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/rogn/opt/anaconda3/envs/deeplearning/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1051, in _call_impl
    return forward_call(*input, **kwargs)
  File "/Users/rogn/opt/anaconda3/envs/deeplearning/lib/python3.8/site-packages/torch/nn/modules/loss.py", line 1120, in forward
    return F.cross_entropy(input, target, weight=self.weight,
  File "/Users/rogn/opt/anaconda3/envs/deeplearning/lib/python3.8/site-packages/torch/nn/functional.py", line 2824, in cross_entropy
    return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
RuntimeError: expected scalar type Long but found Float

Reference resources: https://stackoverflow.com/questions/60440292/runtimeerror-expected-scalar-type-long-but-found-float

The reason is that the category target cannot be a floating-point type, but can only be an integer. For example, it belongs to a certain class

So, change the target to an integer

>>> x = torch.rand(64, 4)
>>> y = torch.randint(0,4, (64,))
>>> criterion(x, y)
tensor(1.4477)