{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Bayesian Statistics Made Simple\n", "\n", "Code and exercises from my workshop on Bayesian statistics in Python.\n", "\n", "Copyright 2020 Allen Downey\n", "\n", "MIT License: https://opensource.org/licenses/MIT" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "import seaborn as sns" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The Bayesian bandit problem\n", "\n", "Suppose you have several \"one-armed bandit\" slot machines, and there's reason to think that they have different probabilities of paying off.\n", "\n", "Each time you play a machine, you either win or lose, and you can use the outcome to update your belief about the probability of winning.\n", "\n", "Then, to decide which machine to play next, you can use the \"Bayesian bandit\" strategy, explained below.\n", "\n", "First, let's see how to do the update." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The prior\n", "\n", "If we know nothing about the probability of wining, we can start with a uniform prior." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "xs = np.linspace(0, 1, 101)\n", "prior = pd.Series(1/101, index=xs)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here's what it looks like." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "def decorate_bandit(title):\n", " \"\"\"Labels the axes.\n", " \n", " title: string\n", " \"\"\"\n", " plt.xlabel('Probability of winning')\n", " plt.ylabel('PMF')\n", " plt.title(title)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "prior.plot()\n", "decorate_bandit('Prior distribution')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The update\n", "\n", "The following function takes a prior distribution and an outcome, either `'W'` or `'L'`.\n", "\n", "It does a Bayesian update in place; that is, it modifies the distribution based on the outcome." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "def update(pmf, data):\n", " \"\"\"Likelihood function for Bayesian bandit\n", " \n", " pmf: Series that maps hypotheses to probabilities\n", " data: string, either 'W' or 'L'\n", " \"\"\"\n", " xs = pmf.index\n", " if data == 'W':\n", " pmf *= xs\n", " else:\n", " pmf *= 1-xs\n", " \n", " pmf /= pmf.sum()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here's an example that starts with a uniform prior and updates with one win and one loss." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "bandit = prior.copy()\n", "update(bandit, 'W')\n", "update(bandit, 'L')\n", "bandit.plot()\n", "decorate_bandit('Posterior distribution, 1 loss, 1 win')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise 1\n", "\n", "Suppose you play a machine 10 times and win once. What is the posterior distribution of $x$?" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Multiple bandits" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now suppose we have several bandits and we want to decide which one to play.\n", "\n", "For this example, we have 4 machines with these probabilities:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "actual_probs = [0.10, 0.20, 0.30, 0.40]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The function `play` simulates playing one machine once and returns `W` or `L`." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "from collections import Counter\n", "\n", "# count how many times we've played each machine\n", "counter = Counter()\n", "\n", "def flip(p):\n", " \"\"\"Return True with probability p.\"\"\"\n", " return np.random.random() < p\n", "\n", "def play(i):\n", " \"\"\"Play machine i.\n", " \n", " returns: string 'W' or 'L'\n", " \"\"\"\n", " counter[i] += 1\n", " p = actual_probs[i]\n", " if flip(p):\n", " return 'W'\n", " else:\n", " return 'L'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here's a test, playing machine 3 twenty times:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "for i in range(20):\n", " result = play(3)\n", " print(result, end=' ')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`counter` keeps track of how many times each machine has been played." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "counter" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now I'll make four copies of the prior to represent our beliefs about the four machines." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "machines = [prior.copy() for i in range(4)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This function displays four distributions in a grid." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "options = dict(xticklabels='invisible', yticklabels='invisible')\n", "\n", "def plot(machines, **options):\n", " for i, m in enumerate(machines):\n", " plt.subplot(2, 2, i+1)\n", " m.plot(label='Machine %s' % i)\n", " plt.gca().set_yticklabels([])\n", " plt.legend()\n", " \n", " plt.tight_layout()" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "scrolled": true }, "outputs": [], "source": [ "plot(machines)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise 2\n", "\n", "Write a nested loop that plays each machine 10 times and updates them based on the results; then plot the posterior distributions. \n", "\n", "Hint: call `play` and then `update`." ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "After playing each machine 10 times, we can summarize `machines` by printing the posterior mean and credible interval:" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "def pmf_mean(pmf):\n", " \"\"\"Compute the mean of a PMF.\n", " \n", " pmf: Series representing a PMF\n", " \n", " return: float\n", " \"\"\"\n", " return np.sum(pmf.index * pmf)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "from scipy.interpolate import interp1d\n", "\n", "def credible_interval(pmf, prob):\n", " \"\"\"Compute the mean of a PMF.\n", " \n", " pmf: Series representing a PMF\n", " prob: probability of the interval\n", " \n", " return: pair of float\n", " \"\"\"\n", " # make the CDF\n", " xs = pmf.index\n", " ys = pmf.cumsum()\n", " \n", " # compute the probabilities\n", " p = (1-prob)/2\n", " ps = [p, 1-p]\n", " \n", " # interpolate the inverse CDF\n", " options = dict(bounds_error=False,\n", " fill_value=(xs[0], xs[-1]), \n", " assume_sorted=True)\n", " interp = interp1d(ys, xs, **options)\n", " return interp(ps)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "for i, m in enumerate(machines):\n", " print(pmf_mean(m), credible_interval(m, 0.9))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Bayesian Bandits\n", "\n", "To get more information, we could play each machine 100 times, but while we are gathering data, we are not making good use of it. The kernel of the Bayesian Bandits algorithm is that it collects and uses data at the same time. In other words, it balances exploration and exploitation.\n", "\n", "The following function chooses among the machines so that the probability of choosing each machine is proportional to its \"probability of superiority\"." ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "def pmf_choice(pmf):\n", " \"\"\"Draw a random sample from a PMF.\n", " \n", " pmf: Series representing a PMF\n", " \n", " returns: quantity from PMF\n", " \"\"\"\n", " return np.random.choice(pmf.index, p=pmf)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "def choose(machines):\n", " \"\"\"Use the Bayesian bandit strategy to choose a machine.\n", " \n", " Draws a sample from each distributions.\n", " \n", " returns: index of the machine that yielded the highest value\n", " \"\"\"\n", " ps = [pmf_choice(m) for m in machines]\n", " return np.argmax(ps)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This function chooses one value from the posterior distribution of each machine and then uses `argmax` to find the index of the machine that chose the highest value.\n", "\n", "Here's an example." ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "choose(machines)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The strategy\n", "\n", "Putting it all together, the following function chooses a machine, plays once, and updates `machines`:" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "def choose_play_update(machines, verbose=False):\n", " \"\"\"Chose a machine, play it, and update machines.\n", " \n", " machines: list of Pmf objects\n", " verbose: Boolean, whether to print results\n", " \"\"\"\n", " # choose a machine\n", " i = choose(machines)\n", " \n", " # play it\n", " outcome = play(i)\n", " \n", " # update beliefs\n", " update(machines[i], outcome)\n", " \n", " if verbose:\n", " print(i, outcome, pmf_mean(machines[i]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here's an example" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "choose_play_update(machines, verbose=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Trying it out" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's start again with a fresh set of machines and an empty `Counter`." ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "machines = [prior.copy() for i in range(4)]\n", "counter = Counter()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we run the bandit algorithm 100 times, we can see how `machines` gets updated:" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [], "source": [ "num_plays = 100\n", "\n", "for _ in range(num_plays):\n", " choose_play_update(machines)\n", " \n", "plot(machines)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can summarize `machines` by printing the posterior mean and credible interval:" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "for i, m in enumerate(machines):\n", " print(pmf_mean(m), credible_interval(m, 0.9))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The credible intervals usually contain the true values (0.1, 0.2, 0.3, and 0.4).\n", "\n", "The estimates are still rough, especially for the lower-probability machines. But that's a feature, not a bug: the goal is to play the high-probability machines most often. Making the estimates more precise is a means to that end, but not an end itself.\n", "\n", "Let's see how many times each machine got played. If things go according to plan, the machines with higher probabilities should get played more often." ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "for i, count in sorted(counter.items()):\n", " print(i, count)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "### Exercise 3\n", "\n", "Go back and run this section again with a different value of `num_play` and see how it does." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The algorithm I presented in this notebook is called [Thompson sampling](https://en.wikipedia.org/wiki/Thompson_sampling). It is an example of a general strategy called [Bayesian decision theory](https://wiki.lesswrong.com/wiki/Bayesian_decision_theory), which is the idea of using a posterior distribution as part of a decision-making process, usually by choosing an action that minimizes the costs we expect on average (or maximizes the benefits).\n", "\n", "In my opinion, strategies like this are the biggest advantage of Bayesian methods over classical statistics. When we represent knowledge in the form of probability distributions, Bayes's theorem tells us how to change our beliefs as we get more data, and Bayesian decision theory tells us how to use those beliefs to make better decisions." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.5" } }, "nbformat": 4, "nbformat_minor": 1 }