Guest User

Untitled

a guest
Feb 17th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. scipy.stats.entropy(pk, qk=None, base=None)
  2.  
  3. import numpy as np
  4.  
  5. def kl(p, q):
  6. """Kullback-Leibler divergence D(P || Q) for discrete distributions
  7.  
  8. Parameters
  9. ----------
  10. p, q : array-like, dtype=float, shape=n
  11. Discrete probability distributions.
  12. """
  13. p = np.asarray(p, dtype=np.float)
  14. q = np.asarray(q, dtype=np.float)
  15.  
  16. return np.sum(np.where(p != 0, p * np.log(p / q), 0))
  17.  
  18. from itertools import product
  19. KL = [kl(hist_mat[:,i],hist_mat[:,j]) for i,j in product( range(0,K), range(0,K) )]
  20.  
  21. def kullback_leibler_divergence(X):
  22.  
  23. """
  24. Finds the pairwise Kullback-Leibler divergence
  25. matrix between all rows in X.
  26.  
  27. Parameters
  28. ----------
  29. X : array_like, shape (n_samples, n_features)
  30. Array of probability data. Each row must sum to 1.
  31.  
  32. Returns
  33. -------
  34. D : ndarray, shape (n_samples, n_samples)
  35. The Kullback-Leibler divergence matrix. A pairwise matrix D such that D_{i, j}
  36. is the divergence between the ith and jth vectors of the given matrix X.
  37.  
  38. Notes
  39. -----
  40. Based on code from Gordon J. Berman et al.
  41. (https://github.com/gordonberman/MotionMapper)
  42.  
  43. References:
  44. -----------
  45. Berman, G. J., Choi, D. M., Bialek, W., & Shaevitz, J. W. (2014).
  46. Mapping the stereotyped behaviour of freely moving fruit flies.
  47. Journal of The Royal Society Interface, 11(99), 20140672.
  48. """
  49.  
  50. X_log = np.log(X)
  51. X_log[np.isinf(X_log) | np.isnan(X_log)] = 0
  52.  
  53. entropies = -np.sum(X * X_log, axis=1)
  54.  
  55. D = np.matmul(-X, X_log.T)
  56. D = D - entropies
  57. D = D / np.log(2)
  58. D *= (1 - np.eye(D.shape[0]))
  59.  
  60. return D
Add Comment
Please, Sign In to add comment