PacktPublishing/Mastering-PyTorch

Code error on chapter 4

Opened this issue · 2 comments

In the rnn.py file, while training there's an error that says the following :

RuntimeError: result type Float can't be cast to the desired output type Long

Please fix it, it'll be a great help
Thanks

Hi @introvertedbot , I will be taking a look at it tonight

Hello! I had a quick look at this. This arises from the loss function if your targets are of the wrong type. The loss_func expects targets of float type.

To reproduce your error:

m = nn.Sigmoid()
loss_func = nn.BCEWithLogitsLoss()
input = torch.randn(3, requires_grad=True)
target = torch.empty(3).random_(2).long()  # target casted as long
loss = loss_func(m(input), target)
loss.backward()

To fix the error, simply cast the targets to float here loss_func(preds, sentiment.float()) or when you make your target tensor.