Bootstrap的直白说明

712 查看

bootstrap不是twitter的那个前端,而是统计学中的概念,下边随实验进行说明
假设有个事件,共发生了10000000次,发生的概率呈泊松分布。当然,假设我们是不知道他是泊松分布的

import numpy as np
import scipy.stats
ALL = np.random.poisson(2, size=10000000)
ALL.mean() # 2.005085!
ALL.var()  # 2.0007084414277481

x = np.arange(0, 20)
y = scipy.stats.poisson(2).pmf(x)
import matplotlib.pyplot as plt
fig = plt.figure()
plot = fig.add_subplot(111)
plot.plot(x, y)

我们只知道它的一个采样,从这个采样中看不出来什么,比如其均值都不对

SAMPLE = np.random.choice(ALL, size=20)
# array([1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 2, 1, 4, 2, 5, 2])
SAMPLE.mean()
# 1.3500000000000001

现在使用bootstrap(其中的一种,resampling),从SAMPLE中重复采样,然后计算平均值,这样就可以计算置信区间了。

samples = [ np.random.choice(SAMPLE, size=20) for i in range(1000) ]
means = [ s.mean() for s in samples ]
plot.hist(means, bins=30)

可以多来几次

def plot_hist():
    fig = plt.figure()
    plot1 = fig.add_subplot(221)
    plot2 = fig.add_subplot(222)
    plot3 = fig.add_subplot(223)
    plot4 = fig.add_subplot(224)
    for plot in (plot1, plot2, plot3, plot4):
        SAMPLE = np.random.choice(ALL, size=50)
        samples = [ np.random.choice(SAMPLE, size=20) for i in range(1000) ]
        means = [ s.mean() for s in samples ]
        plot.clear()
        plot.hist(means, bins=30)
    return fig

可以看出SAMPLE的随机性还是对最终的图形有很大影响的。但是在此计算假设检验的话,基本上都靠谱。