RuntimeError: expected scalar type Long but found Float with Custom Data

Hello, I am a beginner in PyTorch.
I am trying to learn by building a toy example with custom data. Here is my code:

import torch
import torch.nn as nn
import torch.optim as optim
for iter in range(10):
adam = optim.Adam(model.parameters(), lr=1e-1);
for epoch in range(10):
 print(f'Epoch {epoch}: training loss: {l}');

When I run this script this is the error I get:

Traceback (most recent call last):
  File "c", line 15, in <module>
  File "/home/samarth/.local/lib/python3.6/site-packages/torch/nn/modules/", line 1051, in _call_impl
    return forward_call(*input, **kwargs)
  File "/home/samarth/.local/lib/python3.6/site-packages/torch/nn/modules/", line 96, in forward
    return F.linear(input, self.weight, self.bias)
  File "/home/samarth/.local/lib/python3.6/site-packages/torch/nn/", line 1847, in linear
    return torch._C._nn.linear(input, weight, bias)
RuntimeError: expected scalar type Long but found Float

I have told PyTorch to convert the data into LongTensor multiple times, but it still won’t work.
Can anyone help me?
Thank you.

PyTorch assumes that the first argument to a method has the “right” dtype and thus claims that Long is expected in the model parameter.
However, you should use FloatTensors to train the model in order to be able to calculate gradients (which are defined for floating point types).
Transform the data and target thus via float() and this error should be resolved.

However, your code will still not be working, since nn.BCELoss expects the model output to be in [0, 1] so apply a sigmoid on the model output or use nn.BCEWithLogitsLoss instead, which also increases the numerical stability.

Also, loss.backward() won’t work and you should replace it with l.backward().

Thanks a lot. I will try this and get back to you.

Thank you for helping me. My code is working now.