torch.Tensor.Tensor.expand_as
Expand this tensor's shape to match another tensor's shape.
Broadcasts this tensor to have the same shape as another tensor. Useful for automatic shape alignment in operations without explicitly specifying the target shape. Non-destructive operation that creates a view with the same underlying data.
Common use cases:
- Broadcasting to match another tensor automatically
- Generic functions that need shape matching
- Preparing tensors for element-wise operations
- Template-based shape expansion
- Layer forward passes where output shape matches input
- Non-destructive: Creates a view; doesn't copy data.
- Memory efficient: Expanded tensor shares storage with original.
- Broadcasting rules: Follows NumPy broadcasting rules (right-align dimensions).
- View semantics: Modifications don't affect original due to read-only semantics.
Parameters
otherTensor<O>- Template tensor whose shape to match
Returns
Tensor<O, D, Dev>– Expanded tensor with shape matching other, same dtype and deviceExamples
// Expand to match another tensor's shape
const base = torch.tensor([1, 2, 3]); // Shape [3]
const target = torch.zeros([2, 3]); // Shape [2, 3]
const expanded = base.expand_as(target);
console.log(expanded.shape); // [2, 3]
// Result: [[1, 2, 3], [1, 2, 3]]
// Broadcasting for operations
const x = torch.randn([32, 1]);
const y = torch.randn([1, 64]);
const y_expanded = y.expand_as(torch.zeros([32, 64]));
// Generic broadcasting function
function broadcast_to_shape(x, template) {
return x.expand_as(template);
}
// Expand scalar to tensor shape
const scalar = torch.tensor(5.0); // Shape []
const expanded = scalar.expand_as(torch.zeros([3, 4])); // Shape [3, 4]See Also
- PyTorch tensor.expand_as()
- expand - Expand to explicit shape
- broadcast_to - Broadcast to specified shape
- reshape - Reshape to new shape (different semantics)