如何在numpy.linalg.solve中使用稀疏矩阵 [英] How to use a sparse matrix in numpy.linalg.solve
问题描述
我想为x
Ax = b
其中A是稀疏的,而b是正则列矩阵.但是,当我插入常规的np.linalg.solve(A,b)
例程时,它给了我一个错误.但是,当我执行np.linalg.solve(A.todense(),b)
时,效果很好.
Where A is sparse and b is just regular column matrix. However when I plug into the usual np.linalg.solve(A,b)
routine it gives me an error. However when I do np.linalg.solve(A.todense(),b)
it works fine.
我如何使用此线性求解仍保留A
的sparseness
?原因是A
关于150 x 150
很大,并且大约有50个这样的矩阵,因此我希望它尽可能长地保持稀疏.
How can I use this linear solve still preserving the sparseness
of A
?. The reason is A
is quite large about 150 x 150
and there are about 50 such matrices and so keeping it sparse for as long as possible is the way I'd prefer it.
我希望我的问题有道理.我应该如何实现这一目标?
I hope my question makes sense. How should I go about achieving this?
推荐答案
np.linalg.solve
仅适用于类似数组的对象.例如,它可以在np.ndarray
或np.matrix
上工作(来自numpy文档的示例):
np.linalg.solve
only works for array-like objects. For example it would work on a np.ndarray
or np.matrix
(Example from the numpy documentation):
import numpy as np
a = np.array([[3,1], [1,2]])
b = np.array([9,8])
x = np.linalg.solve(a, b)
或
import numpy as np
a = np.matrix([[3,1], [1,2]])
b = np.array([9,8])
x = np.linalg.solve(a, b)
或在A.todense()
上,其中A=scipy.sparse.csr_matrix(np.matrix([[3,1], [1,2]]))
会返回np.matrix
对象.
or on A.todense()
where A=scipy.sparse.csr_matrix(np.matrix([[3,1], [1,2]]))
as this returns a np.matrix
object.
To work with a sparse matrix, you have to use scipy.sparse.linalg.spsolve
(as already pointed out by rakesh)
import numpy as np
import scipy.sparse
import scipy.sparse.linalg
a = scipy.sparse.csr_matrix(np.matrix([[3,1], [1,2]]))
b = np.array([9,8])
x = scipy.sparse.linalg.spsolve(a, b)
请注意,x
仍然是np.ndarray
,而不是稀疏矩阵.仅当您求解Ax = b时才返回稀疏矩阵,其中b是矩阵而不是向量.
Note that x
is still a np.ndarray
and not a sparse matrix. A sparse matrix will only be returned if you solve Ax=b, with b being a matrix and not a vector.
这篇关于如何在numpy.linalg.solve中使用稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!