<jupyter_start><jupyter_text>The pair of dice problemCopyright 2018 <NAME>MIT License: https://opensource.org/licenses/MIT<jupyter_code># Configure Jupyter so figures appear in the notebook
%matplotlib inline

# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'

import numpy as np
import pandas as pd

import thinkplot
from thinkbayes2 import Pmf, Suite

from fractions import Fraction<jupyter_output><empty_output><jupyter_text>The BayesTable classHere's the class that represents a Bayesian table.<jupyter_code>class BayesTable(pd.DataFrame):
    def __init__(self, hypo, prior=1, **options):
        columns = ['hypo', 'prior', 'likelihood', 'unnorm', 'posterior']
        super().__init__(columns=columns, **options)
        self.hypo = hypo
        self.prior = prior
    
    def mult(self):
        self.unnorm = self.prior * self.likelihood
        
    def norm(self):
        nc = np.sum(self.unnorm)
        self.posterior = self.unnorm / nc
        return nc
    
    def update(self):
        self.mult()
        return self.norm()
    
    def reset(self):
        return BayesTable(self.hypo, self.posterior)<jupyter_output><empty_output><jupyter_text>The pair of dice problemSuppose I have a box that contains one each of 4-sided, 6-sided, 8-sided, and 12-sided dice.  I choose two dice at random and roll them without letting you see the die or the outcome.  I report that the sum of the dice is 3.1) What is the posterior probability that I rolled each possible pair of the dice?2) If I roll the same dice again, what is the probability that the sum of the dice is 11? **Solution**I'll start by making a list of possible pairs of dice.<jupyter_code>sides = [4, 6, 8, 12]
hypo = []
for die1 in sides:
    for die2 in sides:
        if die2 > die1:
            hypo.append((die1, die2))
            
hypo<jupyter_output><empty_output><jupyter_text>Here's a `BayesTable` that represents the hypotheses.<jupyter_code>table = BayesTable(hypo)<jupyter_output><empty_output><jupyter_text>Since we didn't specify prior probabilities, the default value is equal priors for all hypotheses.  They don't have to be normalized, because we have to normalize the posteriors anyway.Now we can specify the likelihoods: if the first die has `n1` sides and the second die has `n2` sides, the probability of getting a sum of 3 is`2 / n1 / n2`The factor of `2` is there because there are two ways the sum can be 3, either the first die is `1` and the second is `2`, or the other way around.So the likelihoods are:<jupyter_code>for i, row in table.iterrows():
    n1, n2 = row.hypo
    table.loc[i, 'likelihood'] = 2 / n1 / n2
    
table<jupyter_output><empty_output><jupyter_text>Now we can use `update` to compute the posterior probabilities:<jupyter_code>table.update()
table<jupyter_output><empty_output><jupyter_text>Part twoThe second part of the problem asks for the (posterior predictive) probability of getting a total of 11 if we roll the same dice again.For this, it will be useful to write a more general function that computes the probability of getting a total, `k`, given `n1` and `n2`.Here's an example with the `4` and `6` sided dice:<jupyter_code>n1, n2 = 4, 6
d1 = Pmf(range(1, n1+1))
d2 = Pmf(range(1, n2+1))
total = d1 + d2
thinkplot.Hist(total)<jupyter_output><empty_output><jupyter_text>And here's the general function:<jupyter_code>def prob_total(k, n1, n2):
    d1 = Pmf(range(1, n1+1))
    d2 = Pmf(range(1, n2+1))
    total = d1 + d2
    return total[k]<jupyter_output><empty_output><jupyter_text>To check the results, I'll compare them to the likelihoods in the previous table:<jupyter_code>for i, row in table.iterrows():
    n1, n2 = row.hypo
    p = prob_total(3, n1, n2)
    print(n1, n2, p, p == row.likelihood)<jupyter_output>4 6 0.08333333333333333 True
4 8 0.0625 True
4 12 0.041666666666666664 True
6 8 0.041666666666666664 True
6 12 0.027777777777777776 True
8 12 0.020833333333333332 True<jupyter_text>Now we can answer the second part of the question using the law of total probability.  The chance of getting `11` on the second roll is the$\sum_{n1, n2} P(n1, n2 ~|~ D) \cdot P(11 ~|~ n1, n2)$The first term is the posterior probability, which we can read from the table; the second term is `prob_total(11, n1, n2)`.Here's how we compute the total probability:<jupyter_code>total = 0
for i, row in table.iterrows():
    n1, n2 = row.hypo
    p = prob_total(11, n1, n2)
    total += row.posterior * p 
    
total<jupyter_output><empty_output><jupyter_text>This calculation is similar to the first step of the update, so we can also compute it by1) Creating a new table with the posteriors from `table`.2) Adding the likelihood of getting a total of `11` on the next roll.3) Computing the normalizing constant.<jupyter_code>table2 = table.reset()
for i, row in table2.iterrows():
    n1, n2 = row.hypo
    table2.loc[i, 'likelihood'] = prob_total(11, n1, n2)
    
table2
table2.update()
table2<jupyter_output><empty_output><jupyter_text>Using a Suite We can solve this problem more concisely, and more efficiently, using a `Suite`.First, I'll create `Pmf` object for each die.<jupyter_code>dice = {}
for n in sides:
    dice[n] = Pmf(range(1, n+1))<jupyter_output><empty_output><jupyter_text>And a `Pmf` object for the sum of each pair of dice.<jupyter_code>pairs = {}
for n1 in sides:
    for n2 in sides:
        if n2 > n1:
            pairs[n1, n2] = dice[n1] + dice[n2]<jupyter_output><empty_output><jupyter_text>Here's a `Dice` class that implements `Likelihood` by looking up the data, `k`, in the `Pmf` that corresponds to `hypo`:<jupyter_code>class Dice(Suite):
    
    def Likelihood(self, data, hypo):
        """Likelihood of the data given the hypothesis.
        
        data: total of two dice
        hypo: pair of sides
        
        return: probability
        """
        return pairs[hypo][data]<jupyter_output><empty_output><jupyter_text>Here's the prior:<jupyter_code>suite = Dice(pairs.keys())
suite.Print()<jupyter_output>(4, 6) 0.16666666666666666
(4, 8) 0.16666666666666666
(4, 12) 0.16666666666666666
(6, 8) 0.16666666666666666
(6, 12) 0.16666666666666666
(8, 12) 0.16666666666666666<jupyter_text>And the posterior:<jupyter_code>suite.Update(3)
suite.Print()<jupyter_output>(4, 6) 0.3
(4, 8) 0.225
(4, 12) 0.15
(6, 8) 0.15
(6, 12) 0.1
(8, 12) 0.075<jupyter_text>And the posterior probability of getting `11` on the next roll.<jupyter_code>suite.Update(11)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10120776639657544, 'fraction_numerical': 0.06176425622993426, 'mean_word_length': 4.200317965023848, 'pattern_counts': {'":': 0, '<': 67, '<?xml version=': 0, '>': 69, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 11, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '17', 'dir': 'jupyter-structured-clean-dedup', 'id': '349774', 'license': 'MIT', 'n_tokens_mistral': 2511, 'n_tokens_neox': 2235, 'n_words': 761, 'path': 'examples/pair_dice.ipynb', 'repo_name': 'chwebster/ThinkBayes2', 'size': '6547'}