torch.Tensor.Tensor.unsqueeze
Tensor.unsqueeze<Dim extends number>(dim: Dim): Tensor<DynamicShape, D, Dev>Tensor.unsqueeze(dimOrOptions: number | UnsqueezeOptions, options?: UnsqueezeOptions): Tensor<DynamicShape, D, Dev>Insert a dimension of size 1 at the specified position.
Adds a new dimension with size 1 at the specified position. Useful for broadcasting, adding batch dimensions, or adapting shapes for operations that expect specific dimensions. Essential for working with variable-dimensional inputs.
Common use cases:
- Add batch dimension: (3, 4) -> (1, 3, 4)
- Add channel dimension: (64, 64) -> (64, 64, 1)
- Broadcasting tensors: ensure compatible dimensions
- Preparing single samples for batch processing
- Separating spatial and feature dimensions
- Negative indexing: Negative dim is converted to positive (ranges from 0 to rank).
- No data copy: Just changes shape metadata.
- Broadcasting: Used frequently with broadcasting to add matching dimensions.
Parameters
dimDim- Position where dimension should be inserted. Can be negative (counted from end). Valid range: [-rank-1, rank] where rank is current number of dimensions.
Returns
Tensor<DynamicShape, D, Dev>– Tensor with new dimension inserted at position dimExamples
// Add batch dimension
const x = torch.randn(3, 4); // Shape [3, 4]
const batched = x.unsqueeze(0); // Shape [1, 3, 4]
const batched2 = x.unsqueeze(2); // Shape [3, 4, 1]
// Add channel dimension
const grayscale = torch.randn(64, 64); // [H, W]
const with_channel = grayscale.unsqueeze(0); // [1, H, W] - 1 channel
const with_channel2 = grayscale.unsqueeze(2); // [H, W, 1] - different convention
// Broadcasting: add matching dimensions
const a = torch.randn(32, 1); // Shape [32, 1]
const b = torch.randn(1, 64); // Shape [1, 64]
const c = a.add(b); // Shape [32, 64] - broadcasts
// Negative indexing
const x = torch.randn(3, 4);
const x_unsqueezed = x.unsqueeze(-1); // Insert at end (position 2)
// Shape [3, 4, 1]
// Prepare single sample for batch processing
const single_image = torch.randn(3, 224, 224); // [C, H, W]
const batch_of_one = single_image.unsqueeze(0); // [1, C, H, W]
const output = model(batch_of_one); // Feed to model expecting batchesSee Also
- PyTorch tensor.unsqueeze()
- squeeze - Opposite: removes size-1 dimensions
- reshape - More general shape transformation
- expand - Expand dimensions beyond size-1