假設我有一個像張量
a = torch.tensor([[3, 1, 5, 0, 4, 2],
[2, 1, 3, 4, 5, 0],
[0, 4, 5, 1, 2, 3],
[3, 1, 4, 5, 0, 2],
[3, 5, 4, 2, 0, 1],
[5, 3, 0, 4, 1, 2]])
我想通過應用轉換來重新組織張量的行,a[c]
其中
c = torch.tensor([0,2,4,1,3,5])
要得到
b = torch.tensor([[3, 1, 5, 0, 4, 2],
[0, 4, 5, 1, 2, 3],
[3, 5, 4, 2, 0, 1],
[2, 1, 3, 4, 5, 0],
[3, 1, 4, 5, 0, 2],
[5, 3, 0, 4, 1, 2]])
為此,我想生成張量,c
以便無論張量 a 的大小和步長大小(為簡單起見,我在本示例中將其設為 2)都可以進行此轉換。誰能告訴我如何在不使用 PyTorch 中的顯式 for 回圈的情況下為一般情況生成這樣的張量?
uj5u.com熱心網友回復:
您可以使用torch.index_select,因此:
b = torch.index_select(a, 0, c)
官方檔案中的解釋很清楚。
uj5u.com熱心網友回復:
我還想出了另外一個解決方案,解決了上面重新組織張量的行a
來生成張量b
而不生成索引陣列的問題c
step = 2
b = a.view(-1,step,a.size(-1)).transpose(0,1).reshape(-1,a.size(-1))
uj5u.com熱心網友回復:
想了一會兒,我想出了以下生成索引的解決方案
step = 2
idx = torch.arange(0,a.size(0),step)
# idx = tensor([0, 2, 4])
idx = idx.repeat(int(a.size(0)/idx.size(0)))
# idx = tensor([0, 2, 4, 0, 2, 4])
incr = torch.arange(0,step)
# incr = tensor([0, 1])
incr = incr.repeat_interleave(int(a.size(0)/incr.size(0)))
# incr = tensor([0, 0, 0, 1, 1, 1])
c = incr idx
# c = tensor([0, 2, 4, 1, 3, 5])
在此之后,張量c
可以用于b
通過使用獲得張量
b = a[c.long()]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/397952.html