从生成器创建稀疏矩阵

时间:2014-10-08 10:14:32

标签: python scipy sparse-matrix

我想创建一个大的稀疏矩阵,由于内存问题,其源数据无法完全加载。您可能认为我们在磁盘上有一个非常大文件,我们无法读取它。

我想到了,但我找不到从发生器创建稀疏矩阵的方法。

from scipy.sparse import coo_matrix
matrix1 = coo_matrix(xrange(10)) # it works. Create a sparse matrix with 9 elements.
data = ((0, 1, random.randint(0,5)) for i in xrange(10)) # generator example
matrix2 = coo_matrix(data) # does not work.

有什么想法吗?

修改:我发现this,尚未尝试过,但它看起来很有帮助。

1 个答案:

答案 0 :(得分:0)

这是使用生成器填充稀疏矩阵的示例。我使用生成器填充结构化数组,并从其字段中创建稀疏矩阵。

import numpy as np
from scipy import sparse
N, M = 3,4
def foo(N,M):
    # just a simple dense matrix of random data
    cnt = 0
    for i in xrange(N):
        for j in xrange(M):
            yield cnt, (i, j, np.random.random())
            cnt += 1

dt = dt=np.dtype([('i',int), ('j',int), ('data',float)])
X = np.empty((N*M,), dtype=dt)
for cnt, tup in foo(N,M):
    X[cnt] = tup

print X.shape
print X['i']
print X['j']
print X['data']
S = sparse.coo_matrix((X['data'], (X['i'], X['j'])), shape=(N,M))
print S.shape
print S.A

产生类似的东西:

(12,)
[0 0 0 0 1 1 1 1 2 2 2 2]
[0 1 2 3 0 1 2 3 0 1 2 3]
[ 0.99268494  0.89277993  0.32847213  0.56583702  0.63482291  0.52278063
  0.62564791  0.15356269  0.1554067   0.16644956  0.41444479  0.75105334]
(3, 4)
[[ 0.99268494  0.89277993  0.32847213  0.56583702]
 [ 0.63482291  0.52278063  0.62564791  0.15356269]
 [ 0.1554067   0.16644956  0.41444479  0.75105334]]

所有非零数据点将以2种形式存在于内存中 - X的字段,以及稀疏矩阵的row,col,数据数组。

也可以从csv文件的列加载像X这样的结构化数组。

一些稀疏矩阵格式允许您设置数据元素,例如

S = sparse.lil_matrix((N,M))
for cnt, tup in foo(N,M):
    i,j,value = tup
    S[i,j] = value
print S.A

sparse告诉我lil是此类作业的最便宜的格式。