torch.atleast_1d
function atleast_1d(input: Tensor): voidReturns a tensor with at least 1 dimension.
Ensures input tensors have at least 1 dimension. Useful for:
- API compatibility: Functions that expect at least 1D input
- Safe broadcasting: Guaranteeing minimum dimensionality before operations
- Data loading: Converting scalar values to tensor form
- Uniform tensor handling: Normalizing mixed input types (scalars and tensors)
If the input is already 1D or higher, it's returned unchanged. Only 0D (scalar)
tensors are reshaped to shape [1].
- Zero-copy when possible: If input is already 1D or higher, the same tensor object is returned with no reshape operation. Only 0D tensors require a reshape.
- Data preservation: The reshape only adds dimensions, no data is lost or moved. A 0D scalar
5becomes a 1D tensor[5]with the same value. - Broadcasting implications: After atleast_1d, you can safely use broadcasting operations that require at least 1D tensors without shape errors.
- Tensor identity: For non-0D inputs, the original tensor is returned unchanged. For 0D inputs, a new reshaped tensor is created.
Shape change only for 0D: This function only modifies 0D scalars. Tensors with 1 or more dimensions are always returned exactly as-is.
Parameters
inputTensor- The input tensor (any dimensions, including 0D scalars)
Returns
Tensor with shape [1] if input is 0D, otherwise unchanged
Examples
// Scalar (0D) tensor becomes 1D
const scalar = torch.tensor(5);
torch.atleast_1d(scalar); // Shape [1], value [5]
// 1D tensor unchanged
const vec = torch.tensor([1, 2, 3]);
torch.atleast_1d(vec); // Shape [3], unchanged
// 2D tensor unchanged
const matrix = torch.tensor([[1, 2], [3, 4]]);
torch.atleast_1d(matrix); // Shape [2, 2], unchanged// Normalizing mixed input (useful in library functions)
function processInput(value: Tensor | number): Tensor {
const t = typeof value === 'number' ? torch.tensor(value) : value;
const normalized = torch.atleast_1d(t);
// Now guaranteed to be at least 1D for safe operations
return torch.mean(normalized);
}// Preparing scalars for batching
const loss1 = torch.tensor(0.5);
const loss2 = torch.tensor(0.3);
const loss3 = torch.tensor(0.7);
// Convert to 1D for concatenation
const losses = torch.stack([
torch.atleast_1d(loss1),
torch.atleast_1d(loss2),
torch.atleast_1d(loss3)
], 0); // Shape [3, 1]See Also
- PyTorch torch.atleast_1d()
- atleast_2d - Ensure at least 2 dimensions
- atleast_3d - Ensure at least 3 dimensions
- unsqueeze - Add a specific dimension
- reshape - Arbitrary shape transformation