def __init__(self, name, parent, samples, alpha, pi, freezer, logspace=False): Interval.__init__(self, samples, alpha, ndim=1) self.name = name self.parent = parent # method for computing p(theta | data) self.pi = pi self.freezer = freezer # compute the hpd interval # Adapted from "Monte Carlo Estimation of Bayesian Credible and HPD Intervals", Ming-Hui Chen and Qi-Man Shao, 1999 # self.epsilon = [self.pi(t) for t in self.samples] self.epsilon = [self.compute_pi(sample=t) for t in self.samples] self.epsilon.sort() j = int(self.n * self.alpha) self.epj = self.epsilon[ j] # any observation with pi(x|D) > epj is in the region self.paramSamples = [s[parent][name] for s in self.samples] self.paramSamples.sort() self.lb = self.paramSamples[int(self.n * self.alpha)] self.ub = self.paramSamples[int(self.n * (1 - self.alpha))]
def __init__(self, samples, alpha, start=1e-6, tol=1e-6, maxiter=100): Interval.__init__(self, samples, alpha, ndim=1) p = samples.n alphaPotential = 1. * np.arange(self.n) / self.n self.alpha = filter( lambda x: abs(x - self.alpha) == abs(self.alpha - alphaPotential). min(), alphaPotential)[0] self.mean = samples.array.mean(0) self.std = samples.array.std(0) self.lb, self.ub = self.mean - 2 * self.std, self.mean + 2 * self.std self.epsilon = start # function to calculate the empirical interval alpha for a given epsilon, x check = lambda x: 1. * sum( (self.samples.array > self.lb - x).all(1) & (self.samples.array < self.ub + x).all(1)) / self.n bounds = [] # double to find lower and upper epislon bound while check(self.epsilon) < self.alpha: bounds.append((self.epsilon, check(self.epsilon))) self.epsilon *= 2 bounds.append((self.epsilon, check(self.epsilon))) # binary search eLb, eUb = self.epsilon / 2, self.epsilon i = 0 while True: if abs(check(eLb) - alpha) < tol: self.epsilon = eLb break elif abs(check(eUb) - alpha) < tol: self.epsilon = eUb break nb = (eLb + eUb) / 2 if check(nb) < alpha: eLb = nb bounds.append((nb, check(nb))) else: eUb = nb bounds.append((nb, check(nb))) i += 1 if i > maxiter: self.epsilon = eLb break self.bounds = bounds self.lb = self.mean - self.std - self.epsilon self.ub = self.mean + self.std + self.epsilon