贝叶斯更新

此动画显示在新数据到达时重新安装的后验估计更新。

垂直线表示绘制的分布应该收敛的理论值。

贝叶斯更新示例

  1. import math
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. from matplotlib.animation import FuncAnimation
  5. def beta_pdf(x, a, b):
  6. return (x**(a-1) * (1-x)**(b-1) * math.gamma(a + b)
  7. / (math.gamma(a) * math.gamma(b)))
  8. class UpdateDist(object):
  9. def __init__(self, ax, prob=0.5):
  10. self.success = 0
  11. self.prob = prob
  12. self.line, = ax.plot([], [], 'k-')
  13. self.x = np.linspace(0, 1, 200)
  14. self.ax = ax
  15. # Set up plot parameters
  16. self.ax.set_xlim(0, 1)
  17. self.ax.set_ylim(0, 15)
  18. self.ax.grid(True)
  19. # This vertical line represents the theoretical value, to
  20. # which the plotted distribution should converge.
  21. self.ax.axvline(prob, linestyle='--', color='black')
  22. def init(self):
  23. self.success = 0
  24. self.line.set_data([], [])
  25. return self.line,
  26. def __call__(self, i):
  27. # This way the plot can continuously run and we just keep
  28. # watching new realizations of the process
  29. if i == 0:
  30. return self.init()
  31. # Choose success based on exceed a threshold with a uniform pick
  32. if np.random.rand(1,) < self.prob:
  33. self.success += 1
  34. y = beta_pdf(self.x, self.success + 1, (i - self.success) + 1)
  35. self.line.set_data(self.x, y)
  36. return self.line,
  37. # Fixing random state for reproducibility
  38. np.random.seed(19680801)
  39. fig, ax = plt.subplots()
  40. ud = UpdateDist(ax, prob=0.7)
  41. anim = FuncAnimation(fig, ud, frames=np.arange(100), init_func=ud.init,
  42. interval=100, blit=True)
  43. plt.show()

下载这个示例