我如何制作对角矩阵的蒙版,但从第二列开始?

问题描述 投票:2回答:2

所以这就是我现在可以用torch.eye(3,4)得到的东西

我得到的矩阵:

[[1, 0, 0, 0],
 [0, 1, 0, 0],
 [0, 0, 1, 0]]

是否有(简便)方法对其进行转换,或以这种格式制作这样的蒙版:

我想要的矩阵:

[[0, 1, 0, 0],
 [0, 0, 1, 0],
 [0, 0, 0, 1]]
python matrix pytorch tensor diagonal
2个回答
0
投票

您可以通过使用torch.diagonal并指定所需的对角线来完成:

>>> torch.diag(torch.tensor([1,1,1]), diagonal=1)[:-1]

tensor([[0, 1, 0, 0],
        [0, 0, 1, 0],
        [0, 0, 0, 1]])
  • 如果:attr:diagonal = 0,它是主对角线。
  • 如果:attr:[C0
  • 0,则位于主对角线上方。
  • 如果:attr:diagonal <0,则位于主对角线下方。

0
投票

这里是另一种使用diagonal的解决方案,并使用正torch.diagflat()来移动/移动对角线在主对角线上方>]。

torch.diagflat()

以上操作为我们提供了一个方矩阵;但是,我们需要形状为offset非正方形矩阵。因此,我们将通过简单的索引忽略最后一行:

# diagonal values to fill
In [253]: diagonal_vals = torch.ones(3, dtype=torch.long)  

# desired tensor but ...
In [254]: torch.diagflat(diagonal_vals, offset=1) 
Out[254]: 
tensor([[0, 1, 0, 0],
        [0, 0, 1, 0],
        [0, 0, 0, 1],
        [0, 0, 0, 0]])
© www.soinside.com 2019 - 2024. All rights reserved.