Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert torch int64 to torch LongTensor?

Tags:

python

pytorch

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'
like image 326
David Alford Avatar asked Jun 08 '19 21:06

David Alford


People also ask

How do you convert a float to a double Tensor?

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().


1 Answers

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'

like image 163
David Alford Avatar answered Sep 28 '22 00:09

David Alford