gpt4 book ai didi

python - 使用 scipy.sparse.linalg 线性系统求解器的问题

转载 作者:太空宇宙 更新时间:2023-11-03 15:51:12 25 4
gpt4 key购买 nike

我要求解由大型稀疏矩阵组成的线性系统。

我一直在使用 scipy.sparse 库及其 linalg 子库来执行此操作,但我无法获得一些线性求解器工作。

这是一个为我重现问题的工作示例:

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)

运行会产生以下错误

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

对于 minres 的调用,即使维度明显 兼容。 scipy.sparse.linalg 中的其他求解器,例如 cglsqrgmres 都会抛出相同的错误。

这是在带有 SciPy 0.19 的 python 3.6.1 上运行的。

有人知道这里发生了什么吗?

谢谢!

最佳答案

您的使用与 API 不兼容!

spsolveb 上:

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).

允许稀疏 b

minresb 上:

b : {array, matrix}

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

此处不允许使用稀疏 b!

这同样适用于提到的非工作求解器(其中 lsqr 可能有点不同 -> array_like 与 array)。

这并不少见,因为稀疏 rhs 向量在很多情况下都没有帮助,因此许多数值优化开发人员放弃了支持!

这个有效:

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

(你得到了我的赞成和赞扬,因为这个很好的可重现的例子!)

关于python - 使用 scipy.sparse.linalg 线性系统求解器的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46690196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com