0

我正在尝试将一个 numpy ndarray 添加到一个稀疏矩阵中,但我没有成功。我想知道是否有办法做到这一点,而无需将我的稀疏矩阵转换为密集矩阵。

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

 x = np.dot(aSparseMatrix, weights)
 y = x + bias

其中 x 是我的稀疏矩阵,bias 是 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,)
4

2 回答 2

6

有不同种类的 scipy.sparse 矩阵: csr_matrix 对矩阵代数来说很快但更新很慢, coo_matrix 对代数来说很慢/更新很快。它们在scipy.org/SciPyPackages/Sparse中进行了描述。

如果一个稀疏矩阵是 99% 0,那么sparsematrix + 199% 就是密集的。
例如,您可以手动将其扩展
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
于 2013-01-15T13:23:12.300 回答
0

代替 numpy 点积,使用简单的 * 积。Python 将广播并获得正确的结果。

加法不起作用,因为通过 numpy 点积,结果矩阵的大小与预期不匹配,因此无法在具有不同形状的两个矩阵之间进行加法。

于 2013-01-10T05:07:12.797 回答