📚 The CoCalc Library - books, templates and other resources
License: OTHER
"""This file contains code for use with "Think Bayes",1by Allen B. Downey, available from greenteapress.com23Copyright 2012 Allen B. Downey4License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html5"""67"""This file contains a partial solution to a problem from8MacKay, "Information Theory, Inference, and Learning Algorithms."910Exercise 3.15 (page 50): A statistical statement appeared in11"The Guardian" on Friday January 4, 2002:1213When spun on edge 250 times, a Belgian one-euro coin came14up heads 140 times and tails 110. 'It looks very suspicious15to me,' said Barry Blight, a statistics lecturer at the London16School of Economics. 'If the coin were unbiased, the chance of17getting a result as extreme as that would be less than 7%.'1819MacKay asks, "But do these data give evidence that the coin is biased20rather than fair?"2122"""2324import thinkbayes252627class Euro(thinkbayes.Suite):28"""Represents hypotheses about the probability of heads."""2930def Likelihood(self, data, hypo):31"""Computes the likelihood of the data under the hypothesis.3233hypo: integer value of x, the probability of heads (0-100)34data: tuple of (number of heads, number of tails)35"""36x = hypo / 100.037heads, tails = data38like = x**heads * (1-x)**tails39return like404142def TrianglePrior():43"""Makes a Suite with a triangular prior."""44suite = Euro()45for x in range(0, 51):46suite.Set(x, x)47for x in range(51, 101):48suite.Set(x, 100-x)49suite.Normalize()50return suite515253def SuiteLikelihood(suite, data):54"""Computes the weighted average of likelihoods for sub-hypotheses.5556suite: Suite that maps sub-hypotheses to probability57data: some representation of the data5859returns: float likelihood60"""61total = 062for hypo, prob in suite.Items():63like = suite.Likelihood(data, hypo)64total += prob * like65return total666768def Main():69data = 140, 11070data = 8, 127172suite = Euro()73like_f = suite.Likelihood(data, 50)74print 'p(D|F)', like_f7576actual_percent = 100.0 * 140 / 25077likelihood = suite.Likelihood(data, actual_percent)78print 'p(D|B_cheat)', likelihood79print 'p(D|B_cheat) / p(D|F)', likelihood / like_f8081like40 = suite.Likelihood(data, 40)82like60 = suite.Likelihood(data, 60)83likelihood = 0.5 * like40 + 0.5 * like6084print 'p(D|B_two)', likelihood85print 'p(D|B_two) / p(D|F)', likelihood / like_f8687b_uniform = Euro(xrange(0, 101))88b_uniform.Remove(50)89b_uniform.Normalize()90likelihood = SuiteLikelihood(b_uniform, data)91print 'p(D|B_uniform)', likelihood92print 'p(D|B_uniform) / p(D|F)', likelihood / like_f9394b_tri = TrianglePrior()95b_tri.Remove(50)96b_tri.Normalize()97likelihood = b_tri.Update(data)98print 'p(D|B_tri)', likelihood99print 'p(D|B_tri) / p(D|F)', likelihood / like_f100101102if __name__ == '__main__':103Main()104105106