如何使用Python中的numpy.percentile()计算置信区间

问题描述 投票:0回答:1

一个家庭作业问题让我计算一个平均值的置信区间。当我使用传统方法和numpy.percentile()时,我得到了不同的答案。

我认为我可能误解了如何或何时使用np.percentile()。我的两个问题是:1。我使用它是错误的 - 错误的输入等.2。我是否在错误的地方使用它 - 应该用于bootstrap CI而不是常规方法?

我用传统公式和np.percentile()计算了CI


price = np.random.normal(11427, 5845, 30)
# u = mean of orginal vector
# s = std of original vector
print(price)

[14209.99205723 7793.06283131 10403.87407888 10910.59681669 14427.87437741 4426.8122023 13890.22030853 5652.39284669 22436.9686157 9591.28194843 15543.24262609 11951.15170839 16242.64433138 3673.40741792 18962.90840397 11320.92073514 12984.61905211 8716.97883291 15539.80873528 19324.24734807 12507.9268783 11226.36772026 8869.27092532 9117.52393498 11786.21064418 11273.61893921 17093.20022578 10163.75037277 13962.10004709 17094.70579814]

x_bar = np.mean(price) # mean of vector
s = np.std(price) # std of vector
n = len(price) # number of obs
z = 1.96 # for a 95% CI

lower = x_bar - (z * (s/math.sqrt(n)))
upper = x_bar + (z * (s/math.sqrt(n)))
med = np.median(price)

print(lower, med, upper)

10838.458908888499 11868.68117628698 13901.386475143861

np.percentile(price, [2.5, 50, 97.5])

[ 4219.6258866 11868.68117629 20180.24569667]

ss.scoreatpercentile(price, [2.5, 50, 97.5])

[ 4219.6258866 11868.68117629 20180.24569667]

我希望lower,med和upper等于np.percentile()的输出。

虽然中值相同 - 上下相距很远。

此外,scipy.stats.percentile提供与numpy.percentile相同的输出。

有什么想法吗?

谢谢!

编辑显示价格向量。

python numpy confidence-interval percentile
1个回答
0
投票

置信区间和百分位数不是一回事。两件事的公式非常不同

您拥有的样本数量将影响您的置信区间,但不会改变(多)百分位数。

EG

price = np.random.normal(0, 1, 10000)
print (np.percentile(price, [2.5, 50, 97.5])

[-1.97681778  0.01808908  1.93659551]

price = np.random.normal(0, 1, 100000000)
print (np.percentile(price, [2.5, 50, 97.5]))

几乎相同:

[-1.96012643  9.82108813e-05  1.96030460]

但是运行CI计算代码,如果大量增加样本数,您的置信区间将缩小 - 因为您现在95%确信分布的均值位于较小的范围内。

使用相同的2个价格数组(平均值= 0,sd = 1),包含10个样本和10,000个样本,结果如​​下:

-0.5051688819759096 0.17504324224822834 0.744716862363091 # 10 samples
-0.02645090158517636 -0.006759616493022626 0.012353106820212557 # 10000 samples

正如您所看到的,CI更小,样本更多(正如您所期望的那样,给出CI的公式!)

© www.soinside.com 2019 - 2024. All rights reserved.