torch.Tensor.scatter_#
- Tensor.scatter_(dim, index, src, *, reduce=None) Tensor#
將
src張量中的所有值寫入self中,索引由index張量指定。對於src中的每個值,其輸出索引由其在src中的索引(對於dimension != dim)和index中的相應值(對於dimension = dim)指定。對於一個 3 維張量,
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.size(d) <= src.size(d)對於所有維度d,以及index.size(d) <= self.size(d)對於所有維度d != dim。請注意,對於 NPU,input和index不會相互廣播,因此在 NPU 上執行時,input和index必須具有相同數量的維度。在所有其他情況下,會發生標準廣播。此外,與
gather()一樣,index的值必須包含在0和self.size(dim) - 1之間。警告
當索引不唯一時,行為是不確定的(將從
src中任意選擇一個值)並且梯度將是不正確的(它將被傳播到源中與同一索引對應的所有位置)!注意
反向傳播僅對
src.shape == index.shape進行了實現。此外,它還接受一個可選的
reduce引數,該引數允許指定一個可選的歸約操作,該操作將應用於src張量中的所有值,寫入self中由index指定的索引處。對於src中的每個值,歸約操作將應用於self中的一個索引,該索引由其在src中的索引(對於dimension != dim)和index中的相應值(對於dimension = dim)指定。給定一個 3 維張量並使用乘法進行歸約,
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_()。警告
帶有張量
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) – 要散佈的元素的索引,可以是空的,也可以與
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.]])