entropy.py 365 B

1234567891011121314151617181920
  1. import numpy as np
  2. import math, sys
  3. filename = sys.argv[1]
  4. metrix = np.loadtxt(filename)
  5. def cal_entropy(m):
  6. sum_err = m.sum()
  7. entropy = 0.0
  8. if sum_err == 0:
  9. return entropy
  10. for i in np.nditer(m):
  11. if i != 0:
  12. p = i / sum_err
  13. entropy += -1 * (p * math.log2(p))
  14. return entropy
  15. print(cal_entropy(metrix))