PyTorch torch.atleast_1d Function
PyTorch torch Reference Manual
torch.atleast_1dis a function in PyTorch used to convert input tensors to at least 1 dimension. If the input is already at least 1-dimensional, it returns a view of the original tensor; otherwise, it adds a new dimension.
Function Definition
torch.atleast_1d(*tensors)
Usage Example
Example
import torch
# Scalar converted to 1-D tensor
x = torch.atleast_1d(5)
print("After scalar conversion:", x, "Shape:", x.shape)
# Tensor already 1-D
x = torch.tensor([1, 2, 3])
y = torch.atleast_1d(x)
print("1-D tensor:", y, "Shape:", y.shape)
# 2-D tensor remains unchanged
x = torch.tensor([[1, 2], [3, 4]])
y = torch.atleast_1d(x)
print("2-D 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):
print(f"Input {i} shape: {t.shape}")
# Scalar converted to 1-D tensor
x = torch.atleast_1d(5)
print("After scalar conversion:", x, "Shape:", x.shape)
# Tensor already 1-D
x = torch.tensor([1, 2, 3])
y = torch.atleast_1d(x)
print("1-D tensor:", y, "Shape:", y.shape)
# 2-D tensor remains unchanged
x = torch.tensor([[1, 2], [3, 4]])
y = torch.atleast_1d(x)
print("2-D 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):
print(f"Input {i} shape: {t.shape}")
Other Extensions