Efficiently Row Standardize a Matrix

后端 未结 1 1214
梦如初夏
梦如初夏 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 ''
        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 ''
        with 24 stored elements in Compressed Sparse Row format>
    

    0 讨论(0)
提交回复
热议问题