Advertisement
Guest User

Untitled

a guest
Jan 29th, 2015
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. import numpy as np
  2. from scipy.stats import dirichlet
  3. from scipy.special import psi, polygamma
  4.  
  5. eps = 1e-100
  6. max_iter = 10
  7.  
  8. def parameter_estimation(theta, old_alpha):
  9. """
  10. estimating a dirichlet parameter given a set of multinomial parameters.
  11. Dirichlet parameter alpha can be decomposed into precision s and mean m
  12. where s = \sum_k alpha_k, m = alpha/s, and alpha = s * m.
  13. s and each entry of m must be positive.
  14.  
  15. Argument
  16. theta : a set of multinomial, N x K matrix (N = # of observation, K = dimension of dirichlet)
  17. s : precision parameter (scala)
  18. m : mean parameter (K-vector)
  19. """
  20.  
  21. log_p_bar = np.mean(np.log(theta), 0) #sufficient statistics
  22.  
  23. for j in xrange(max_iter):
  24. digamma_alpha = psi(np.sum(old_alpha)) + log_p_bar
  25. old_alpha = np.exp(digamma_alpha) + 0.5
  26. old_alpha[old_alpha<0.6] = 1.0/(- digamma_alpha[old_alpha<0.6] + psi(1.))
  27.  
  28. for i in xrange(max_iter):
  29. new_alpha = old_alpha - (psi(old_alpha)-digamma_alpha)/(polygamma(1,old_alpha))
  30. old_alpha = new_alpha
  31.  
  32. return new_alpha
  33.  
  34.  
  35. if __name__ == '__main__':
  36. N = 100
  37. K = 5 # dimension of Dirichlet
  38.  
  39. _alpha = np.random.gamma(1,1) * np.random.dirichlet([1.]*K) # ground truth alpha
  40.  
  41. obs = np.random.dirichlet(_alpha, size=N) + eps # draw N samples from Dir(_alpha)
  42. obs /= np.sum(obs, 1)[:,np.newaxis] #renormalize for added eps
  43.  
  44. initial_alpha = np.random.dirichlet([1.]*K) * np.random.gamma(1,1) # first guess on alpha
  45.  
  46. g_ll = 0 #log-likelihood with ground truth parameter
  47. ll = 0 #log-likelihood with initial guess of alpha
  48. for i in xrange(N):
  49. g_ll += dirichlet.logpdf(obs[i], _alpha)
  50. ll += dirichlet.logpdf(obs[i], initial_alpha)
  51. print 'likelihood p(obs|_alpha) = %.3f' % g_ll
  52. print 'likelihood p(obs|initial_alpha) = %.3f' % ll
  53.  
  54. #estimating
  55. est_alpha = parameter_estimation(obs, initial_alpha)
  56.  
  57. ll = 0 #log-likelihood with estimated parameter
  58. for i in xrange(N):
  59. ll += dirichlet.logpdf(obs[i], est_alpha)
  60.  
  61. print 'likelihood p(obs|est_alpha) = %.3f' % ll
  62. print 'likelihood difference = %.3f' % (g_ll - ll)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement