如何在Python中绘制最大似然估计值

前端之家收集整理的这篇文章主要介绍了如何在Python中绘制最大似然估计值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在从exponential distribution中抽取一些样本.在我的第一个实验中,我正在绘制1000个样本,而在第二个实验中,我正在从该分布中抽取10,000个样本. (使用numpy.random.exponential)

我想直观地比较两次实验的最大似然估计的差异. (因为这是指数分布,MLE将只是样本均值,所以在我的第二个实验中,MLE应该更接近真实密度).

我怎样才能在Python中进行这样的比较?我知道如何在matplotlib中绘制图形,但在这里我不知道应该使用什么类型的图形.

最佳答案
鉴于评论中的评论,我想以下是您正在寻找的内容

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. def plot_exponential_density(mu,xmax,fmt,label):
  4. x = np.arange(0,0.1)
  5. y = 1/mu * np.exp(-x/mu)
  6. plt.plot(x,y,label=label)
  7. def sample_and_plot(N,color):
  8. # first sample N valus
  9. samples = np.zeros( (N,1) )
  10. for i in range(0,N):
  11. samples[i] = np.random.exponential()
  12. # determine the mean
  13. mu = np.mean(samples)
  14. print("N = %d ==> mu = %f" % (N,mu))
  15. # plot a histogram of the samples
  16. (n,bins) = np.histogram(samples,bins=int(np.sqrt(N)),density=True)
  17. plt.step(bins[:-1],n,color=color,label="samples N = %d" % N)
  18. xmax = max(bins)
  19. # plot the density according to the estimated mean
  20. plot_exponential_density(mu,color + "--",label="estimated density N = %d" % N)
  21. return xmax
  22. # sample 100 values,draw a histogram,and the density according to
  23. # the estimated mean
  24. xmax1 = sample_and_plot(100,'r')
  25. # do the same for 1000 samples
  26. xmax2 = sample_and_plot(10000,'b')
  27. # finally plot the true density
  28. plot_exponential_density(1,max(xmax1,xmax2),'k',"true density")
  29. # add a legend
  30. plt.legend()
  31. # and show the plot
  32. plt.show()

我使用了100和10,000个样本,因为有1,估计已经相当不错了.但是仍然只有100个样本,我有点惊讶于平均值和密度的估计有多好.鉴于直方图没有知道样本是从指数分布中提取的,我不确定我会在这里识别出指数分布……

猜你在找的Python相关文章