PyTorch torch.atleast_2d function
PyTorch torch reference manual
torch.atleast_2dis a function in PyTorch used to convert input tensors to at least 2 dimensions. If the input has fewer than 2 dimensions, it automatically adds dimensions to make it 2-dimensional.
Function definition
torch.atleast_2d(*tensors)
Usage example
]) Shape: torch.Size([1, 1])
import torch
# Convert scalar to 2-dimensional tensor
x = torch.atleast_2d(5)
print("After scalar conversion:", x, "Shape:", x.shape)
# Output: After scalar conversion: tensor([
# Convert 1-dimensional tensor to 2 dimensions
x = torch.tensor([1, 2, 3])
y = torch.atleast_2d(x)
print("1D to 2D:", y, "Shape:", y.shape)
# Output: 1D to 2D: tensor([[1, 2, 3]]) Shape: torch.Size([1, 3])
# A tensor that is already 2-dimensional remains unchanged
x = torch.tensor([[1, 2], [3, 4]])
y = torch.atleast_2d(x)
print("2D tensor:", y, "Shape:", y.shape)
# Convert scalar to 2-dimensional tensor
x = torch.atleast_2d(5)
print("After scalar conversion:", x, "Shape:", x.shape)
# Output: After scalar conversion: tensor([
# Convert 1-dimensional tensor to 2 dimensions
x = torch.tensor([1, 2, 3])
y = torch.atleast_2d(x)
print("1D to 2D:", y, "Shape:", y.shape)
# Output: 1D to 2D: tensor([[1, 2, 3]]) Shape: torch.Size([1, 3])
# A tensor that is already 2-dimensional remains unchanged
x = torch.tensor([[1, 2], [3, 4]])
y = torch.atleast_2d(x)
print("2D tensor:", y, "Shape:", y.shape)
Other extensions