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

5 投票
1 回答
8898 浏览
提问于 2025-04-17 05:00

我正在从一个叫做指数分布的东西中抽样。在我的第一次实验中,我抽取了1000个样本,而在第二次实验中,我抽取了10,000个样本(使用的是numpy.random.exponential)。

我想直观地比较一下这两次实验的最大似然估计的差异。(因为这是指数分布,所以最大似然估计就是样本的平均值,所以在我的第二次实验中,最大似然估计应该更接近真实的分布情况)。

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

1 个回答

4

根据评论中的内容,我猜您可能在寻找类似下面的东西:

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()

在这里输入图片描述

我使用了100个和10,000个样本,因为用1,000个样本时,估算结果已经相当不错了。不过,即使只有100个样本,我还是有点惊讶于均值的估算结果,以及密度的估算结果竟然这么好。如果仅仅看这个直方图,而不知道这些样本是来自指数分布的,我不确定我能否认出这是一个指数分布……

撰写回答