torch.Tensor.Tensor.squeeze
Tensor.squeeze(): Tensor<DynamicShape, D, Dev>Tensor.squeeze(dimOrOptions?: number | SqueezeOptions, options?: SqueezeOptions): Tensor<DynamicShape, D, Dev>Remove dimensions of size 1 from the tensor.
Removes all dimensions with size 1 (if no dimension specified) or a specific dimension if it has size 1. Useful for removing batch dimensions, channel dimensions, etc. that are not needed. Returns original tensor if specified dimension is not size 1.
Common use cases:
- Remove batch dimension: (1, 64, 64) -> (64, 64)
- Remove singleton dimensions after reduction
- Shape compatibility for operations
- Adapting shapes from different sources
- Safe operation: If specified dimension is not size 1, returns tensor unchanged.
- Broadcasting: Often used after operations that add dimensions.
Returns
Tensor<DynamicShape, D, Dev>– Tensor with dimension(s) removed, same dataExamples
// Remove all singleton dimensions
const x = torch.zeros(1, 3, 1, 4);
const squeezed = x.squeeze(); // Shape [3, 4]
// Remove specific dimension
const y = torch.zeros(1, 3, 4);
const y_squeezed = y.squeeze(0); // Shape [3, 4]
// Squeeze after reduction
const batch = torch.randn(32, 64, 64, 64);
const reduced = batch.sum(1); // Shape [32, 1, 64, 64]
const final = reduced.squeeze(1); // Shape [32, 64, 64]
// Removing batch dimension from single sample prediction
const output = model(input); // Shape [1, num_classes]
const squeezed = output.squeeze(0); // Shape [num_classes]See Also
- PyTorch tensor.squeeze()
- unsqueeze - Opposite: adds size-1 dimensions
- reshape - More general shape transformation