| by Arround The Web | No comments

How to Perform Tensor Conversions Using PyTorch?

Tensors are multidimensional arrays that store and represent data of different types and shapes. They can have different data types, such as Boolean, half, double, short, and long, etc. PyTorch enables users to easily convert any tensor into a different data type, such as integer, float, or Boolean. This blog will illustrate the method to perform tensor conversions using PyTorch.

How to Perform Tensor Conversions Using PyTorch?

To perform tensor conversions using PyTorch, follow the provided step-by-step instructions:

Step 1: Import PyTorch Library

First, import the “torch” library:

import torch

 

Step 2: Create and Print Tensor

Then, create a desired tensor and print it. Here, we are creating a tensor “tens” from the list using the “torch.tensor()” function:

tens = torch.tensor([5, 3, 0, 1])
print(tens)

 
According to the below output the tensor has been created from the list:


Step 3: Perform Tensor Conversion

Now, perform the tensor conversions which include the different data types such as Boolean, half, double,  short, long, etc.

Look at the following examples to see how to convert the tensor into different data types:

Example 1: Tensor Conversion into Boolean Data Type

In this example, we will convert the above-created tensor into Boolean data type:

print(tens.bool())

 
The below output shows that the “tens” tensor’s elements have been converted into Boolean values:

Example 2: Tensor Conversion into Integer Type Values

In this example, we will convert the “tens” tensor into the integer type values:

print(tens.short())
print(tens.long())

 
Here, “short” is for the “int16” data type, and “long” is for the “int64” data type.

It can be seen that the tensor’s elements have been successfully converted into the “int16” and “int64” data types:

Example 3: Tensor Conversion into Float Type Values

In this example, we will convert the “tens” tensor into the float type values:

print(tens.half())
print(tens.double())

 
Here, “half” is for the “float16” data type, and “double” is for the “float64” data type.

The below output indicates that the tensor’s elements have been successfully converted into the “float16” and “float64” data types:


We have efficiently explained the method of applying tensor conversions using PyTorch.

Note: You can access our Google Colab Notebook at this link.

Conclusion

To perform a tensor conversion in PyTorch, first, import the “torch” library and create a desired tensor. Then, use the “bool()”, “short()”, “long()”, “half()”, and “double()” functions to convert the created tensor into Boolean, integer, and floating data types. This blog has illustrated the method to perform tensor conversions using PyTorch.

Share Button

Source: linuxhint.com

Leave a Reply