稀疏矩阵的除法

2024-05-23 19:24:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个稀疏稀疏含有45671x45671个元素的矩阵。在此矩阵中,某些行仅包含“0”值。在

我的问题是,如何将每一行的值除以行和。显然,对于for循环,这是有效的,但我正在寻找一种有效的方法。。。在

我已经试过了:

  • matrix / matrix.sum(1)但我有{}问题。在
  • matrix / scs.csc_matrix((matrix.sum(axis=1)))但是{}
  • 其他奇怪的事情。。。在

此外,我想跳过只有“0”值的行。在

所以,如果你有什么解决办法。。。在

提前谢谢你!在


Tags: 方法元素for矩阵事情matrixsumscs
1条回答
网友
1楼 · 发布于 2024-05-23 19:24:26

我有一个M在附近徘徊:

In [241]: M
Out[241]: 
<6x3 sparse matrix of type '<class 'numpy.uint8'>'
    with 6 stored elements in Compressed Sparse Row format>
In [242]: M.A
Out[242]: 
array([[1, 0, 0],
       [0, 1, 0],
       [0, 0, 1],
       [0, 1, 0],
       [0, 0, 1],
       [1, 0, 0]], dtype=uint8)
In [243]: M.sum(1)            # dense matrix
Out[243]: 
matrix([[1],
        [1],
        [1],
        [1],
        [1],
        [1]], dtype=uint32)
In [244]: M/M.sum(1)      # dense matrix - full size of M
Out[244]: 
matrix([[ 1.,  0.,  0.],
        [ 0.,  1.,  0.],
        [ 0.,  0.,  1.],
        [ 0.,  1.,  0.],
        [ 0.,  0.,  1.],
        [ 1.,  0.,  0.]])

这将解释内存错误-如果M太大,M.A会产生内存错误。在


^{pr2}$

我不太清楚这是怎么回事。在

元素乘法有效

In [266]: M.multiply(S)
Out[266]: 
<6x3 sparse matrix of type '<class 'numpy.uint32'>'
    with 6 stored elements in Compressed Sparse Row format>

所以如果我把S构造为S = sparse.csr_matrix(1/M.sum(1)),它应该可以工作

如果某些行的总和为零,则存在被零除的问题。在


如果我将M修改为具有0行

In [283]: M.A
Out[283]: 
array([[1, 0, 0],
       [0, 1, 0],
       [0, 0, 0],
       [0, 1, 0],
       [0, 0, 1],
       [1, 0, 0]], dtype=uint8)
In [284]: S = sparse.csr_matrix(1/M.sum(1))
/usr/local/bin/ipython3:1: RuntimeWarning: divide by zero encountered in true_divide
  #!/usr/bin/python3
In [285]: S.A
Out[285]: 
array([[  1.],
       [  1.],
       [ inf],
       [  1.],
       [  1.],
       [  1.]])
In [286]: M.multiply(S)
Out[286]: 
<6x3 sparse matrix of type '<class 'numpy.float64'>'
    with 5 stored elements in Compressed Sparse Row format>
In [287]: _.A
Out[287]: 
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.],
       [ 1.,  0.,  0.]])

这并不是最好的M来演示这一点,但它提供了一种有用的方法。行和将是密集的,因此您可以使用常见的密集数组方法清除其逆。在

相关问题 更多 >