PyTorch torch.atleast_3d function
PyTorch torch reference manual
torch.atleast_3d is a function in PyTorch used to convert an input tensor to at least 3 dimensions. If the input has fewer than 3 dimensions, dimensions are automatically added to make it 3D.
Function definition
torch.atleast_3d(*tensors)
Usage examples
Example
import
torch
Convert a scalar to a 3D tensor
x
=
torch.
atleast_3d
(
5
)
(
"After scalar conversion:"
,
x
,
"Shape:"
,
x.
shape
)
Output: After scalar conversion: tensor([[[5]]]) shape: torch.Size([1, 1, 1])
Convert a 1D tensor to 3D
x
=
torch.
tensor
(
[
1
,
2
,
3
]
)
y
=
torch.
atleast_3d
(
x
)
(
"1D to 3D:"
,
y
,
"Shape:"
,
y.
shape
)
Output: 1D to 3D: tensor([[[1], [2], [3]]]) shape: torch.Size([3, 1, 1])
Convert a 2D tensor to 3D
x
=
torch.
tensor
(
[
[
1
,
2
]
,
[
3
,
4
]
]
)
y
=
torch.
atleast_3d
(
x
)
(
"2D to 3D:"
,
y
,
"Shape:"
,
y.
shape
)
Output: 2D to 3D: tensor([[[1, 2], [3, 4]]]) shape: torch.Size([1, 2, 2])
A tensor that is already 3D remains unchanged
x
=
torch.
tensor
(
[
[
[
1
,
2
]
,
[
3
,
4
]
]
]
)
y
=
torch.
atleast_3d
(
x
)
(
"3D tensor:"
,
y
,
"Shape:"
,
y.
shape
)