[英]Python Sparse matrix access elements
I have a sparse matrix A in python.我在 python 中有一个稀疏矩阵 A。 I m going through code of a friend of mine and he uses
A[:,i:i+1].toarray().flatten()
in his code.我正在浏览我的一个朋友的代码,他在他的代码中使用
A[:,i:i+1].toarray().flatten()
。 As far as I m concerned, the program worked for him.就我而言,该程序对他有用。 However when I try to use it, I get:
但是,当我尝试使用它时,我得到:
from scipy import sparse
...
diagonals = [[2] * 3, [-1] * (3-1), [-1] * (3-1)]
offsets = [0, 1, -1]
B = sparse.diags(diagonals, offsets)
A = sparse.kronsum(B,B)
...
A[:,i:i+1].toarray().flatten()
Exception:例外:
in __getitem__
raise NotImplementedError
NotImplementedError
My question, what to I need to implement or how could I access elements of a sparse matrix.我的问题是,我需要实现什么或如何访问稀疏矩阵的元素。 Thanks for the help.
谢谢您的帮助。
Most likely you have a bsr format matrix, while the code you have, was implemented using an older version of scipy and returns a csr or csc matrix.很可能您有一个bsr格式矩阵,而您拥有的代码是使用旧版本的 scipy 实现的,并返回一个 csr 或 csc 矩阵。 I don't know a good way of tracing this.
我不知道追踪这个的好方法。
So if we run you code on scipy 1.7.2:因此,如果我们在 scipy 1.7.2 上运行您的代码:
type(A)
scipy.sparse.bsr.bsr_matrix
We can access the elements by:我们可以通过以下方式访问元素:
A = sparse.kronsum(B,B,format = "csr")
A[:,i:i+1].toarray().flatten()
array([-1., 4., -1., 0., -1., 0., 0., 0., 0.])
Or或者
A = sparse.kronsum(B,B)
A.tocsr()[:,i:i+1].toarray().flatten()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.