torch.Tensor.scatter_¶
- Tensor.scatter_(dim, index, src, *, reduce=None) Tensor¶
將張量
src中的所有值寫入到張量self中由index張量指定的索引位置。對於src中的每個值,其輸出索引由其在src中(對於dimension != dim的維度)的索引以及在index中(對於dimension = dim的維度)的對應值指定。對於一個 3D 張量,
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()中描述的操作方式相反。self、index和src(如果它是張量)應具有相同的維度數。此外,要求對於所有維度d,index.size(d) <= src.size(d);對於所有維度d != dim,index.size(d) <= self.size(d)。請注意,index和src不會進行廣播。此外,與
gather()一樣,index中的值必須在0和self.size(dim) - 1(包含)之間。警告
當索引不唯一時,行為是非確定性的(將任意選擇
src中的一個值),並且梯度將是不正確的(它將傳播到源中對應於相同索引的所有位置)!注意
反向傳播僅在
src.shape == index.shape時實現。此外,接受一個可選的
reduce引數,該引數允許指定一個可選的歸約(reduction)操作,該操作應用於張量src中的所有值,並將結果放入self中由index指定的索引位置。對於src中的每個值,歸約操作應用於self中的一個索引,該索引由其在src中(對於dimension != dim的維度)的索引以及在index中(對於dimension = dim的維度)的對應值指定。給定一個 3D 張量並使用乘法操作進行歸約,
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
使用加法操作進行歸約與使用
scatter_add_()相同。警告
使用 Tensor
src的 reduce 引數已被棄用,並將在未來的 PyTorch 版本中移除。請改用scatter_reduce_()以獲得更多歸約選項。- 引數
- 關鍵字引數
reduce (str, optional) – 要應用的歸約操作,可以是
'add'(加法)或'multiply'(乘法)。
示例
>>> 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]])
- scatter_(dim, index, value, *, reduce=None) Tensor:
將
value中的值寫入到self中由index張量指定的索引位置。此操作等效於上一個版本,但src張量完全填充了value。- 引數
dim (int) – 指定索引軸
index (LongTensor) – 要分散(scatter)的元素的索引,可以是空張量或與
src具有相同的維度。當為空時,操作返回未更改的self。value (Scalar) – 要分散的值。
- 關鍵字引數
reduce (str, optional) – 要應用的歸約操作,可以是
'add'(加法)或'multiply'(乘法)。
示例
>>> index = torch.tensor([[0, 1]]) >>> value = 2 >>> torch.zeros(3, 5).scatter_(0, index, value) tensor([[2., 0., 0., 0., 0.], [0., 2., 0., 0., 0.], [0., 0., 0., 0., 0.]])