How to solve the runtime error - "RuntimeError: expected scalar type Long but found Float?"

After trying out several workaround to this problem , I am still stuck with this error message. I have a very basic Neural network called “Neuralnetwork”.

class Neuralnetwork(nn.Module):

    def __init__(self, in_features):

        super().__init__()

        self.disc = nn.Sequential(

            nn.Linear(in_features, 4), #change it to 4 neurons

            nn.LeakyReLU(0.01),

            nn.Linear(4, 1),

            nn.Sigmoid(),

        )

    def forward(self, x):

        return self.disc(x)

I have few samples to feed into the neural network. The samples are defined as follow -

samples = [torch.tensor([1,0,0,1],dtype=torch.long),

          torch.tensor([0.9,0.1,0.2,0.8],dtype=torch.long),

          torch.tensor([0.9,0.2,0.1,0.8],dtype=torch.long),

          torch.tensor([0.8,0.1,0.2,0.9],dtype=torch.long),

          torch.tensor([0.8,0.2,0.1,0.9],dtype=torch.long)]

So when I train the neural network with each of the sample fromt he samples, I get the error -

image_dim=4
disc=Neuralnetwork(image_dim)
criterion=nn.BCELoss()

for epoch in range(epochs):
     for sample in samples:
           disc_train=disc(sample)  ##This line is generating the error "RuntimeError: expected scalar type Long but found Float"

In order to look for a solution I have also taken the following measure but no luck -

sample= sample.type(torch.LongTensor)
disc_train=disc(sample)

Your model expects a floating point input (a few layers are exceptions such as e.g. nn.Embedding which expects integer types) so transform your input to a FloatTensor via:

out = disc(sample.to(torch.float32))
1 Like