當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python PyTorch Tensor.scatter_用法及代碼示例

本文簡要介紹python語言中 torch.Tensor.scatter_ 的用法。

用法:

Tensor.scatter_(dim, index, src, reduce=None) → Tensor

參數

  • dim(int) -索引的軸

  • index(LongTensor) -要分散的元素的索引可以為空或與 src 具有相同的維度。當為空時,該操作返回 self 不變。

  • src(Tensor或者float) -要分散的源元素。

  • reduce(str,可選的) -要應用的縮減操作,可以是 'add''multiply'

將張量 src 中的所有值寫入 selfindex 張量中指定的索引處。對於 src 中的每個值,其輸出索引由 src 中的索引指定 dimension != dimindex 中的相應值 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() 中說明的方式的相反操作。

selfindexsrc (如果是張量)都應該具有相同的維數。還需要 index.size(d) <= src.size(d) 用於所有維度 d ,並且 index.size(d) <= self.size(d) 用於所有維度 d != dim 。請注意,indexsrc 不廣播。

此外,對於 gather() index的值必須在0self.size(dim) - 1之間。

警告

當索引不唯一時,行為是不確定的(將任意選取來自src 的值之一)並且梯度將不正確(它將傳播到源中對應於相同索引的所有位置) !

注意

向後傳遞僅針對 src.shape == index.shape 實施。

此外,還接受一個可選的 reduce 參數,該參數允許指定可選的歸約操作,該操作適用於在 index 中指定的索引處將張量 src 中的所有值轉換為 self 。對於src 中的每個值,歸約操作應用於self 中的索引,該索引由src 中的索引指定dimension != dimindex 中的相應值指定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

使用加法操作減少與使用 scatter_add_() 相同。

例子:

>>> 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]])

相關用法


注:本文由純淨天空篩選整理自pytorch.org大神的英文原創作品 torch.Tensor.scatter_。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。