自助法分布

20 种产品的在线卖家数量与价格离散度——重抽样相关系数及百分位数和 BCa 95% 置信区间。

自助法分布

自助法(Bootstrap)在从数据中有放回抽取的数千个样本上重新估计统计量;这些估计值的离散程度即为其抽样不确定性。直方图是相关系数的自助法分布,橙色线是在完整样本中观测到的值。上方绘有两个 95% 区间:简单的百分位数区间,以及 BCa(偏差校正加速)区间——后者会发生偏移,以校正此处可见的偏差和偏度:只有 20 种产品时,该分布远非对称。

背景为 Leiter 和 Warin (2012),“Homogenous goods markets: An empirical study of price dispersion on the internet”(International Journal of Economics and Business Research):对 20 种同质产品中的每一种,取在线卖家数量和价格离散度(标价的变异系数,%)。数据由 numpy(固定种子)模拟,仅作示例,并非该论文的数据或结果。scipy.stats.bootstrap(配对,9,999 次重抽样)给出两个区间。

代码及图中文字均为英文。

bootstrap-distribution.py · 49 行
下载 GitHub
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

# Simulated data, set in the context of Leiter & Warin (2012) [leiter2012]
# 20 products: number of online sellers and price dispersion (CV of prices, %)
rng = np.random.default_rng(2012)
x = np.round(rng.lognormal(np.log(15), 0.6, 20))
y = np.clip(14 - 2.8 * np.log(x) + rng.normal(0, 1.6, 20), 1, None)
r_obs = stats.pearsonr(x, y)[0]

# Paired bootstrap of Pearson's r: percentile and BCa intervals from the same resamples
r = lambda a, b, axis=-1: stats.pearsonr(a, b, axis=axis)[0]
boot = {m: stats.bootstrap((x, y), r, paired=True, vectorized=True, n_resamples=9999,
                           method=m, random_state=np.random.default_rng(7))
        for m in ["percentile", "BCa"]}
dist = boot["BCa"].bootstrap_distribution
fisher = np.tanh(np.arctanh(r_obs) + np.array([-1, 1]) * 1.96 / np.sqrt(len(x) - 3))

fig, ax = plt.subplots(figsize=(8, 5))
lo, hi = boot["BCa"].confidence_interval
counts, edges, bars = ax.hist(dist, bins=60, color="#C7C7CC", edgecolor="white", lw=0.4)
for b, left in zip(bars, edges[:-1]):
    if lo <= left + (edges[1] - edges[0]) / 2 <= hi:
        b.set_facecolor("#007AFF"); b.set_alpha(0.75)

# Intervals stacked above the histogram
top = counts.max()
for i, (m, c, name) in enumerate([("percentile", "#8E8E93", "Percentile"),
                                  ("BCa", "#007AFF", "BCa")]):
    a, b = boot[m].confidence_interval
    yy = top * (1.12 + 0.12 * i)
    ax.plot([a, b], [yy, yy], color=c, lw=3, solid_capstyle="butt")
    ax.vlines([a, b], yy - top * 0.03, yy + top * 0.03, color=c, lw=2)
    ax.text(b + 0.015, yy, f"{name} 95% CI  [{a:.2f}, {b:.2f}]", ha="left", va="center",
            fontsize=9.5, color=c, fontweight="semibold")

ax.vlines(r_obs, 0, top * 1.34, color="#FF9500", lw=2, zorder=3)
ax.text(r_obs, top * 1.36, f"observed r = {r_obs:.2f}", ha="center", va="bottom",
        fontsize=9.5, color="#FF9500", fontweight="semibold")
ax.set_xlim(-1, 0)
ax.set_ylim(0, top * 1.46)
ax.set_xlabel("Bootstrap estimate of Pearson's r")
ax.set_ylabel("Resamples")
ax.set_title("More sellers, less price dispersion: a skewed bootstrap distribution", pad=26)
ax.text(0, 1.02, f"Paired bootstrap, B = 9,999 · n = {len(x)} products (simulated) · bias = "
        f"{dist.mean() - r_obs:+.3f} · Fisher-z CI [{fisher[0]:.2f}, {fisher[1]:.2f}]",
        transform=ax.transAxes, fontsize=9.5, color="#6E6E73")
plt.show()

图表使用了可选的 PyStatlas 样式:添加 plt.style.use("pystatlas.mplstyle") 即可完全还原其外观。

数据来源

  • Simulated data. Simulated data with a fixed random seed, created for this example.
    No real respondents, documents or measurements: the numbers only illustrate how the chart and its statistics work.
  • Leiter & Warin (2012), price dispersion on the internet. Leiter, D., & Warin, T. (2012). Homogenous goods markets: An empirical study of price dispersion on the internet. International Journal of Economics and Business Research, 4(5), 514. https://doi.org/10.1504/ijebr.2012.048776
    The example is set in the context of this paper; unless its description says otherwise, the numbers are simulated and are not the paper's data or results.

这些示例用于说明统计方法。除条目另有说明外,其数值均为模拟数据,图表标题描述的是该图在这些模拟数据中呈现的内容——既不是所引论文的结论,也不是作者对实质问题的立场。关于结果、背景和数据,请以此处引用的论文为准。

如何引用

PyStatlas 由 Thierry Warin 创建并维护。如果它对你的工作有所帮助,敬请引用。

Warin, T. (2026). Bootstrap distribution. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/inference-uncertainty/bootstrap-distribution/

@misc{warin2026statlas,
  author       = {Warin, Thierry},
  title        = {PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences},
  year         = {2026},
  version      = {1.1.0},
  howpublished = {\url{https://warin.ca/pystatlas/}},
  note         = {Source code: https://github.com/warint/pystatlas}
}

更多推断与不确定性图表