Tensor.scatter_
函数定义
Tensor.scatter_(dim, index, src, reduce=None) → Tensor
将张量src中的所有的值,按照index中指定的indices位置,写到自身张量self中。对于src中的每一个值,它的写入index位置被指定为:
- 等于src中的index,当dimension != dim时
- 等于index参数中对应的值,当dimension = dim时
对于一个3-D的张量,self按照如下公式进行更新:
self[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0 self[i][index[i][j][k]][k] = src[i][j][k] # if dim == 1 self[i][j][index[i][j][k]] = src[i][j][k] # if dim == 2
这个方法是gather()的反向操作。(个人:参数index中有多少个元素,self就有多少个位置的元素需要被改变,操作时,根据参数index的的每一个位置(i,j,k),到src的(i,j,k)位置取出要scatter的值,然后把这个值按照上面的公式,scatter到self的指定位置)
函数参数
-
dim (int) – the axis along which to index
-
index (LongTensor) – the indices of elements to scatter, can be either empty or of the same dimensionality as
src
. When empty, the operation returnsself
unchanged. -
src (Tensor or float) – the source element(s) to scatter.
-
reduce (str, optional) – reduction operation to apply, can be either
'add'
or'multiply'
.
函数参数说明
- 参数index中的值必须介于0和self.size(dim)-1之间。
- self,index和src(如果它是一个张量的话)必须拥有相同数目的维度,并且要求 index.size(d)<=src.size(d)对于所有的维度d,index.size(d)<=self.size(d)对于所有的维度 d != dim。注意:index和src不能被广播
- 对于一个 3-D的张量,当reduction =‘
multiply
’时,self被更新为:self[index[i][j][k]][j][k] *= src[i][j][k] # if dim == 0 self[i][index[i][j][k]][k] *= src[i][j][k] # if dim == 1 self[i][j][index[i][j][k]] *= src[i][j][k] # if dim == 2
例子
>>> src = torch.arange(1, 11).reshape((2, 5)) >>> src tensor([[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10]]) >>> index = torch.tensor([[0, 1, 2, 0]]) >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(0, index, src) tensor([[1, 0, 0, 4, 0], [0, 2, 0, 0, 0], [0, 0, 3, 0, 0]]) >>> index = torch.tensor([[0, 1, 2], [0, 1, 4]]) >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(1, index, src) tensor([[1, 2, 3, 0, 0], [6, 7, 0, 0, 8], [0, 0, 0, 0, 0]]) >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), ... 1.23, reduce='multiply') tensor([[2.0000, 2.0000, 2.4600, 2.0000], [2.0000, 2.0000, 2.0000, 2.4600]]) >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), ... 1.23, reduce='add') tensor([[2.0000, 2.0000, 3.2300, 2.0000], [2.0000, 2.0000, 2.0000, 3.2300]])