用矢量划分scipy.lil_matrix

时间:2018-02-18 09:56:45

标签: python numpy scipy sparse-matrix division

我想用矢量划分我的稀疏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矩阵/向量完美无缺

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矩阵/向量分开会引发 ValueError:不一致的形状

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

是否有一些通过向量划分稀疏矩阵的好方法?

1 个答案:

答案 0 :(得分:4)

  

是否有一些通过向量划分稀疏矩阵的好方法?

您可以使用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>