条件选取:torch.where(condition, x, y) → Tensor
返回从 x 或 y 中选择元素的张量,取决于 condition
操作定义:
举个例子:
>>> import torch >>> c = randn(2, 3) >>> c tensor([[ 0.0309, -1.5993, 0.1986], [-0.0699, -2.7813, -1.1828]]) >>> a = torch.ones(2, 3) >>> a tensor([[1., 1., 1.], [1., 1., 1.]]) >>> b = torch.zeros(2, 3) >>> b tensor([[0., 0., 0.], [0., 0., 0.]]) >>> torch.where(c > 0, a, b) tensor([[1., 0., 1.], [0., 0., 0.]]) |
举个例子:
>>> a = torch.randn(4, 10) >>> b = a.topk(3, dim = 1) >>> b (tensor([[ 1.0134, 0.8785, -0.0373], [ 1.4378, 1.4022, 1.0115], [ 0.8985, 0.6795, 0.6439], [ 1.2758, 1.0294, 1.0075]]), tensor([[5, 7, 6], [2, 5, 8], [5, 9, 2], [7, 9, 6]])) >>> index = b[1] >>> index tensor([[5, 7, 6], [2, 5, 8], [5, 9, 2], [7, 9, 6]]) >>> label = torch.arange(10) + 100 >>> label tensor([100, 101, 102, 103, 104, 105, 106, 107, 108, 109]) >>> torch.gather(label.expand(4, 10), dim=1, index=index.long()) # 进行聚合操作 tensor([[105, 107, 106], [102, 105, 108], [105, 109, 102], [107, 109, 106]]) |