PacktPublishing / Mastering-PyTorch

Mastering PyTorch, published by Packt
MIT License
253 stars 109 forks source link

Code error on chapter 4 #4

Closed ghost closed 2 years ago

ghost commented 3 years ago

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

JavierAbascal commented 3 years ago

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

thatgeeman commented 2 years ago

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.