The Tensor.type(dtype=None) function has the ability to cast the tensor to the given dtype as a parameter. If dtype parameter is not provided, it just returns the dtype of the tensor. So, the difference is the added functionality of casting.
Also, If the casting is performed to a new type, then the function returns a copy of the tensor.
Answer from Vishnudev Krishnadas on Stack OverflowThere are three kinds of things:
dtype || CPU tensor || GPU tensor
torch.float32 torch.FloatTensor torch.cuda.FloatTensor
The first one you get with print(t.dtype) if t is your tensor, else you use t.type() for the other two.
Use the dtype attribute:
>>> import torch
>>> print(torch.Tensor(1).dtype)
torch.float32
The documentation also gives the canonical list of datatypes.
y = y.long() does the job. There are similar methods for other data types, such as int, char, float and byte.
You can check different dtypes here.
use .to method of torch as follows:
y = y.to(torch.long)
More details about torch tensor type/ops can be found here
https://pytorch.org/docs/stable/tensors.html
As pointed out by jasonharper, you can use torch.is_floating_point to check your tensor:
if torch.is_floating_point(my_tensor):
# the tensor is "normalized"...
else:
# the tensor is an integer and needs to be normalized...
As mentioned by other answers and comments, torch.is_floating_point will cover most situations.
However, do note that torch.is_floating_point will return False for complex dtypes, which are not integers. It seems that, as of now, PyTorch is missing a torch.is_integer check.
As a workaround to cover more cases than just int VS float, one may consider using the following condition:
not torch.is_floating_point(my_tensor) and not torch.is_complex(my_tensor)