[Pytorch筆記] scatter_


https://blog.csdn.net/qq_16234613/article/details/79827006

scatter_(input, dim, index, src)將src中數據根據index中的索引按照dim的方向填進input中.

1 >>> x = torch.rand(2, 5)
2 >>> x
3 
4  0.4319  0.6500  0.4080  0.8760  0.2355
5  0.2609  0.4711  0.8486  0.8573  0.1029
6 [torch.FloatTensor of size 2x5]

1) dim = 0,分別對每列填充:

>>> torch.zeros(3, 5).scatter_(0, torch.LongTensor([[0, 1, 2, 0, 0], [2, 0, 0, 1, 2]]), x)

 0.4319  0.4711  0.8486  0.8760  0.2355
 0.0000  0.6500  0.0000  0.8573  0.0000
 0.2609  0.0000  0.4080  0.0000  0.1029
[torch.FloatTensor of size 3x5]

實現原理:

對於LoneTensor內的矩陣,暫且稱為 tmp = [[0, 1, 2, 0, 0], [2, 0, 0, 1, 2]];將最終的 3*5的矩陣,暫且稱為result。result初始為全0,需要經過scatter_處理。

舉例:

對於tmp[0][0] = 0  -> 取x中x[0][0] = 0.4319,將其插入到result第0列的第0個位置,result[0][0] = 0.4319;

對於tmp[0][1] = 1  -> 取x中x[0][1] = 0.6500,將其插入到result第1列的第1個位置,result[1][1] = 0.6500;

對於tmp[0][2] = 2  -> 取x中x[0][1] = 0.4080,將其插入到result第2列的第2個位置,result[2][2] = 0.4080;

......

對於tmp[1][0] = 2  -> 取x中x[1][0] = 0.2609,將其插入到result第0列的第2個位置,result[2][0] = 0.2609;

對於tmp[1][1] = 0  -> 取x中x[1][1] = 0.4711,將其插入到result第1列的第0個位置,result[0][1] = 0.4711。

......

2) dim = 1,分別對每行填充

1 >>> z = torch.zeros(2, 4).scatter_(1, torch.LongTensor([[2], [3]]), 1.23)
2 >>> z
3 
4  0.0000  0.0000  1.2300  0.0000
5  0.0000  0.0000  0.0000  1.2300
6 [torch.FloatTensor of size 2x4]

tmp = [[2], [3]]

tmp[0][0] = 2 -> 取x中x[0][0] = 0.4319,將其插入到result第0行的第2個位置,result[0][2] = 0.4319;

......


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM