pytorch

How to Access Elements in a 3D Tensor in PyTorch?

PyTorch is a free-to-use deep learning library that enables users to work with tensors. Tensors are the essential data structure in PyTorch that can have N-dimensional data. The 3D tensor represents data in three dimensions i.e., rows, columns, and depth. Sometimes, users may want to access elements in a 3D tensor. In this situation, PyTorch permits them to perform this operation.

This blog will illustrate the method to access elements in desired 3D tensor in PyTorch.

How to Access/Retrieve Specific Elements in 3D Tensor in PyTorch?

To get particular elements in a desired 3D tensor in PyTorch, follow the below-listed steps:

Step 1: Import PyTorch Library

First, import the “torch” library to create tensors and access its elements:

import torch

Step 2: Create 3D Tensor

Then, create a desired 3D tensor and print its elements. Here, we are creating the following “Tens” tensor using the “torch.tensor()” function:

Tens = torch.tensor([[[2, 4, 6, 8], [10, 12, 14, 16], [18, 20, 22, 24]],
                     [[1, 3, 5, 7], [9, 11, 13, 15], [17, 19, 21, 23]]])

print(Tens)

This has created a 3D tensor as seen below:

Step 3: Access Tensor Element

Now, access the specific element of the above-created 3D tensor by specifying the desired row, column, and depth. For instance, we are accessing the element of the 3D tensor at the first row, second column, and two depths:

Tens_element = Tens[1, 2, 2]

Step 4: Display Accessed Element

Finally, display the accessed element of the 3D tensor:

print(Tens_element)

The below screenshot displays the accessed element of the specified position i.e., “21”:

Moreover, users can also extract the sub-tensor at a particular position. For instance, we are extracting the sub-tensor starting at zero row, first column, and one depth as seen below:

Tens_elem = Tens[:, 1:, 1:]

print(Tens_elem)

This has extracted the sub-tensor successfully:

We have explained the efficient way to access the elements in a 3D tensor in PyTorch.

Note: The link to our Google Colab Notebook is accessible right here.

Conclusion

To access certain elements in a specific 3D tensor in PyTorch, first, import the “torch” library. Then, create the desired 3D tensor and view its elements. Next, access the specific element of the 3D tensor by specifying the desired row, column, and depth. Lastly, display the accessed elements. This blog has illustrated the method to access elements in a 3D tensor in PyTorch.

About the author

Laiba Younas

I have done bachelors in Computer Science. Being passionate about learning new technologies, I am interested in exploring different programming languages and sharing my experience with the world.