将numpy ndarray添加到稀疏矩阵中

BBB*_*BBB 0 python numpy sparse-matrix

我试图在稀疏矩阵中添加一个numpy ndarray,但我没有成功.我想知道是否有办法这样做,而不将我的稀疏矩阵转换成密集的矩阵.

另一个问题是是否可以添加两个稀疏矩阵.

 x = np.dot(aSparseMatrix, weights)
 y = x + bias
Run Code Online (Sandbox Code Playgroud)

其中x是我的稀疏矩阵,偏差是numpy数组.我得到的错误是:

NotImplementedError: adding a scalar to a CSC or CSR matrix is not supported

aSparseMatrix.shape (1, 10063)

weights.shape  (10063L, 2L)

bias.shape  (2L,)
Run Code Online (Sandbox Code Playgroud)

den*_*nis 5

有不同种类的scipy.sparse矩阵:csr_matrix对于矩阵代数是快速的,但是更新很慢,对于代数/快速更新,coo_matrix很慢.它们在scipy.org/SciPyPackages/Sparse中有描述.

如果稀疏矩阵为99%0,sparsematrix + 1则为99% - 密集.
您可以手动扩展
y = dot( x + bias, npvec )
到以后使用的dot( x, npvec ) + bias * npvec
任何地方y- 可能是短代码,但没有乐趣.

我强烈推荐IPython来尝试:

# add some combinations of scipy.sparse matrices + numpy vecs
# see http://www.scipy.org/SciPyPackages/Sparse

from __future__ import division
import numpy as np
from scipy import sparse as sp

npvec = np.tile( [0,0,0,0,1.], 20 )
Acsr = sp.csr_matrix(npvec)
Acoo = Acsr.tocoo()

for A in (Acsr, Acoo, npvec):
    print "\n%s" % type(A)
    for B in (Acsr, Acoo, npvec):
        print "+ %s = " % type(B) ,
        try:
            AplusB = A + B
            print type(AplusB)
        except StandardError, errmsg:
            print "Error", errmsg
Run Code Online (Sandbox Code Playgroud)