Efficient way to normalize a Scipy Sparse Matrix

后端 未结 5 1770
孤独总比滥情好
孤独总比滥情好 2020-12-29 20:49

I\'d like to write a function that normalizes the rows of a large sparse matrix (such that they sum to one).

from pylab import *
import scipy.sparse as sp

d         


        
5条回答
  •  猫巷女王i
    2020-12-29 21:46

    here is my solution.

    • transpose A
    • calculate sum of each col
    • format diagonal matrix B with reciprocal of sum
    • A*B equals normalization
    • transpose C

      import scipy.sparse as sp
      import numpy as np
      import math
      
      minf = 0.0001
      
      A = sp.lil_matrix((5,5))
      b = np.arange(0,5)
      A.setdiag(b[:-1], k=1)
      A.setdiag(b)
      print A.todense()
      A = A.T
      print A.todense()
      
      sum_of_col = A.sum(0).tolist()
      print sum_of_col
      c = []
      for i in sum_of_col:
          for j in i:
              if math.fabs(j)

提交回复
热议问题