python - 使用自举库查找自举置信区间
问题描述
所以让我们想象一下我有一个正态分布的样本数据数组。我想要的是计算另一个样本小于 -3 的概率,并为该概率提供一个自举置信区间。经过一番研究,我找到了bootstrapped
我想用来查找 CI 的 python 库。
所以我有:
import numpy as np
import bootstrapped.bootstrap as bs
import bootstrapped.stats_functions as bs_stats
mu, sigma = 2.5, 4 # mean and standard deviation
samples = np.random.normal(mu, sigma, 1000)
bs.bootstrap(samples, stat_func= ???)
我应该为 stat_func 写什么?我尝试编写一个 lambda 函数来计算 -3 的概率,但它不起作用。我知道如何计算样本小于 -3 的概率,这只是我很难处理的 CI。
解决方案
我按照包中的示例进行stat_functions.mean
操作bootstrapped
。它的下方被包裹在一个“工厂”中,以便您可以指定要计算频率的级别(遗憾的是,您不能将其作为可选参数传递给bootstrap()
期望的函数)。基本上prob_less_func_factory(level)
返回一个函数,该函数计算您的样本比例小于该值level
。就像我遵循的示例一样,它可以用于矩阵。
def prob_less_func_factory(level = -3.0):
def prob_less_func(values, axis=1):
'''Returns the proportion of samples that are less than the 'level' of each row of a matrix'''
return np.mean(np.asmatrix(values)<level, axis=axis).A1
return prob_less_func
现在你像这样传递它
level = -3
bs_res = bs.bootstrap(samples, stat_func = prob_less_func_factory(level=level))
我得到的结果(你的会略有不同,因为samples
是随机的)是
0.088 (0.06999999999999999, 0.105)
所以boostrap
函数估计(嗯,计算)其中的值的比例samples
小于-3
,0.088
并且它周围的置信区间是(0.06999999999999999, 0.105)
为了检查,我们可以从您的分布中计算一个样本的理论值小于-3
:
from scipy.stats import norm
print(f'Theoretical Prob(N(mean={mu},std={sigma})<{level}): {norm.cdf(level, loc=mu,scale =sigma)}')
我们得到
Theoretical Prob(N(mean=2.5,std=4)<-3): 0.08456572235133569
所以这一切似乎一致一致。
推荐阅读
- html - 嵌套
和,像'
' - excel - 计算最大出现次数并在excel中找到对应的值
- javascript - 如何在没有用户输入的情况下设置 Material UI 滑块的值?
- flutter - DropdownButton 导致空项目异常
- java - Java 命令执行失败
- python - 为什么 model.fit_generator() 有归因错误?
- php - PHP中的PostgreSQL - 发布数据时会话变量似乎自行取消
- swift - 核心数据错误更新多个对象
- node.js - hyperledger fabric 1.4 node sdk 是否依赖于 Node 标准库 API?
- python - Python Selenium - 无法通过 xpath 获取元素