从稀疏矩阵的行创建稀疏对角矩阵

时间:2011-12-01 09:49:28

标签: python numpy scipy sparse-matrix

我在Python / Scipy中处理相当大的矩阵。我需要从大矩阵(加载到coo_matrix)中提取行并将它们用作对角元素。目前我以下列方式做到这一点:

import numpy as np
from scipy import sparse

def computation(A):
  for i in range(A.shape[0]):
    diag_elems = np.array(A[i,:].todense())
    ith_diag = sparse.spdiags(diag_elems,0,A.shape[1],A.shape[1], format = "csc")
    #...

#create some random matrix
A = (sparse.rand(1000,100000,0.02,format="csc")*5).astype(np.ubyte)
#get timings
profile.run('computation(A)')

我从profile输出中看到的是,get_csr_submatrix函数在提取diag_elems时大部分时间消耗了这些时间。这让我觉得我使用了初始数据的低效稀疏表示或从稀疏矩阵中提取行的错误方法。你能建议一种更好的方法从稀疏矩阵中提取一行并以对角线形式表示吗?

修改

以下变体消除了行提取的瓶颈(请注意,简单地将'csc'更改为csr是不够的,A[i,:]也必须替换为A.getrow(i)。然而,主要问题是如何省略实现(.todense())并从行的稀疏表示创建对角矩阵。

import numpy as np
from scipy import sparse

def computation(A):
  for i in range(A.shape[0]):
    diag_elems = np.array(A.getrow(i).todense())
    ith_diag = sparse.spdiags(diag_elems,0,A.shape[1],A.shape[1], format = "csc")
    #...

#create some random matrix
A = (sparse.rand(1000,100000,0.02,format="csr")*5).astype(np.ubyte)
#get timings
profile.run('computation(A)')

如果我直接从1行CSR矩阵创建DIAgonal矩阵,如下所示:

diag_elems = A.getrow(i)
ith_diag = sparse.spdiags(diag_elems,0,A.shape[1],A.shape[1])

然后我既不能指定format="csc"参数,也不能将ith_diags转换为CSC格式:

Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.6/profile.py", line 70, in run
    prof = prof.run(statement)
  File "/usr/local/lib/python2.6/profile.py", line 456, in run
    return self.runctx(cmd, dict, dict)
  File "/usr/local/lib/python2.6/profile.py", line 462, in runctx
    exec cmd in globals, locals
  File "<string>", line 1, in <module>
  File "<stdin>", line 4, in computation
  File "/usr/local/lib/python2.6/site-packages/scipy/sparse/construct.py", line 56, in spdiags
    return dia_matrix((data, diags), shape=(m,n)).asformat(format)
  File "/usr/local/lib/python2.6/site-packages/scipy/sparse/base.py", line 211, in asformat
    return getattr(self,'to' + format)()
  File "/usr/local/lib/python2.6/site-packages/scipy/sparse/dia.py", line 173, in tocsc
    return self.tocoo().tocsc()
  File "/usr/local/lib/python2.6/site-packages/scipy/sparse/coo.py", line 263, in tocsc
    data    = np.empty(self.nnz, dtype=upcast(self.dtype))
  File "/usr/local/lib/python2.6/site-packages/scipy/sparse/sputils.py", line 47, in upcast
    raise TypeError,'no supported conversion for types: %s' % args
TypeError: no supported conversion for types: object`

1 个答案:

答案 0 :(得分:3)

以下是我提出的建议:

def computation(A):
    for i in range(A.shape[0]):
        idx_begin = A.indptr[i]
        idx_end = A.indptr[i+1]
        row_nnz = idx_end - idx_begin
        diag_elems = A.data[idx_begin:idx_end]
        diag_indices = A.indices[idx_begin:idx_end]
        ith_diag = sparse.csc_matrix((diag_elems, (diag_indices, diag_indices)),shape=(A.shape[1], A.shape[1]))
        ith_diag.eliminate_zeros()

Python profiler表示1.464秒而5.574秒之前。它利用了定义稀疏矩阵的底层密集数组(indptr,indices,data)。这是我的速成课程:A.indptr [i]:A.indptr [i + 1]定义密集数组中哪些元素对应于第i行中的非零值。 A.data是一个非零的密集1d数组,A和A.indptr的值是这些值的列。

我会做更多的测试,以确保这与以前一样。我只查了几个案例。