How to Slice a 3D Tensor in Pytorch?
Last Updated :
18 Jul, 2021
In this article, we will discuss how to Slice a 3D Tensor in Pytorch.
Let’s create a 3D Tensor for demonstration. We can create a vector by using torch.tensor() function
Syntax: torch.tensor([value1,value2,.value n])
Code:
Python3
import torch
a = torch.tensor([[[1, 2, 3, 4, 5, 6, 7, 8],
[10, 11, 12, 13, 14, 15, 16, 17]],
[[71, 72, 73, 74, 75, 76, 77, 78],
[81, 82, 83, 84, 85, 86, 87, 88]]])
print(a)
|
Output:
tensor([[[ 1, 2, 3, 4, 5, 6, 7, 8],
[10, 11, 12, 13, 14, 15, 16, 17]],
[[71, 72, 73, 74, 75, 76, 77, 78],
[81, 82, 83, 84, 85, 86, 87, 88]]])
Slicing a 3D Tensor
Slicing: Slicing means selecting the elements present in the tensor by using “:” slice operator. We can slice the elements by using the index of that particular element.
Note: Indexing starts with 0
Syntax: tensor[tensor_position_start:tensor_position_end, tensor_dimension_start:tensor_dimension_end , tensor_value_start:tensor_value_end]
Parameters:
- tensor_position_start: Specifies the Tensor to start iterating
- tensor_position_end: Specifies the Tensor to stop iterating
- tensor_dimension_start: Specifies the Tensor to start the iteration of tensor in given positions
- tensor_dimension_stop: Specifies the Tensor to stop the iteration of tensor in given positions
- tensor_value_start: Specifies the start position of the tensor to iterate the elements given in dimensions
- tensor_value_stop: Specifies the end position of the tensor to iterate the elements given in dimensions
Example 1: Python code to access all the tensors of 1 dimension and get only 7 values in that dimension
Output:
tensor([[[1, 2, 3, 4, 5, 6, 7]]])
Example 2: Python code to access all the tensors of all dimensions and get only 3 values in each dimension
Output:
tensor([[[ 1, 2, 3],
[10, 11, 12]]])
Example 3: Access 8 elements in 1 dimension on all tensors
Output:
tensor([[10, 11, 12, 13, 14, 15, 16, 17],
[81, 82, 83, 84, 85, 86, 87, 88]])
Please Login to comment...