Pytorch Torch Dstack
# PyTorch torch.dstack Function
* * Pytorch torch Reference Manual](#)
`torch.dstack` is a function in PyTorch used to stack tensors in depth (along the third dimension).
### Function Definition
torch.dstack(tensors, *, out=None)
* * *
## Usage Examples
## Example
import torch
# 2D Tensor Depth Stacking
x1 = torch.tensor([[1,2],[3,4]])
x2 = torch.tensor([[5,6],[7,8]])
result = torch.dstack([x1, x2])
print("2D Tensor Depth Stacking:")
print(f" x1:n{x1}")
print(f" x2:n{x2}")
print(f" dstack:n{result}")
# 3D Tensor Depth Stacking
y1 = torch.tensor([[[1,2],[3,4]],[[5,6],[7,8]]])
y2 = torch.tensor([[[9,10],[11,12]],[[13,14],[15,16]]])
result = torch.dstack([y1, y2])
print("n3D Tensor Depth Stacking:")
print(f" y1:n{y1}")
print(f" y2:n{y2}")
print(f" dstack:n{result}")
print(f" dstack Shape: {result.shape}")
# 1D Tensor Depth Stacking
z1 = torch.tensor([1,2,3])
z2 = torch.tensor([4,5,6])
result = torch.dstack([z1, z2])
print("n1D Tensor Depth Stacking:")
print(f" z1: {z1}")
print(f" z2: {z2}")
print(f" dstack:n{result}")
The output result is:
2D tensor deep stacking: x1: tensor([[1, 2], [3, 4]]) x2: tensor([[5, 6], [7, 8]]) dstack: tensor([[[ 1, 5], [ 2, 6]], [[ 3, 7], [ 4, 8]]])3D tensor deep stacking: y1: tensor([[[ 1, 2], [ 3, 4]], [[ 5, 6], [ 7, 8]]]) y2: tensor([[[ 9, 10], [11, 12]], [[13, 14], [15, 16]]]) dstack: tensor([[[ 1, 2, 9, 10], [ 3, 4, 11, 12]], [[ 5, 6, 13, 14], [ 7, 8, 15, 16]]]) dstack shape: torch.Size([2, 2, 4])1D tensor deep stacking: z1: tensor([1, 2, 3]) z2: tensor([4, 5, 6]) dstack: tensor([[1, 4], [2, 5], [3, 6]])
* * Pytorch torch Reference Manual](#)
YouTip