-
Notifications
You must be signed in to change notification settings - Fork 0
/
bootstrap_module.py
74 lines (55 loc) · 2.2 KB
/
bootstrap_module.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import scipy.stats as stat
from math import *
import random, scipy
from random import gauss, randint
from look_up_table import *
dict = look_up_table()
class bootstrap:
def __init__(self,data,n):
self.data = data
self.n = n
def _average(self,X):
return sum(X)/float(len(X))
def mean(self,X):
return sum(X)/float(len(X))
def sample_wr(self,population, k):
"""Chooses k random elements (with replacement) from a population"""
n = len(population)
_random, _int = random.random, int
result = [None] * k
for i in xrange(k):
j = _int(_random() * n)
result[i] = population[j]
return result
def bootstrap(self,statistic, nsamples = 1000):
"""
Arguments:
sample - input sample of values
nsamples - number of samples to generate
samplesize - sample size of each generated sample
statfunc- statistical function to apply to each generated sample.
Performs resampling from sample with replacement, gathers
statistic in a list computed by statfunc on the each generated sample.
"""
if not self.n:
self.n = len(self.data)
X = []
for i in range(nsamples):
resample = self.sample_wr(self.data,self.n)
x = statistic(resample)
X.append(x)
return X
def bootstrapCI(self, statistic, clevel=0.975, N=1000, n=None):
"""Compute bootstrap confidence interval for real-valued statistic."""
results = self.bootstrap(statistic)
try:
results.sort()
except:
results = map(lambda x: x[0], results)
results.sort()
avg = self._average(results)
print "results for plotting in grace avg: %g ub: %g lb:%g for function: %s"%\
(avg,abs(results[975])-abs(avg),abs(avg)-abs(results[25]), str(statistic.__name__))
return (avg,abs(results[975])-abs(avg),abs(avg)-abs(results[25]))
if __name__=='__main__':
pass