Nothing here
Nothing here

Reputation: 2373

How to convert torch int64 to torch LongTensor?

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'

Upvotes: 6

Views: 34065

Answers (1)

Nothing here
Nothing here

Reputation: 2373

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'

Upvotes: 9

Related Questions