Add a batch dimension
A model expects a batch axis but one sample lacks it.
PyTorch · Function
Adds a size-one dimension to a tensor at a chosen position. The returned tensor shares the input's underlying data.
torch.unsqueeze returns a tensor view with one size-one dimension inserted at the requested position. The input values remain available through shared underlying storage, and negative positions are interpreted relative to the resulting rank.
torch.unsqueeze(input, dim)| Name | Type | Description |
|---|---|---|
input | Tensor | The tensor whose shape receives an added singleton dimension. |
dim | int | The integer position at which to insert the singleton dimension. |
A new Tensor with one dimension of size one inserted; it shares the input tensor's underlying data.
import torch
x = torch.tensor([1, 2, 3, 4])
y = torch.unsqueeze(x, 1)
assert y.shape == (4, 1)
assert torch.equal(y[:, 0], x)
print(y)Adds a singleton dimension at index 1, converting the four-element vector into a column-shaped tensor.
A model expects a batch axis but one sample lacks it.
A vector must align as a row or column in broadcasting or matrix operations.
A scalar or lower-rank tensor needs an explicit axis before concatenation or stacking.
It inserts a dimension whose size is one at the position specified by dim. For example, inserting at position 1 changes a one-dimensional tensor of length four into shape (4, 1).
Follow-up: What happens to the tensor's data? The result shares the same underlying data as the input, so this operation changes the view's shape rather than copying values.
input is the tensor to reshape conceptually, and dim is the integer index where the singleton dimension is inserted. The function returns a Tensor.
Follow-up: How are negative indices handled? PyTorch maps a negative dim by adding input.dim() + 1.
For an input with rank n, dim may range from -n - 1 through n inclusive, expressed as the half-open interval [-n - 1, n + 1). A valid insertion therefore produces a tensor with rank n + 1.
Follow-up: Why is the upper endpoint exclusive? The documented interval notation permits n but excludes n + 1, which is beyond the available insertion positions.
torch.Tensor.unsqueezetorch.Tensor.unsqueeze_torch.squeeze