Advertisement
Guest User

Untitled

a guest
Mar 27th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. import csv
  2. import numpy as np
  3.  
  4. J = 200; I = 10;
  5. H = np.linspace(-5.0, 5.0, 10000)
  6.  
  7. def X(h):
  8. return h
  9. def A(x_h):
  10. return norm.pdf(x=x_h, loc=0, scale=1)
  11. def P_X_h(a_i, b_i, theta_j):
  12. p = 1.0 / (1.0 + np.exp(-1.7 * a_i * (theta_j - b_i)))
  13. return p
  14. def P_X_h_post(u, a, b, h, i, j):
  15. p = 1.0; p_tmp1 = 0.0; p_tmp2 = 1.0;
  16. for i in range(I):
  17. p *= P_X_h(a[i], b[i], h) ** u[j][i] * (1.0 - P_X_h(a[i], b[i], h)) ** (1 - u[j][i]) * A(X(h))
  18. for h_ in range (-H / 2 , H / 2):
  19. for i in range(I):
  20. p_tmp2 /= P_X_h(a[i], b[i], h_) ** u[j][i] * (1.0 - P_X_h(a[i], b[i], h_)) ** (1 - u[j][i]) * A(X(h_))
  21. p_tmp1 += p_tmp2
  22. p /= p_tmp1
  23. return p
  24. def L(u, a, b, h, j):
  25. l = 1.0
  26. for i in range(I):
  27. l *= P_X_h(a[i], b[i], h) ** u[i][j] * (1.0 - P_X_h(a[i], b[i], h)) ** (1 - u[j][i]) * A(X(h))
  28. return l
  29.  
  30. def likelihood_a_i(u, a, b, i):
  31. l = 0.0
  32. for h in H:
  33. for j in range(J):
  34. l += (u[j][i] - P_X_h(a[i], b[i], h)) * (X(j) - b[i]) * P_X_h_post(u, a, b, h, i, j)
  35. return l_a_i
  36. def likelihood_b_i(u, a_i, b_i, i):
  37. l = 0.0
  38. for h in H:
  39. for j in range(J):
  40. l += (u[j][i] - P_X_h(a_i, b_i, h)) * P_X_h_post(u, a, b, h, i, j)
  41. l *= -a_i
  42. return l_b_i
  43. def theta_j_eap(u, a_estimated, b_estimated, j):
  44. e_tmp1 = 0.0
  45. for h in H:
  46. e += X(h) * L(u, a_estimated, b_estimated, h, j) * A(X(h))
  47. e_tmp1 += L(u, a_estimated, b_estimated, h, j) * A(X(h))
  48. e /= e_tmp1
  49. return e
  50.  
  51. csv_obj = csv.render(open("data.csv", "r"))
  52. reader = csv.reader(f)
  53. data = [ v for v in csv_obj]
  54.  
  55. a = [0.0 for i in range(I)]
  56. b = [0.0 for i in range(I)]
  57. theta = [0.0 for j in range(J)]
  58.  
  59. while end == false:
  60. end = false
  61. for i in range(I):
  62. grad = likelihood_a_i(u, a[i], b[i], i)
  63. a[i] += 0.001 * grad
  64. if abs() > 10.0:
  65. a[i] = random.uniform(-5,5)
  66. end = false
  67. if grad < 0.0001:
  68. a_estimated[i] = a[i]
  69. else:
  70. end = false
  71. for i in range(I):
  72. grad = likelihood_b_i(u, a[i], b[i], i)
  73. b[i] += 0.001 * grad
  74. if abs() > 10.0:
  75. b[i] = random.uniform(-5,5)
  76. end = false
  77. if grad < 0.0001:
  78. b_estimated[i] = b[i]
  79. else:
  80. end = false
  81.  
  82. for j in J:
  83. theta[j] = theta_j_eap(a_estimated, b_estimated)
  84.  
  85. for i in I:
  86. print str(a_estimated[i])
  87. print str(b_estimated[i])
  88. for j in J:
  89. print str(theta_estimated[j])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement