相关疑难解决方法(0)

如何通过广播的密集1d数组元素地乘以scipy.sparse矩阵?

假设我有一个2d稀疏数组.在我的实际用例中,行数和列数都要大得多(比如20000和50000),因此在使用密集表示时它无法适应内存:

>>> import numpy as np
>>> import scipy.sparse as ssp

>>> a = ssp.lil_matrix((5, 3))
>>> a[1, 2] = -1
>>> a[4, 1] = 2
>>> a.todense()
matrix([[ 0.,  0.,  0.],
        [ 0.,  0., -1.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  2.,  0.]])
Run Code Online (Sandbox Code Playgroud)

现在假设我有一个密集的1d数组,其中包含大小为3的所有非零组件(在我的实际案例中为50000):

>>> d = np.ones(3) * 3
>>> d
array([ 3.,  3.,  3.])
Run Code Online (Sandbox Code Playgroud)

我想使用numpy的常用广播语义来计算a和d的元素乘法.然而,scipy中的稀疏矩阵属于np.matrix:'*'运算符被重载使其行为类似于矩阵乘法而不是逐元乘法:

>>> a * d
array([ 0., -3.,  0.,  0.,  6.])
Run Code Online (Sandbox Code Playgroud)

一种解决方案是将'a'切换到'*'运算符的数组语义,这将产生预期的结果:

>>> a.toarray() * d
array([[ 0.,  0., …
Run Code Online (Sandbox Code Playgroud)

python numpy scipy sparse-matrix

41
推荐指数
2
解决办法
1万
查看次数

scipy.sparse矩阵的元素功效

如何scipy.sparse根据元素将矩阵提升为幂?numpy.power根据其手册,应该这样做,但它在稀疏矩阵上失败:

>>> X
<1353x32100 sparse matrix of type '<type 'numpy.float64'>'
        with 144875 stored elements in Compressed Sparse Row format>

>>> np.power(X, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../scipy/sparse/base.py", line 347, in __pow__
    raise TypeError('matrix is not square')
TypeError: matrix is not square
Run Code Online (Sandbox Code Playgroud)

同样的问题X**2.转换为密集阵列有效,但浪费了宝贵的秒数.

我有同样的问题np.multiply,我用稀疏矩阵的multiply方法解决了,但似乎没有pow方法.

python numpy exponentiation scipy sparse-matrix

16
推荐指数
2
解决办法
4870
查看次数

标签 统计

numpy ×2

python ×2

scipy ×2

sparse-matrix ×2

exponentiation ×1