python - 使用自举库查找自举置信区间

标签 python confidence-interval statistics-bootstrap

让我们假设我有一个正态分布的样本数据数组。我想要的是计算另一个样本小于 -3 的概率,并为该概率提供一个自举置信区间。在做了一些研究之后,我找到了我想用来查找 CI 的 bootstrapped 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。

最佳答案

我遵循了 bootstrapped 包中的 stat_functions.mean 示例。它下面被包裹在一个“工厂”中,这样​​你就可以指定你想要计算频率的级别(遗憾的是你不能将它作为可选参数传递给 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

所以这一切看起来都是一致的。

关于python - 使用自举库查找自举置信区间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64897948/

相关文章:

python - 如何在通过检查第一个 pygame.MOUSEBUTTONDOWN 开始的循环内检测第二个 pygame.MOUSEBUTTONDOWN

python - Windows 的 Python 中包含 json 包吗?

python - Python 的 HackerRank "filled orders"问题

python - 是否有任何内置的 lambda for is notNone in python

python - scipy.stats.lognorm.interval 的倒数

r - 使用 rq 函数计算 R 中分位数回归的 95% 置信区间

r - ggplot中中位数置信区间的计算

r - 使用 ggplot2 用丝带绘制两条线

r - 在 R 中按组引导结果向量

R:使用新 lme4 包的 bootMer() 引导二进制混合模型逻辑回归