正态分布样本的置信区间

时间:2018-04-11 07:56:31

标签: python matplotlib jupyter statsmodels confidence-interval

我想找出遵循正态分布的样本的置信区间。

为了测试代码,我先创建一个样本并尝试在Jupyter笔记本中绘制置信区间图[python kernel]

%matplotlib notebook

import pandas as pd
import numpy as np
import statsmodels.stats.api as sms
import matplotlib.pyplot as plt

s= np.random.normal(0,1,2000)
# s= range(10,14)                   <---this sample has the right CI
# s = (0,0,1,1,1,1,1,2)             <---this sample has the right CI

# confidence interval
# I think this is the fucniton I misunderstand
ci=sms.DescrStatsW(s).tconfint_mean()

plt.figure()
_ = plt.hist(s,  bins=100)

# cnfidence interval left line
one_x12, one_y12 = [ci[0], ci[0]], [0, 20]
# cnfidence interval right line
two_x12, two_y12 = [ci[1], ci[1]], [0, 20]

plt.plot(one_x12, one_y12, two_x12, two_y12, marker = 'o')

绿线和黄线假设为置信区间。但他们并没有处于正确的位置。

我可能会误解这个功能:

sms.DescrStatsW(s).tconfint_mean()

但文件说这个函数会返回置信区间。

enter image description here

这是我期望的数字:

%matplotlib notebook

import pandas as pd
import numpy as np
import statsmodels.stats.api as sms
import matplotlib.pyplot as plt

s= np.random.normal(0,1,2000)


plt.figure()
_ = plt.hist(s,  bins=100)
# cnfidence interval left line
one_x12, one_y12 = [np.std(s, axis=0) * -1.96, np.std(s, axis=0) * -1.96], [0, 20]
# cnfidence interval right line
two_x12, two_y12 = [np.std(s, axis=0) * 1.96, np.std(s, axis=0) * 1.96], [0, 20]

plt.plot(one_x12, one_y12, two_x12, two_y12, marker = 'o')

enter image description here

1 个答案:

答案 0 :(得分:1)

问题看起来像#34;有什么函数来计算置信区间&#34;。

由于给定的数据是正态分布,这可以通过

简单地完成
ci = scipy.stats.norm.interval(0.95, loc=0, scale=1)

0.95是α值,它指定了95个百分点,因为公式中给出了相应的1.96标准偏差。 (https://en.wikipedia.org/wiki/1.96

loc=0指定平均值,scale=1指定sigma。 (https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule

您可以查看@bogatron的答案,详细了解Compute a confidence interval from sample data

以下代码生成您想要的图表。我将随机数播种为可重复性。

import pandas as pd
import numpy as np
import statsmodels.stats.api as sms
import matplotlib.pyplot as plt
import scipy

s = np.random.seed(100)
s= np.random.normal(0,1,2000)

plt.figure()
_ = plt.hist(s,  bins=100)

sigma=1
mean=0
ci = scipy.stats.norm.interval(0.95, loc=mean, scale=sigma)
print(ci)

# cnfidence interval left line
one_x12, one_y12 = [ci[0],ci[0]], [0, 20]
# cnfidence interval right line
two_x12, two_y12 = [ci[1],ci[1]], [0, 20]

plt.plot(one_x12, one_y12, two_x12, two_y12, marker = 'o')

ci返回

(-1.959963984540054, 1.959963984540054)

这是情节。

enter image description here