我想知道用scipy.sparse迭代稀疏矩阵的非零项的最佳方法是什么。例如,如果我执行以下操作:
from scipy.sparse import lil_matrix
x = lil_matrix( (20,1) )
x[13,0] = 1
x[15,0] = 2
c = 0
for i in x:
print c, i
c = c+1
输出是
0
1
2
3
4
5
6
7
8
9
10
11
12
13 (0, 0) 1.0
14
15 (0, 0) 2.0
16
17
18
19
因此,迭代器似乎接触到了每个元素,而不仅仅是非零项。我看过API
http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.lil_matrix.html
找了一下,但我似乎找不到有效的解决方案。
最快的方法应该是转换成
coo_matrix
:为了循环来自
scipy.sparse
代码部分的各种稀疏矩阵,我将使用这个小包装函数(注意,对于Python-2,我们鼓励您使用xrange
和izip
来提高大型矩阵的性能):编辑:bbtrb's method(使用coo_matrix)比使用nonzero的原始建议快得多。Sven Marnach建议使用
itertools.izip
也提高了速度。当前最快的是using_tocoo_izip
:产生以下结果:
相关问题 更多 >
编程相关推荐