from __future__ import print_function, division import thinkbayes2 class Coin(thinkbayes2.Suite): def Likelihood(self, data, hypo): x = hypo / 100 if data == 'H': return x else: return 1-x suite = Coin(range(0, 101)) import thinkplot thinkplot.Pdf(suite) posterior = suite.Copy() posterior.Update('H') thinkplot.Pdf(posterior) results = 'HTHHTHHHTTHHHTH' for data in results: posterior.Update(data) thinkplot.Pdf(posterior) class Pmf(object): def Normalize(self, fraction=1.0): """Normalizes this PMF so the sum of all probs is fraction. Args: fraction: what the total should be after normalization Returns: the total probability before normalizing """ if self.log: raise ValueError("Normalize: Pmf is under a log transform") total = self.Total() if total == 0.0: raise ValueError('Normalize: total probability is zero.') #logging.warning('Normalize: total probability is zero.') #return total factor = fraction / total for x in self.d: self.d[x] *= factor return total class Suite(Pmf): """Represents a suite of hypotheses and their probabilities.""" def Update(self, data): """Updates each hypothesis based on the data. data: any representation of the data returns: the normalizing constant """ for hypo in self.Values(): like = self.Likelihood(data, hypo) self.Mult(hypo, like) return self.Normalize()