看了好些教程,都是文字版的,感觉还是图更清晰,也好理解。
PyTorch 中,一般函数加下划线代表直接在原来的 Tensor 上修改
scatter(dim, index, src) 的参数有 3 个
dim:沿着哪个维度进行索引
index:用来 scatter 的元素索引
src:用来 scatter 的源元素,可以是一个标量或一个张量
先看两个例子:
dim=0:
input = torch.rand(2, 5)
index=torch.tensor([[0, 1, 2, 0, 0], [2, 0, 0, 1, 2]])
output=torch.zeros(3, 5).scatter_(0, index, input)
print(input)
print(output)
输出:
第一行index=[0,1,2,0,0]
第二行index=[2,0,0,1,2]
dim=1:
input = torch.randn(2, 4)
print(input)
output = torch.zeros(2, 5)
index = torch.tensor([[3, 2, 0, 1], [1, 2, 0, 3]])
output = output.scatter(1, index, input)
print(output)
输出:
第一行index为[3,2,0,1]
第二行index为[1,2,0,3]
dim=0是纵向的,dim=1是横向的,按平常遍历数组的顺序去遍历tensor(第一行的元素遍历完后再遍历下一行),将遍历到的元素按照index的顺序重新排列即可。