我的意图是让代码在给定列表上执行引导(统计)
样本大小等于列表的长度10,000次,然后计算
95%置信区间。
import numpy
from random import choice
class bootstrapping(object):
def __init__(self,bslist=[],iteration=10000):
self.bslist = bslist
self.iteration = iteration
def CI(self):
listofmeans = []
for numbers in range(0,self.iteration):
bootstraplist = [choice(self.bslist) for _ in range(len(self.bslist))]
listofmeans.append(sum(bootstraplist) / len(bootstraplist))
s = numpy.std(listofmeans)
z = 1.96
n = self.iteration**0.5
lower_confidence = (sum(listofmeans) / len(listofmeans)) - (z*s/n)
upper_confidence = (sum(listofmeans) / len(listofmeans)) + (z*s/n)
return lower_confidence,upper_confidence
test = bootstrapping([60,33,102,53,63,33,42,19,31,86,15,50,
45,47,26,23,30,20,18,48,22,20,17,29,43,52,29],10000)
test.CI()
我得到的置信区间(37.897427638499948,38.102572361500052)是
奇怪地狭窄。当我在Minitab中输入相同的数字列表时,95%
我得到的置信区间是(30.74,47.48)。我做错了什么吗?
最佳答案
要找到95%的置信区间,请z = 1.96
(近似)并计算平均值,正负z*std
的区间,其中是标准偏差。换句话说,使用std
而不是z*std
:
import numpy as np
import random
random.seed(2017)
class Bootstrapping(object):
def __init__(self,bslist=[],iteration=10000):
self.bslist = bslist
self.iteration = iteration
def CI(self):
listofmeans = []
for numbers in range(0,self.iteration):
bootstraplist = [random.choice(self.bslist) for _ in range(len(self.bslist))]
mean = sum(bootstraplist) / len(bootstraplist)
listofmeans.append(mean)
mean = np.mean(listofmeans, axis=0)
std = np.std(listofmeans, axis=0)
z = 1.96
err = z*std
lower_confidence = mean - err
upper_confidence = mean + err
return lower_confidence, upper_confidence
test = Bootstrapping([60,33,102,53,63,33,42,19,31,86,15,50,
45,47,26,23,30,20,18,48,22,20,17,29,43,52,29],10000)
print(test.CI())
产量
(31.309540089458281, 46.876348799430602)
或者,您可以计算置信区间,而无需使用平均值+/- 1.96 * std公式。您可以通过对
z*std/n
进行排序并找到第5个和第95个百分点的值来获得置信区间的经验估计:import random
random.seed(2017)
class Bootstrapping(object):
def __init__(self,bslist=[],iteration=10000):
self.bslist = bslist
self.iteration = iteration
def CI(self):
listofmeans = []
for numbers in range(0,self.iteration):
bootstraplist = [random.choice(self.bslist) for _ in range(len(self.bslist))]
mean = sum(bootstraplist) / len(bootstraplist)
listofmeans.append(mean)
listofmeans = sorted(listofmeans)
a, b = round(self.iteration*0.05), round(self.iteration*0.95)
lower_confidence = listofmeans[a]
upper_confidence = listofmeans[b]
return lower_confidence, upper_confidence
test = Bootstrapping([60,33,102,53,63,33,42,19,31,86,15,50,
45,47,26,23,30,20,18,48,22,20,17,29,43,52,29],10000)
print(test.CI())
产量
(32.888888888888886, 45.888888888888886)
关于python - 我创建了一个类以在引导后返回置信区间,但是我的置信区间看起来很窄。我做错什么了?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41989866/