Issues using the scipy.sparse.linalg linear system solvers

社会主义新天地 提交于 2021-02-08 15:25:37

问题


I've got linear system to solve which consists of large, sparse matrices.

I've been using the scipy.sparse library, and its linalg sub-library to do this, but I can't get some of the linear solvers to work.

Here is a working example which reproduces the issue for me:

from numpy.random import random
from scipy.sparse import csc_matrix
from scipy.sparse.linalg import spsolve, minres

N = 10
A = csc_matrix( random(size = (N,N)) )
A = (A.T).dot(A) # force the matrix to be symmetric, as required by minres
x = csc_matrix( random(size = (N,1)) ) # create a solution vector
b = A.dot(x) # create the RHS vector

# verify shapes and types are correct
print('A', A.shape, type(A))
print('x', x.shape, type(x))
print('b', b.shape, type(b))

# spsolve function works fine
sol1 = spsolve(A, b)

# other solvers throw a incompatible dimensions ValueError
sol2 = minres(A, b)

Running this produces the following error

    raise ValueError('A and b have incompatible dimensions')
ValueError: A and b have incompatible dimensions

for the call to minres, even though the dimensions clearly are compatible. Other solvers in scipy.sparse.linalg, such as cg, lsqr and gmres all throw an identical error.

This is being run on python 3.6.1 with SciPy 0.19.

Anyone have any idea what's going on here?

Thanks!


回答1:


Your usage is incompatible with the API!

spsolve on b:

b : ndarray or sparse matrix

The matrix or vector representing the right hand side of the equation. If a vector, b.shape must be (n,) or (n, 1).

sparse b is allowed

minres on b:

b : {array, matrix}

Right hand side of the linear system. Has shape (N,) or (N,1).

sparse b is not allowed here!

The same applies to the mentioned non-working solvers (where lsqr might be a bit different -> array_like vs. array).

This is not that uncommon as sparse rhs-vectors are not helping in many cases and a lot of numerical-optimization devs therefore drop support!

This works:

sol2 = minres(A, b.todense())

(you got my upvote and praise for the nice reproducible example!)



来源:https://stackoverflow.com/questions/46690196/issues-using-the-scipy-sparse-linalg-linear-system-solvers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!