如何在Python的SciPy中更改稀疏矩阵中的元素?

22

我已经编写了一段小代码,想要用于解决涉及大稀疏矩阵的特征值问题。目前它能够正常工作,我现在想做的是将稀疏矩阵中的某些元素设置为零,即最顶行的元素(这对应于实现边界条件)。我可以调整下面的列向量(C0、C1和C2)来实现这一点。然而,我想知道是否有更直接的方法。显然,NumPy索引在SciPy的稀疏包中不起作用。

import scipy.sparse as sp
import scipy.sparse.linalg  as la
import numpy as np
import matplotlib.pyplot as plt

#discretize x-axis
N = 11
x = np.linspace(-5,5,N)
print(x)
V = x * x / 2
h = len(x)/(N)
hi2 = 1./(h**2)
#discretize Schroedinger Equation, i.e. build 
#banded matrix from difference equation
C0 = np.ones(N)*30. + V
C1 = np.ones(N) * -16.
C2 = np.ones(N) * 1.
diagonals = np.array([-2,-1,0,1,2])
H = sp.spdiags([C2, C1, C0,C1,C2],[-2,-1,0,1,2], N, N)
H *= hi2 * (- 1./12.) * (- 1. / 2.)
#solve for eigenvalues
EV = la.eigsh(H,return_eigenvectors = False)

#check structure of H
plt.figure()
plt.spy(H)
plt.show()

这是由上面的代码创建的矩阵的可视化。我想将第一行中的元素设置为零。enter image description here


我找到了一个解决方法。我使用的格式(dia_matrix)不适合我想要实现的目标。我将改用csr_matrix。那我应该关闭这个帖子吗? - seb
这是一个写得很好的问题,将来可能对其他人有用。你考虑把你找到的东西发表为答案吗? - YXD
2个回答

28

根据评论的建议,我将发布我找到的答案以回答自己的问题。 SciPy的稀疏包中有几个矩阵类,它们在这里列出。人们可以将稀疏矩阵从一个类转换为另一个类。所以,为了我需要做的事情,我选择将我的稀疏矩阵转换为csr_matrix类,只需

H = sp.csr_matrix(H)

然后,我可以使用常规的NumPy表示法将第一行中的元素设置为0:

H[0,0] = 0
H[0,1] = 0
H[0,2] = 0

为了完整起见,我在下面发布完整的修改后的代码片段。

#SciPy Sparse linear algebra takes care of sparse matrix computations
#http://docs.scipy.org/doc/scipy/reference/sparse.linalg.html
import scipy.sparse as sp
import scipy.sparse.linalg  as la

import numpy as np
import matplotlib.pyplot as plt

#discretize x-axis
N = 1100
x = np.linspace(-100,100,N)
V = x * x / 2.
h = len(x)/(N)
hi2 = 1./(h**2)

#discretize Schroedinger Equation, i.e. build 
#banded matrix from difference equation
C0 = np.ones(N)*30. + V
C1 = np.ones(N) * -16.
C2 = np.ones(N) * 1.

H = sp.spdiags([C2, C1, C0, C1, C2],[-2,-1,0,1,2], N, N)
H *= hi2 * (- 1./12.) * (- 1. / 2.)
H = sp.csr_matrix(H)
H[0,0] = 0
H[0,1] = 0
H[0,2] = 0

#check structure of H
plt.figure()
plt.spy(H)
plt.show()

EV = la.eigsh(H,return_eigenvectors = False)

4
如果行数大于列数,使用csr会更快,但如果列数大于行数,则使用csc会更快。 - Ulf Aslak
4
如果您要频繁修改矩阵,则基于行的链表稀疏矩阵更快-请使用lil_matrix - Toke Faurby

3

在scipy中,使用 lil_matrix 比简单的 numpy 方法更加高效地改变元素。

H = sp.csr_matrix(H)
HL = H.tolil()
HL[1,1] = 5  # same as the numpy indexing notation
print HL
print HL.todense() # if numpy style matrix is required
H = HL.tocsr()    # if csr is required

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接