如何在处理pytorch中的运行时错误时向量化矩阵求逆

How to vectorize matrix inversion while handling runtime error in pytorch

我需要在 pytorch 中反转一些矩阵。但是,有些矩阵是不可逆的,导致代码抛出如下运行时错误,

matrices = torch.randn([5,3,3])
matrices[[2,3]] = torch.zeros([3,3])
inverses = torch.inverse(matrices)

RuntimeError: inverse_cpu: For batch 2: U(1,1) is zero, singular U.

对于这种情况,我有一个后备技术。但是,我无法弄清楚哪个矩阵会引发错误。目前,我已将代码替换为非矢量化版本,但它已成为瓶颈。

有没有办法在不放弃矢量化的情况下处理这个问题?

我能想到的最好的方法是先计算每个矩阵的行列式,然后计算具有 abs(det)>0.

的矩阵的逆矩阵
matrices = torch.randn([5,3,3])
matrices[[2,3]] = torch.zeros([3,3])
determinants = torch.det(matrices)
inverses = torch.inverse(matrices[determinants.abs()>0.])

您将不得不处理奇异矩阵的移除,但这应该不会太难,因为您从 determinants.abs()==0. 中获得了这些矩阵的索引值。这允许您保持反演向量化。