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 library import torch # create torch tensors tens_1 = torch.tensor([ 1. , 2. , 3. , 4. , 5. ]) # display tensors print ( "\n First Tensor - " , tens_1) # check this tensor is contiguous or not output_1 = tens_1.is_contiguous() # display output 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 library import torch # define a torch tensor tens = torch.tensor([[ 10. , 20. , 30. ], [ 40. , 50. , 60. ]]) # transpose of the above defined tensor tens_transpose = tens.transpose( 0 , 1 ) # display tensors print ( "\n Original Tensor \n" , tens) print ( "\n Transpose of original Tensor \n" , tens_transpose) # check if a tensor and it's transpose are # contiguous or not 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: