将 scipy.lil_matrix 除以向量

Dividing scipy.lil_matrix by vector

我想将我的稀疏 scipy.lil_matrix 矩阵除以向量并再次获得稀疏矩阵。假设我有 2 个 lil_matrix 变量和 2 个 numpy 数组 a, b, c, d,像这样

In [1]: a
Out[1]: 
<4x3 sparse matrix of type '<class 'numpy.float64'>'
    with 11 stored elements in LInked List format>

In [2]: b
Out[2]: 
<4x1 sparse matrix of type '<class 'numpy.float64'>'
    with 4 stored elements in LInked List format>

In [3]: c
Out[3]: 
array([[ 0.,  1.,  2.],
       [ 1.,  2.,  3.],
       [ 2.,  3.,  4.],
       [ 3.,  4.,  5.]])

In [4]: d
Out[4]: 
array([[ 1.],
       [ 2.],
       [ 3.],
       [ 4.]])

除以 numpy matrix/vector 完美

In [136]: c/d
Out[136]: 
array([[ 0.        ,  1.        ,  2.        ],
       [ 0.5       ,  1.        ,  1.5       ],
       [ 0.66666667,  1.        ,  1.33333333],
       [ 0.75      ,  1.        ,  1.25      ]])

但是除法 lil_matrix matrix/vector 会引发 ValueError: inconsistent shapes

In [137]: a/b
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-137-aae42d317509> in <module>()
----> 1 a/b

/usr/local/lib/python3.6/dist-packages/scipy/sparse/lil.py in __truediv__(self, other)
    401             return new
    402         else:
--> 403             return self.tocsr() / other
    404 
    405     def copy(self):

/usr/local/lib/python3.6/dist-packages/scipy/sparse/base.py in __truediv__(self, other)
    503 
    504     def __truediv__(self, other):
--> 505         return self._divide(other, true_divide=True)
    506 
    507     def __div__(self, other):

/usr/local/lib/python3.6/dist-packages/scipy/sparse/base.py in _divide(self, other, true_divide, rdivide)
    496             self_csr = self.tocsr()
    497             if true_divide and np.can_cast(self.dtype, np.float_):
--> 498                 return self_csr.astype(np.float_)._divide_sparse(other)
    499             else:
    500                 return self_csr._divide_sparse(other)

/usr/local/lib/python3.6/dist-packages/scipy/sparse/compressed.py in _divide_sparse(self, other)
   1134         """
   1135         if other.shape != self.shape:
-> 1136             raise ValueError('inconsistent shapes')
   1137 
   1138         r = self._binopt(other, '_eldiv_')

ValueError: inconsistent shapes

有什么好的方法可以用向量划分稀疏矩阵吗?

Is there some nice way to divide sparse matrices by vector?

你可以使用multiply()方法,结果仍然是一个稀疏矩阵,但是coo格式:

>>> a
<4x3 sparse matrix of type '<class 'numpy.float64'>'
    with 11 stored elements in LInked List format>
>>> d
array([[1.],
       [2.],
       [3.],
       [4.]])
>>> a.multiply(1/d)
<4x3 sparse matrix of type '<class 'numpy.float64'>'
    with 11 stored elements in COOrdinate format>