qp.math.where¶
- where(condition, x=None, y=None)[source]¶
Returns elements chosen from x or y depending on a boolean tensor condition, or the indices of entries satisfying the condition.
The input tensors
condition,x, andymust all be broadcastable to the same shape.- Parameters:
condition (tensor_like[bool]) – A boolean tensor. Where
True, elements fromxwill be chosen, otherwisey. IfxandyareNonethe indices wherecondition==Trueholds will be returned.x (tensor_like) – values from which to choose if the condition evaluates to
Truey (tensor_like) – values from which to choose if the condition evaluates to
False
- Returns:
If
x is Noneandy is None, a tensor or tuple of tensors with the indices whereconditionisTrue. Else, a tensor with elements fromxwhere theconditionisTrue, andyotherwise. In this case, the output tensor has the same shape as the input tensors.- Return type:
tensor_like or tuple[tensor_like]
Example with three arguments
>>> a = torch.tensor([0.6, 0.23, 0.7, 1.5, 1.7], requires_grad=True) >>> b = torch.tensor([-1., -2., -3., -4., -5.], requires_grad=True) >>> math.where(a < 1, a, b) tensor([ 0.6000, 0.2300, 0.7000, -4.0000, -5.0000], grad_fn=<SWhereBackward>)
Warning
The output format for
x=Noneandy=Noneis a tuple of tensor-like objects, with thejth object indicating thejth entries of all indices. Also see the examples below.Example with single argument
For Torch, Autograd, JAX and NumPy, the output formatting is as follows:
>>> a = [[0.6, 0.23, 1.7],[1.5, 0.7, -0.2]] >>> math.where(torch.tensor(a) < 1) (tensor([0, 0, 1, 1]), tensor([0, 1, 1, 2]))
This is not a single tensor-like object but corresponds to the shape
(2, 4).Note that the number of dimensions of the output does not depend on the input shape, it is always two-dimensional.