例子来源
https://pytorch.org/docs/stable/generated/torch.Tensor.scatter_.html
# example-01
import torch
src = torch.arange(1, 11).reshape((2, 5))
"""
tensor([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10]])
"""
index = torch.tensor([[0, 1, 2, 0]])
output = torch.zeros(3, 5, dtype=src.dtype)
res = output.scatter_(0, index, src)
"""
res=
tensor([[1, 0, 0, 4, 0],
[0, 2, 0, 0, 0],
[0, 0, 3, 0, 0]])
"""
"""
解析:
scatter_的作用是,将src中的某些值填充到output中
当维度=0时,
公式:src[i][j]=output[index[i][j]][j]
具体地,
src[0][0]=output[index[0][0]][0]=output[0][0]=1
src[0][1]=output[index[0][1]][0]=output[1][1]=2
src[0][2]=output[index[0][2]][0]=output[2][2]=3
src[0][3]=output[index[0][3]][0]=output[0][3]=4
"""
src = torch.arange(1, 11).reshape((2, 5))
index = torch.tensor([[0, 1, 2], [0, 1, 4]])
res = output.scatter_(1, index, src)
"""
res=
tensor([[1, 2, 3, 0, 0],
[6, 7, 0, 0, 8],
[0, 0, 0, 0, 0]])
"""
"""
当维度=1时,
公式:src[i][j]=output[i][index[i][j]]
具体地,
src[0][0]=output[0][index[0][0]]=output[0][0]=1
src[0][1]=output[0][index[0][0]]=output[0][1]=2
src[0][2]=...
...
src[1][2]=output[1][index[1][2]]=output[1][4]=8
注:src[i][j]中,i和j的取值是根据index矩阵的行列大小来取值的。
"""