PyTorch torch.dsplit() Method

PyTorch torch.dsplit() method is “used to split the input, a tensor with three or more dimensions, into multiple tensors depthwise according to indices_or_sections.” Each split is a view of input.

Syntax

torch.dsplit(input, indices_or_sections)

Parameters

  1. input (Tensor): The input tensor to be split. It should have at least 3 dimensions.
  2. split_size_or_sections (int or list): Size of each chunk or section to divide. If it’s an integer, the input tensor will be divided into equally sized chunks (if possible). If it’s a list, it specifies the number of chunks of each size.

Example 1: Splitting a 3D tensor into equally sized chunks

import torch

tensor_1 = torch.rand((2, 2, 6)) # A 3D tensor
chunks_1 = torch.dsplit(tensor_1, 3)

print("Original Tensor Shape:")
print(tensor_1.shape)
print("\nShapes of Chunks:")
for c in chunks_1:
  print(c.shape)

Output

Original Tensor Shape:
torch.Size([2, 2, 6])

Shapes of Chunks:
torch.Size([2, 2, 2])
torch.Size([2, 2, 2])
torch.Size([2, 2, 2])

Example 2: Splitting using a list to define chunk sizes

import torch

tensor_2 = torch.rand((2, 2, 8))
chunks_2 = torch.dsplit(tensor_2, [3, 5])

print("Original Tensor Shape:")
print(tensor_2.shape)
print("\nShapes of Chunks:")
for c in chunks_2:
  print(c.shape)

Output

Original Tensor Shape:
torch.Size([2, 2, 8])

Shapes of Chunks:
torch.Size([2, 2, 3])
torch.Size([2, 2, 2])
torch.Size([2, 2, 3])

Example 3: Working with a larger 3D tensor

import torch

tensor_3 = torch.rand((4, 4, 10))
chunks_3 = torch.dsplit(tensor_3, 5)

print("Original Tensor Shape:")
print(tensor_3.shape)
print("\nShapes of Chunks:")
for c in chunks_3:
  print(c.shape)

Output

Original Tensor Shape:
torch.Size([4, 4, 10])

Shapes of Chunks:
torch.Size([4, 4, 2])
torch.Size([4, 4, 2])
torch.Size([4, 4, 2])
torch.Size([4, 4, 2])
torch.Size([4, 4, 2])

That’s it!

Related posts

torch.chunk()

torch.split()

torch.cat()

Leave a Comment