Expected scalar type Long but found Float

Aakash, please help withis error am getting, I am completely new to machine learning
expected scalar type Long but found Float

I changed it to long , it then said expected float got long
what do I do or what am I doing wrong

I am not Aakash though but make sure both of your inputs are of the same type, especially if you are using Cross Entropy of any kind. That is in
F.binary_cross_entropy(x, y)
if your x is float y must be float.

1 Like

Hi Godwin, can you please share the code for the cell which is causing this issue?

Hi,
As mentioned in assignment 2, our pytorch dataset is of type float32. Now we defined class:
class InsuranceModel(nn.Module):

def __init__(self):

    super().__init__()

    self.linear = nn.Linear(input_size, output_size)            # fill this (hint: use input_size & output_size defined above)

    

def forward(self, xb):

    xb = xb.reshape(-1, input_size)                         # fill this

    out = self.linear(xb)

    return out



def training_step(self, batch):

    inputs, targets = batch 

    # Generate predictions

    out = self(inputs)          

    # Calcuate loss

    loss = F.cross_entropy(out, targets)                          # fill this

    return loss



def validation_step(self, batch):

    inputs, targets = batch

    # Generate predictions

    out = self(inputs)

    # Calculate loss

    loss = F.cross_entropy(out, targets)                             # fill this    

    return {'val_loss': loss.detach()}

    

def validation_epoch_end(self, outputs):

    batch_losses = [x['val_loss'] for x in outputs]

    epoch_loss = torch.stack(batch_losses).mean()   # Combine losses

    return {'val_loss': epoch_loss.item()}



def epoch_end(self, epoch, result, num_epochs):

    # Print result every 20th epoch

    if (epoch+1) % 20 == 0 or epoch == num_epochs-1:

        print("Epoch [{}], val_loss: {:.4f}".format(epoch+1, result['val_loss']))

Then we created a model object:
model = InsuranceModel()

Now we defined:
def evaluate(model, val_loader):

outputs = [model.validation_step(batch) for batch in val_loader]

return model.validation_epoch_end(outputs)

Here, If i try to do below:
result = evaluate(model, val_loader)
print(result)

We get error: expected scalar type Long but found Float

Hi,
I got the issue. Our output_size is incorrect. Instead of 1, it was 7 for me. But now, After fixing that, I am facing another error in exact same line.

“1D target tensor expected, multi-target not supported”