Efficiently Row Standardize a Matrix

后端 未结 1 1213
梦如初夏
梦如初夏 2021-01-18 19:10

I need an efficient way to row standardize a sparse matrix.

Given

W = matrix([[0, 1, 0, 1, 0, 0, 0, 0, 0],
            [1, 0, 1, 0, 1, 0, 0, 0, 0],
          


        
相关标签:
1条回答
  • 2021-01-18 19:48

    with a bit of matrix algebra

    >>> cc
    <9x9 sparse matrix of type '<type 'numpy.int32'>'
        with 24 stored elements in Compressed Sparse Row format>
    >>> ccd = sparse.spdiags(1./cc.sum(1).T, 0, *cc.shape)
    >>> ccn = ccd * cc
    >>> np.round(ccn.todense(), 2)
    array([[ 0.  ,  0.5 ,  0.  ,  0.5 ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ],
           [ 0.33,  0.  ,  0.33,  0.  ,  0.33,  0.  ,  0.  ,  0.  ,  0.  ],
           [ 0.  ,  0.5 ,  0.  ,  0.  ,  0.  ,  0.5 ,  0.  ,  0.  ,  0.  ],
           [ 0.33,  0.  ,  0.  ,  0.  ,  0.33,  0.  ,  0.33,  0.  ,  0.  ],
           [ 0.  ,  0.25,  0.  ,  0.25,  0.  ,  0.25,  0.  ,  0.25,  0.  ],
           [ 0.  ,  0.  ,  0.33,  0.  ,  0.33,  0.  ,  0.  ,  0.  ,  0.33],
           [ 0.  ,  0.  ,  0.  ,  0.5 ,  0.  ,  0.  ,  0.  ,  0.5 ,  0.  ],
           [ 0.  ,  0.  ,  0.  ,  0.  ,  0.33,  0.  ,  0.33,  0.  ,  0.33],
           [ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.5 ,  0.  ,  0.5 ,  0.  ]])
    >>> ccn
    <9x9 sparse matrix of type '<type 'numpy.float64'>'
        with 24 stored elements in Compressed Sparse Row format>
    
    0 讨论(0)
提交回复
热议问题