📚 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"""67import thinkbayes8import thinkplot910from thinkbayes import Pmf, Percentile11from dice import Dice121314class Train(Dice):15"""Represents hypotheses about how many trains the company has."""161718class Train2(Dice):19"""Represents hypotheses about how many trains the company has."""2021def __init__(self, hypos, alpha=1.0):22"""Initializes the hypotheses with a power law distribution.2324hypos: sequence of hypotheses25alpha: parameter of the power law prior26"""27Pmf.__init__(self)28for hypo in hypos:29self.Set(hypo, hypo**(-alpha))30self.Normalize()313233def MakePosterior(high, dataset, constructor):34"""Makes and updates a Suite.3536high: upper bound on the range of hypotheses37dataset: observed data to use for the update38constructor: function that makes a new suite3940Returns: posterior Suite41"""42hypos = xrange(1, high+1)43suite = constructor(hypos)44suite.name = str(high)4546for data in dataset:47suite.Update(data)4849return suite505152def ComparePriors():53"""Runs the analysis with two different priors and compares them."""54dataset = [60]55high = 10005657thinkplot.Clf()58thinkplot.PrePlot(num=2)5960constructors = [Train, Train2]61labels = ['uniform', 'power law']6263for constructor, label in zip(constructors, labels):64suite = MakePosterior(high, dataset, constructor)65suite.name = label66thinkplot.Pmf(suite)6768thinkplot.Save(root='train4',69xlabel='Number of trains',70ylabel='Probability')7172def main():73ComparePriors()7475dataset = [30, 60, 90]7677thinkplot.Clf()78thinkplot.PrePlot(num=3)7980for high in [500, 1000, 2000]:81suite = MakePosterior(high, dataset, Train2)82print high, suite.Mean()8384thinkplot.Save(root='train3',85xlabel='Number of trains',86ylabel='Probability')8788interval = Percentile(suite, 5), Percentile(suite, 95)89print interval9091cdf = thinkbayes.MakeCdfFromPmf(suite)92interval = cdf.Percentile(5), cdf.Percentile(95)93print interval949596if __name__ == '__main__':97main()9899100