PyTorch torch.atleast_1d function
PyTorch torch reference manual
torch.atleast_1d is a function in PyTorch used to convert an input tensor to at least 1 dimension. If the input is already at least 1D, a view of the original tensor is returned; otherwise a new dimension is added.
Function definition
torch.atleast_1d(*tensors)
Usage examples
Example
import
torch
Convert a scalar to a 1D tensor
x
=
torch.
atleast_1d
(
5
)
(
"After scalar conversion:"
,
x
,
"Shape:"
,
x.
shape
)
A tensor that is already 1D
x
=
torch.
tensor
(
[
1
,
2
,
3
]
)
y
=
torch.
atleast_1d
(
x
)
(
"1D tensor:"
,
y
,
"Shape:"
,
y.
shape
)
A 2D tensor remains unchanged
x
=
torch.
tensor
(
[
[
1
,
2
]
,
[
3
,
4
]
]
)
y
=
torch.
atleast_1d
(
x
)
(
"2D tensor:"
,
y
,
"Shape:"
,
y.
shape
)
Multiple inputs
a
=
1
b
=
torch.
tensor
(
[
2
,
3
]
)
c
=
torch.
tensor
(
[
[
4
,
5
]
]
)
result
=
torch.
atleast_1d
(
a
,
b
,
c
)
for
i
,
t
in
enumerate
(
result
)
:
(
f
"Input {i} shape: {t.shape}"
)