RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'target' in call to _thnn_nll_loss2d_forward

hi. I got this error “RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 ‘target’ in call to _thnn_nll_loss2d_forward” when I executed the following code:
model = torchvision.models.resnet50(pretrained=False)
criterion=MSELoss().cuda()
train_loss = 0
for i_batch, sample_batched in enumerate(TraindataLoader):
local_X = sample_batched[‘input’].cuda()
local_Y = sample_batched[‘EEGResponse’].cuda()
can anbody tell me how to solve this problem?

    # compute the model output
    yhat = model(local_X)
    yhat= torch.reshape(yhat,[size_batches,1,17,100])
    # calculate loss
    loss = criterion(yhat, local_Y)
    train_loss += loss.item()
    losses.update(loss.item(), size_batches)
        
    # compute gradient and do SGD step
    optimizer.zero_grad()

        
    # credit assignment
    loss.backward()
    # update model weights
    optimizer.step()

Hi Nikiguo!

Somewhere in your code you are not actually using MSELoss
as your criterion (but rather, most likely, CrossEntropyLoss).

At this point print out type (criterion) before calling
loss = criterion(yhat, local_Y) to see what criterion
actually is.

Best.

K. Frank

Hi. Thank you for your suggestion. I printed the type of criterion and it is crossentropyloss. But I define it as MSELoss. Previously I used to defined it as CrossEntropyLoss but now I change it. It is weird. Could you please tell me how to fix this problem?