I am going through a course which uses a deprecated version of PyTorch which does not change torch.int64 to torch.LongTensor as needed. The current section of code which is throwing the error is:
loss = loss_fn(Ypred, Ytrain_) # calc loss on the prediction
I believe the dtype should be changed in thhis section though:
Ytrain_ = torch.from_numpy(y_train.values).view(1, -1)[0].
When testing the data-type by using Ytrain_.dtype it returns torch.int64. I have tried to convert it by applying the long() function as such: Ytrain_ = Ytrain_.long() to no avail.
I have also tried looking for it in the documentation but it seems that it says torch.int64 OR torch.long which I assume means torch.int64 should work.
RuntimeError Traceback (most recent call last)
----> 9 loss = loss_fn(Ypred, Ytrain_) # calc loss on the prediction
RuntimeError: Expected object of scalar type Long but got scalar type Int for argument #2 'target'
We can check the type of this variable by using the type functionality. We see that it is a FloatTensor. To convert this FloatTensor to a double, define the variable double_x = x. double().
As stated by user8426627 you want to change the tensor type, not the data type. Therefore the solution was to add .type(torch.LongTensor) to convert it to a LongTensor.
Final code:
Ytrain_ = torch.from_numpy(Y_train.values).view(1, -1)[0].type(torch.LongTensor)
Test tensor type:
Ytrain_.type()
'torch.LongTensor'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With