正态分布样本的置信区间

2024-06-24 13:10:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我想找出服从正态分布的样本的置信区间。在

为了测试代码,我首先创建了一个示例,并尝试在Jupyter notebook[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')

绿线和黄线假设是置信区间。但他们的立场并不正确。在

我可能会误解这个功能:

^{pr2}$

但是文件说这个函数将返回置信区间。在

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


Tags: importrightcimatplotlibasnplineplt
1条回答
网友
1楼 · 发布于 2024-06-24 13:10:03

这个问题看起来像是“有什么函数可以计算置信区间”。在

由于给定数据为正态分布,因此可以通过

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

你可以在Compute a confidence interval from sample data上查看@bogatron的答案


下面的代码生成所需的绘图。我把随机数植入种子中,以保证重复性。在

^{pr2}$

ci返回

(-1.959963984540054, 1.959963984540054)

这是情节。在

enter image description here

相关问题 更多 >