首先我们看一下Pytorch中torch.where函数是怎样定义的:
1 @overload 2 def where(condition: Tensor) -> Union[Tuple[Tensor, ...], List[Tensor]]: ...
torch.where函数的功能如下:
1 torch.where(condition, x, y): 2 condition:判断条件 3 x:若满足条件,则取x中元素 4 y:若不满足条件,则取y中元素
以具体实例看一下torch.where函数的效果:
1 import torch 2 3 # 条件 4 condition = torch.rand(3, 2) 5 print(condition) 6 # 满足条件则取x中对应元素 7 x = torch.ones(3, 2) 8 print(x) 9 # 不满足条件则取y中对应元素 10 y = torch.zeros(3, 2) 11 print(y) 12 # 条件判断后的结果 13 result = torch.where(condition > 0.5, x, y) 14 print(result)
结果如下:
1 tensor([[0.3224, 0.5789], 2 [0.8341, 0.1673], 3 [0.1668, 0.4933]]) 4 tensor([[1., 1.], 5 [1., 1.], 6 [1., 1.]]) 7 tensor([[0., 0.], 8 [0., 0.], 9 [0., 0.]]) 10 tensor([[0., 1.], 11 [1., 0.], 12 [0., 0.]])
可以看到torch.where函数会对condition中的元素逐一进行判断,根据判断的结果选取x或y中的值,所以要求x和y应该与condition形状相同。