gpt-4.1-2025-04-14· OpenAI
LMArena Human Preference 140K
""" import torch x = torch.tensor([[1.0, 2.0, 3.0]]) # shape (1, 3) n = 4 Broadcast to…
- User
""" import torch
x = torch.tensor([[1.0, 2.0, 3.0]]) # shape (1, 3) n = 4
Broadcast to (4, 3)
y = x.expand(n, -1) """ What does -1 mean in x.expand
- Assistant
Great question!
In PyTorch, when you use the
expand()method, the-1means "keep the size of this dimension the same as the original."So, in your code:
y = x.expand(n, -1)nsets the first dimension ton(so it becomes 4).-1tells PyTorch to keep the second dimension the same as inx(which is 3).
In summary:
-1is a placeholder that means "do not change this dimension's size."
Example:
If
x.shapeis(1, 3), then:x.expand(4, -1)→ shape(4, 3)x.expand(-1, 3)→ shape(1, 3)(no change)x.expand(2, 3)→ shape(2, 3)
Reference:
PyTorch docs: torch.Tensor.expandLet me know if you want more examples!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.