I have a 3D tensor in PyTorch. I think of it as an array of 2D matrices. How can i index…
- User
I have a 3D tensor in PyTorch. I think of it as an array of 2D matrices. How can i index this tensor to get the first matrix?
- Assistant
In PyTorch, a 3D tensor can be thought of as a collection of 2D matrices. To index the first matrix of a 3D tensor, you can use simple indexing.
Assuming you have a tensor named
tensor_3d, you can access the first matrix (which is at index 0) like this:pythonimport torch # Example: create a 3D tensor tensor_3d = torch.randn(3, 4, 5) # A tensor with shape (3, 4, 5) # Access the first matrix (the first 2D array) first_matrix = tensor_3d[0] print(first_matrix)In the example above,
tensor_3d[0]retrieves the first 2D matrix from the 3D tensor. The shape offirst_matrixwould be(4, 5), corresponding to the second and third dimensions of the original tensor. - User
tell me more about indexing pytorch tensors
- Assistant