ana*_*cat 5 python matplotlib confidence-interval boxplot seaborn
首先,我必须承认我的统计知识充其量是生锈的:即使它刚刚崭露头角,也不是我特别喜欢的学科,这意味着我很难理解它。
不过,我看了一下柱状图如何计算误差线,并惊讶地发现使用“置信区间”(CI)代替(更常见的)标准偏差。对更多CI的研究使我想到了这篇Wikipedia文章,该文章似乎说,基本上,CI的计算公式为:


或者,使用伪代码:
def ci_wp(a):
"""calculate confidence interval using Wikipedia's formula"""
m = np.mean(a)
s = 1.96*np.std(a)/np.sqrt(len(a))
return m - s, m + s
Run Code Online (Sandbox Code Playgroud)
但是我们在seaborn / utils.py中发现的是:
def ci(a, which=95, axis=None):
"""Return a percentile range from an array of values."""
p = 50 - which / 2, 50 + which / 2
return percentiles(a, p, axis)
Run Code Online (Sandbox Code Playgroud)
现在也许我完全错过了,但是这似乎与Wikipedia提出的计算完全不同。谁能解释这个差异?
再举一个例子,从评论中,我们为什么在以下情况之间得到如此不同的结果:
>>> sb.utils.ci(np.arange(100))
array([ 2.475, 96.525])
>>> ci_wp(np.arange(100))
[43.842250270646467,55.157749729353533]
Run Code Online (Sandbox Code Playgroud)
并与其他统计工具进行比较:
def ci_std(a):
"""calculate margin of error using standard deviation"""
m = np.mean(a)
s = np.std(a)
return m-s, m+s
def ci_sem(a):
"""calculate margin of error using standard error of the mean"""
m = np.mean(a)
s = sp.stats.sem(a)
return m-s, m+s
Run Code Online (Sandbox Code Playgroud)
这给了我们:
>>> ci_sem(np.arange(100))
(46.598850802411796, 52.401149197588204)
>>> ci_std(np.arange(100))
(20.633929952277882, 78.366070047722118)
Run Code Online (Sandbox Code Playgroud)
或带有随机样本:
rng = np.random.RandomState(10)
a = rng.normal(size=100)
print sb.utils.ci(a)
print ci_wp(a)
print ci_sem(a)
print ci_std(a)
Run Code Online (Sandbox Code Playgroud)
...产生:
[-1.9667006 2.19502303]
(-0.1101230745774124, 0.26895640045116026)
(-0.017774461397903049, 0.17660778727165088)
(-0.88762281417683186, 1.0464561400505796)
Run Code Online (Sandbox Code Playgroud)
为什么Seaborn的数字与其他结果如此根本不同?
使用此Wikipedia公式进行的计算是完全正确的。Seaborn只是使用另一种方法:https ://en.wikipedia.org/wiki/Bootstrapping_(statistics )。Dragicevic [1]对此进行了很好的描述:
[它]包括通过随机绘制替换观察值从实验数据中生成许多备用数据集。假设这些数据集之间的可变性近似于采样误差,并用于计算所谓的自举置信区间。[...]它非常通用,可用于多种发行版。
在Seaborn的源代码,一个barplot用途estimate_statistic,其自举数据然后计算在其上的置信区间:
>>> sb.utils.ci(sb.algorithms.bootstrap(np.arange(100)))
array([43.91, 55.21025])
Run Code Online (Sandbox Code Playgroud)
结果与您的计算一致。
[1] Dragicevic,P.(2016年)。人机交互中公平的统计交流。在《 HCI的现代统计方法》(第291-330页)中。湛史普林格。
您需要检查百分位数的代码。您发布的seaborn ci代码只是计算百分位数限制。该区间的定义平均值为 50(中位数),默认范围为95% 置信区间。实际平均值、标准差等将出现在百分位数例程中。