Eficientemente fila estandarizar una matriz

Necesito una forma eficiente de estandarizar una matriz dispersa.

Dado

W = matrix([[0, 1, 0, 1, 0, 0, 0, 0, 0], [1, 0, 1, 0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0, 0], [1, 0, 0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 1, 0, 1, 0, 1, 0], [0, 0, 1, 0, 1, 0, 0, 0, 1], [0, 0, 0, 1, 0, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 0, 1, 0, 1, 0]]) row_sums = W.sum(1) 

Necesito producir …

 W2 = matrix([[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. ]]) 

Dónde,

 for i in range(9): W2[i] = W[i]/row_sums[i] 

Me gustaría encontrar una manera de hacer esto sin bucles (es decir, vectorizados) y utilizando matrices Scipy.sparse. W podría ser tan grande a 10mil x 10mil.

con un poco de algebra matricial

 >>> 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>