假设分布未知,根据样本数据计算置信区间

Compute a confidence interval from sample data assuming unknown distribution

我有样本数据,我想为其计算置信区间,假设分布不正态且未知。基本上,看起来分布是 Pareto 但我不确定。

正态分布的答案:

Compute a confidence interval from sample data

如果您不知道底层分布,那么我的第一个想法是使用引导程序:https://en.wikipedia.org/wiki/Bootstrapping_(statistics)

在伪代码中,假设 x 是一个包含您的数据的 numpy 数组:

import numpy as np
N = 10000
mean_estimates = []
for _ in range(N):
    re_sample_idx = np.random.randint(0, len(x), x.shape)
    mean_estimates.append(np.mean(x[re_sample_idx]))

mean_estimates 现在是一个包含 10000 个分布均值估计值的列表。取这 10000 个值的第 2.5 个和第 97.5 个百分位数,您的数据均值附近有一个置信区间:

sorted_estimates = np.sort(np.array(mean_estimates))
conf_interval = [sorted_estimates[int(0.025 * N)], sorted_estimates[int(0.975 * N)]]

根据对其他答案的讨论,我假设您想要总体均值的置信区间,是吗? (你必须有一些数量的置信区间,而不是分布本身。)

对于所有具有有限矩的分布,均值的抽样分布渐近地趋于正态分布,均值等于总体均值,方差等于总体方差除以n。因此,如果您有大量数据,$\mu \pm \Phi^{-1}(p) \sigma / \sqrt{n}$ 应该是总体均值的 p 置信区间的良好近似值,即使如果分布不正常。

当前解决方案无效,因为 randint 似乎已被弃用

np.random.seed(10)
point_estimates = []         # Make empty list to hold point estimates

for x in range(200):         # Generate 200 samples
    sample = np.random.choice(a= x, size=x.shape)
    point_estimates.append( sample.mean() )
sorted_estimates = np.sort(np.array(point_estimates))
conf_interval = [sorted_estimates[int(0.025 * N)], sorted_estimates[int(0.975 * N)]]
print(conf_interval, conf_interval[1] - conf_interval[0])
pd.DataFrame(point_estimates).plot(kind="density", legend= False)

您可以使用 bootstrap 来估算同样来自未知分布的每个数量

def bootstrap_ci(
    data, 
    statfunction=np.average, 
    alpha = 0.05, 
    n_samples = 100):

    """inspired by https://github.com/cgevans/scikits-bootstrap"""
    import warnings

    def bootstrap_ids(data, n_samples=100):
        for _ in range(n_samples):
            yield np.random.randint(data.shape[0], size=(data.shape[0],))    
    
    alphas = np.array([alpha/2, 1 - alpha/2])
    nvals = np.round((n_samples - 1) * alphas).astype(int)
    if np.any(nvals < 10) or np.any(nvals >= n_samples-10):
        warnings.warn("Some values used extremal samples; results are probably unstable. "
                      "Try to increase n_samples")

    data = np.array(data)
    if np.prod(data.shape) != max(data.shape):
        raise ValueError("Data must be 1D")
    data = data.ravel()
    
    boot_indexes = bootstrap_ids(data, n_samples)
    stat = np.asarray([statfunction(data[_ids]) for _ids in boot_indexes])
    stat.sort(axis=0)

    return stat[nvals]

模拟帕累托分布的一些数据

np.random.seed(33)
data = np.random.pareto(a=1, size=111)
sample_mean = np.mean(data)

plt.hist(data, bins=25)
plt.axvline(sample_mean, c='red', label='sample mean'); plt.legend()

使用 bootstrapping

为样本均值 生成置信区间
low_ci, up_ci = bootstrap_ci(data, np.mean, n_samples=1000)

绘制结果

plt.hist(data, bins=25)
plt.axvline(low_ci, c='orange', label='low_ci mean')
plt.axvline(up_ci, c='magenta', label='up_ci mean')
plt.axvline(sample_mean, c='red', label='sample mean'); plt.legend()

使用 bootstrapping

为分布参数
生成置信区间
from scipy.stats import pareto

true_params = pareto.fit(data)
low_ci, up_ci = bootstrap_ci(data, pareto.fit, n_samples=1000)

low_ci[0]up_ci[0] 是形状参数

的置信区间
low_ci[0], true_params[0], up_ci[0] ---> (0.8786, 1.0983, 1.4599)