# bayes_vs_frequentist_battle_0.1.py

a guest
Jan 24th, 2020
84
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. #!/usr/bin/env python3
2. import random
3. from typing import Tuple
4. from tqdm import tqdm
5. import typer
6.
7.
8. def avgpos_bayes(l: int, r: int) -> float:
9.     return (l + 1) / (l + r + 2)
10.
11.
12. def avgfreq_pos(l: int, r: int) -> float:
13.     return l / (l + r)
14.
15.
16. def simulate_outcome(num_balls: int) -> Tuple[float, int]:
17.     first_ball = random.random()
18.     l = 0
19.     for _ in range(num_balls):
20.         if random.random() < first_ball:
21.             l += 1
22.     return first_ball, l
23.
24.
25. def one_run(num_balls: int) -> Tuple[float, float]:
26.     actual_pos, l = simulate_outcome(num_balls)
27.     r = num_balls - l
28.     bayes_pos = avgpos_bayes(l, r)
29.     freq_pos = avgfreq_pos(l, r)
30.     bayes_diff = abs(actual_pos - bayes_pos)
31.     freq_diff = abs(actual_pos - freq_pos)
32.     return bayes_diff, freq_diff
33.
34.
35. def main(num_balls: int, num_simulations: int = 1000000):
36.     bayes_diffs_sum = 0
37.     freq_diffs_sum = 0
38.     num_bayes_won = 0
39.     num_freq_won = 0
40.     for _ in tqdm(range(num_simulations)):
41.         bayes_diff, freq_diff = one_run(num_balls)
42.         bayes_diffs_sum += bayes_diff
43.         freq_diffs_sum += freq_diff
44.         num_bayes_won += bayes_diff < freq_diff
45.         num_freq_won += freq_diff < bayes_diff
46.     print(f"simulated {num_balls} balls {num_simulations} times")
47.     print(f"the Bayesian approach won over the Frequentist one {100 * num_bayes_won / num_simulations}% of the times")
48.     ties = num_simulations - (num_bayes_won + num_freq_won)
49.     if ties:
50.         print(f"{100 * ties / num_simulations}% of the simulations were ties, "
51.               f"so {100 * num_freq_won / num_simulations}% were Frequentist wins")
52.     print(f"the mean deviation from the real value for the Bayesian approach was:\t{bayes_diffs_sum / num_simulations}")
53.     print(f"the mean deviation from the real value for the Frequentist approach was:\t{freq_diffs_sum / num_simulations}")
54.
55.
56. if __name__ == "__main__":
57.     typer.run(main)
RAW Paste Data