Tensor To Float: Convert a PyTorch Tensor To A Floating Number Data Type

PyTorch Tensor To Float: Convert a PyTorch Tensor To A Floating Number Data Type

PyTorch Tensor To Float: Convert a PyTorch Tensor To A Floating Number Data Type

Video Transcript


This video will show you how to convert a PyTorch Tensor To Float Tensor.


First, we import PyTorch.

import torch


Then we check the PyTorch version we are using

print(torch.__version__)

We are using PyTorch version 2.0.0


Next, let's create a PyTorch Tensor full of integers numbers:

x_int = torch.tensor([1, 2, 3])


To confirm that it's a PyTorch integer tensor, let's use the PyTorch dtype method to check the tensor's data type attribute

x_int.dtype

We can see that it's "torch.int64" which is a 64-bit integer that is signed.


Great, now let's convert the Tensor to Float.


We convert the tensor to a Float tensor using the PyTorch float() method.

x_float = x.float()


Now that the tensor has been converted to a floating point tensor, let's double check the new tensor's data type to make sure it's a float tensor

x_float.dtype


We can see that the data type is now a "torch.float32" 32-bit floating point.


Lastly, let's print the tensor to visually check it out

print(x_float)

We can see a decimal point whereas before we couldn't see the decimal point.


Perfect!

We were able to use PyTorch's float() method to convert a PyTorch Tensor to a Float tensor.

Receive the Data Science Weekly Newsletter every Thursday

Easy to unsubscribe at any time. Your e-mail address is safe.