Advertisement
Guest User

Untitled

a guest
Apr 16th, 2014
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. 1:193260
  2. 2:51794
  3. 3:19112
  4. 4:9250
  5. 5:6486
  6.  
  7. pdf(x) = 1 / scale * exp ( - x / scale)
  8.  
  9. log_pdf(x) = - log(scale) - x / scale
  10.  
  11. def neg_log_likelihood(scale):
  12. total = 0.0
  13. for x, count in counter.iteritems():
  14. total += (math.log(scale) + x / scale) * count
  15. return total
  16.  
  17. import scipy.stats
  18. import scipy.optimize
  19. import math
  20. import collections
  21.  
  22. def fit1(counter):
  23. def neg_log_likelihood(scale):
  24. total = 0.0
  25. for x, count in counter.iteritems():
  26. total += (math.log(scale) + x / scale) * count
  27. return total
  28.  
  29. optimize_result = scipy.optimize.minimize(neg_log_likelihood, [1.0])
  30. if not optimize_result.success:
  31. raise Exception(optimize_result.message)
  32. return optimize_result.x[0]
  33.  
  34. def fit2(counter):
  35. data = []
  36. # Create an array where each key is repeated as many times
  37. # as the value of the counter.
  38. for x, count in counter.iteritems():
  39. data += [x] * count
  40. fit_result = scipy.stats.expon.fit(data, floc = 0)
  41. return fit_result[-1]
  42.  
  43. def test():
  44. c = collections.Counter()
  45. c[1] = 193260
  46. c[2] = 51794
  47. c[3] = 19112
  48. c[4] = 9250
  49. c[5] = 6486
  50.  
  51. print "fit1 'scale' is %f " % fit1(c)
  52. print "fit2 'scale' is %f " % fit2(c)
  53.  
  54. test()
  55.  
  56. fit1 'scale' is 1.513437
  57. fit2 'scale' is 1.513438
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement