Given that [code] simplify the following PyTorch expression: [code]
- User
Given that
import torch a = torch.randn(8) b = torch.randn(2)simplify the following PyTorch expression:
tensors = [] for i in range(a.size(0)): v = a[i] result = v > b tensors.append(result) return torch.stack(tensors) - Assistant
The given code compares each element of tensor
awith each element of tensorb, resulting in a boolean tensor indicating where elements ofaare greater than elements ofb. This is done in a loop, which can be inefficient for large tensors.We can simplify and vectorize this operation by utilizing PyTorch's broadcasting capabilities. By reshaping
ato have an extra dimension and comparing it directly withb, PyTorch automatically broadcasts the tensors to align their shapes and performs the element-wise comparison.Here's the simplified expression:
return a[:, None] > bThis code reshapes
ato have shape(8, 1)and compares it withbof shape(2,), resulting in a boolean tensor of shape(8, 2), which is the same as stacking the results from the loop.Simplified Code:
return a[:, None] > b