逆矩阵和稀疏矩阵乘积的有效numpy/lapack例程? [英] Efficient numpy / lapack routine for product of inverse and sparse matrix?

查看:235
本文介绍了逆矩阵和稀疏矩阵乘积的有效numpy/lapack例程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正方形且密集的矩阵 B 和一个矩形且稀疏的矩阵 A .

I have a matrix B that is square and dense, and a matrix A that is rectangular and sparse.

是否有一种有效地计算乘积B^-1 * A的方法?

Is there a way to efficiently compute the product B^-1 * A?

到目前为止,我使用(以numpy格式)

So far, I use (in numpy)

tmp = B.inv()
return tmp * A

我相信,这使我们感到A的稀疏.我在考虑使用稀疏方法 numpy.sparse.linalg.spsolve,但这要求B(而不是A)是稀疏的.

which, I believe, makes us of A's sparsity. I was thinking about using the sparse method numpy.sparse.linalg.spsolve, but this requires B, and not A, to be sparse.

还有其他加快速度的方法吗?

Is there another way to speed things up?

推荐答案

由于要反转的矩阵是密集的,因此spsolve不是您想要的工具.此外,计算矩阵的逆并将其乘以另一个矩阵是不好的数值实践-使用

Since the matrix to be inverted is dense, spsolve is not the tool you want. In addition, it is bad numerical practice to calculate the inverse of a matrix and multiply it by another - you are much better off using LU decomposition, which is supported by scipy.

另一点是,除非您使用矩阵类(我认为ndarray类更好,这是一个趣味性问题),否则您需要使用dot而不是乘法运算符.而且,如果要将稀疏矩阵与密集矩阵高效相乘,则需要使用稀疏矩阵的dot方法.不幸的是,这仅在第一个矩阵稀疏的情况下有效,因此您需要使用Anycorn建议的技巧,即采用转置来交换操作顺序.

Another point is that unless you are using the matrix class (I think that the ndarray class is better, this is something of a question of taste), you need to use dot instead of the multiplication operator. And if you want to efficiently multiply a sparse matrix by a dense matrix, you need to use the dot method of the sparse matrix. Unfortunately this only works if the first matrix is sparse, so you need to use the trick which Anycorn suggested of taking the transpose to swap the order of operations.

这是一个懒惰的实现,它不使用LU分解,但是应该有效:

Here is a lazy implementation which doesn't use the LU decomposition, but which should otherwise be efficient:

B_inv = scipy.linalg.inv(B)
C = (A.transpose().dot(B_inv.transpose())).transpose()

通过LU分解正确地进行处理涉及找到一种方法,以有效地将三角矩阵与稀疏矩阵相乘,这目前使我难以理解.

Doing it properly with the LU decomposition involves finding a way to efficiently multiply a triangular matrix by a sparse matrix, which currently eludes me.

这篇关于逆矩阵和稀疏矩阵乘积的有效numpy/lapack例程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆