
The expand function broadcasts a tensor to a new shape, but without duplicating its data.
tensor = torch.tensor([1, 2, 3]) # Shape: (3,)
expanded_tensor = tensor.expand(3, 3) # Shape: (3, 3)
print(expanded_tensor)
tensor([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
tensor = torch.tensor([[1], [2], [3]]) # Shape: (3, 1)
expanded_tensor = tensor.expand(3, 4) # Shape: (3, 4)
print(expanded_tensor)
tensor([[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]])