开始使用免费开始使用

自助法构建置信区间

评估数据变异性的一种有用工具是自助法(bootstrap)。在本练习中,您将编写自己的自助法函数,用来返回一个自助法置信区间。

该函数包含 3 个参数:一个 2 维数值数组(data)、需要计算的百分位数列表(percentiles),以及要进行的自助迭代次数(n_boots)。它使用 resample 函数生成一次自助样本,然后重复多次以计算置信区间。

本练习是课程的一部分

Python 中的时间序列机器学习

查看课程

练习说明

  • 该函数应按自助次数参数(n_boots)进行循环,并执行:
    • 对数据进行一次有放回的随机抽样,并计算该随机样本的均值
    • 计算 bootstrap_means 的百分位数并返回

交互式实操练习

通过完成这段示例代码来试试这个练习。

from sklearn.utils import ____

def bootstrap_interval(data, percentiles=(2.5, 97.5), n_boots=100):
    """Bootstrap a confidence interval for the mean of columns of a 2-D dataset."""
    # Create our empty array to fill the results
    bootstrap_means = np.zeros([n_boots, data.shape[-1]])
    for ii in range(____):
        # Generate random indices for our data *with* replacement, then take the sample mean
        random_sample = ____
        bootstrap_means[ii] = random_sample.mean(axis=0)
        
    # Compute the percentiles of choice for the bootstrapped means
    percentiles = ____(bootstrap_means, percentiles, axis=0)
    return percentiles
编辑并运行代码