How to check if a tensor is contiguous or not in PyTorch
Last Updated :
21 Apr, 2022
In this article, we are going to see how to check if a tensor is contiguous or not in PyTorch.
A contiguous tensor could be a tensor whose components are stored in a contiguous order without having any empty space between them. We can check if a tensor is contiguous or not by using the Tensor.is_contiguous() method.
Tensor.is_contiguous() method
This method helps us to identify whether a tensor is contiguous or not. This method returns True if a tensor is contiguous else it will return False. Use the below syntax to understand how to check if a tensor is contiguous or not in PyTorch.
Syntax – Tensor.is_contiguous()
Example 1:
In the following program, we are going to check whether a tensor is contiguous or not.
Python3
import torch
tens_1 = torch.tensor([ 1. , 2. , 3. , 4. , 5. ])
print ( "\n First Tensor - " , tens_1)
output_1 = tens_1.is_contiguous()
print ( "\n This tensor is contiguous - " , output_1)
|
Output:
Example 2:
In the following program, we are going to see transpose of a tensor is contiguous or not.
Python3
import torch
tens = torch.tensor([[ 10. , 20. , 30. ],
[ 40. , 50. , 60. ]])
tens_transpose = tens.transpose( 0 , 1 )
print ( "\n Original Tensor \n" , tens)
print ( "\n Transpose of original Tensor \n" ,
tens_transpose)
Output_1 = tens.is_contiguous()
print ( "\n Original Tensor is contiguous - " , Output_1)
Output_2 = tens_transpose.is_contiguous()
print ( "\n Transpose of original Tensor is contiguous - " , Output_2)
|
Output:
Share your thoughts in the comments
Please Login to comment...