Skip to content

[Solved][PyTorch] RuntimeError: Expected object of scalar type Float but got scalar type Long for argument

I think if we use Pytorch framework to train a model, the commonly error messages are “Model mismatch” and the following error:

RuntimeError: Expected object of scalar type Float but got scalar type Long for argument

This error messages have many types, for example maybe it expected to receive the “Long” type but got “Float” type.

The solution is very clearly. We just need two steps:

  1. Check the position where the error occur, maybe in loss function or model you build
  2. Convert the data type to be the correct type.

Let’s take a look for a loss function:

# Loss
def loss_function(inputs, targets):
    return nn.BCELoss()(inputs, targets)



If my targets is “Long” data type, it will get an error message: Because the nn.BCELoss() need to input the “Float” data type.

To avoid this problem, I can use “float()” to convert my data:

# Loss
def loss_function(inputs, targets):
    return nn.BCELoss()(inputs, targets.float())



And then we can execute our training, it will running good.

Leave a Reply