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

标签 python numpy statistics machine-learning

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

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

如何在 Python 中进行这样的比较?我知道如何在 matplotlib 中绘制图形,但在这里我不知道我应该使用哪种类型的图形。

最佳答案

鉴于评论中的评论,我猜您正在寻找类似以下内容的内容:

import numpy as np
import matplotlib.pyplot as plt

def plot_exponential_density(mu, xmax, fmt, label):
        x = np.arange(0, xmax, 0.1)
        y = 1/mu * np.exp(-x/mu)
        plt.plot(x, y, fmt, label=label)

def sample_and_plot(N, color):
        # first sample N valus
        samples = np.zeros( (N,1) )
        for i in range(0,N):
                samples[i] = np.random.exponential()

        # determine the mean
        mu = np.mean(samples)
        print("N = %d  ==> mu = %f" % (N, mu))

        # plot a histogram of the samples
        (n, bins) = np.histogram(samples, bins=int(np.sqrt(N)), density=True)
        plt.step(bins[:-1], n, color=color, label="samples N = %d" % N)

        xmax = max(bins)

        # plot the density according to the estimated mean
        plot_exponential_density(mu, xmax, color + "--", label="estimated density N = %d" % N)

        return xmax


# sample 100 values, draw a histogram, and the density according to
# the estimated mean
xmax1 = sample_and_plot(100, 'r')
# do the same for 1000 samples
xmax2 = sample_and_plot(10000, 'b')

# finally plot the true density
plot_exponential_density(1, max(xmax1, xmax2), 'k', "true density")

# add a legend
plt.legend()

# and show the plot
plt.show()

enter image description here

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

关于python - 如何在 Python 中绘制最大似然估计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7897251/

相关文章:

python - 无法在 Python 3.7 中导入名称 'etree',我怎样才能让它工作?

python - 如何在没有循环的情况下修改特定位置的 2D numpy 数组?

powershell - 在 PowerShell 中查找数据集的统计模式

Python 脚本给出 `: No such file or directory`

python - 将代码复制到word文档中并保持格式

python - 更改类中的 kivy 小部件属性

python - 在Python中对一系列数据进行分类的最佳方法

python - 当我在内部使用两个循环时,如何提高算法的效率?

java - 在给定其他先验概率的情况下估计概率

python - 使用python分析抛硬币统计