{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Probability \n", "\n", "This IPy notebook acts as supporting material for topics covered in **Chapter 13 Quantifying Uncertainty**, **Chapter 14 Probabilistic Reasoning**, **Chapter 15 Probabilistic Reasoning over Time**, **Chapter 16 Making Simple Decisions** and parts of **Chapter 25 Robotics** of the book* Artificial Intelligence: A Modern Approach*. This notebook makes use of the implementations in probability.py module. Let us import everything from the probability module. It might be helpful to view the source of some of our implementations. Please refer to the Introductory IPy file for more details on how to do so." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "from probability import *\n", "from utils import print_table\n", "from notebook import psource, pseudocode, heatmap" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## CONTENTS\n", "- Probability Distribution\n", " - Joint probability distribution\n", " - Inference using full joint distributions\n", "
\n", "- Bayesian Networks\n", " - BayesNode\n", " - BayesNet\n", " - Exact Inference in Bayesian Networks\n", " - Enumeration\n", " - Variable elimination\n", " - Approximate Inference in Bayesian Networks\n", " - Prior sample\n", " - Rejection sampling\n", " - Likelihood weighting\n", " - Gibbs sampling\n", "
\n", "- Hidden Markov Models\n", " - Inference in Hidden Markov Models\n", " - Forward-backward\n", " - Fixed lag smoothing\n", " - Particle filtering\n", "
\n", "
\n", "- Monte Carlo Localization\n", "- Decision Theoretic Agent\n", "- Information Gathering Agent" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## PROBABILITY DISTRIBUTION\n", "\n", "Let us begin by specifying discrete probability distributions. The class **ProbDist** defines a discrete probability distribution. We name our random variable and then assign probabilities to the different values of the random variable. Assigning probabilities to the values works similar to that of using a dictionary with keys being the Value and we assign to it the probability. This is possible because of the magic methods **_ _getitem_ _** and **_ _setitem_ _** which store the probabilities in the prob dict of the object. You can keep the source window open alongside while playing with the rest of the code to get a better understanding." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
class ProbDist:\n",
       "    """A discrete probability distribution. You name the random variable\n",
       "    in the constructor, then assign and query probability of values.\n",
       "    >>> P = ProbDist('Flip'); P['H'], P['T'] = 0.25, 0.75; P['H']\n",
       "    0.25\n",
       "    >>> P = ProbDist('X', {'lo': 125, 'med': 375, 'hi': 500})\n",
       "    >>> P['lo'], P['med'], P['hi']\n",
       "    (0.125, 0.375, 0.5)\n",
       "    """\n",
       "\n",
       "    def __init__(self, varname='?', freqs=None):\n",
       "        """If freqs is given, it is a dictionary of values - frequency pairs,\n",
       "        then ProbDist is normalized."""\n",
       "        self.prob = {}\n",
       "        self.varname = varname\n",
       "        self.values = []\n",
       "        if freqs:\n",
       "            for (v, p) in freqs.items():\n",
       "                self[v] = p\n",
       "            self.normalize()\n",
       "\n",
       "    def __getitem__(self, val):\n",
       "        """Given a value, return P(value)."""\n",
       "        try:\n",
       "            return self.prob[val]\n",
       "        except KeyError:\n",
       "            return 0\n",
       "\n",
       "    def __setitem__(self, val, p):\n",
       "        """Set P(val) = p."""\n",
       "        if val not in self.values:\n",
       "            self.values.append(val)\n",
       "        self.prob[val] = p\n",
       "\n",
       "    def normalize(self):\n",
       "        """Make sure the probabilities of all values sum to 1.\n",
       "        Returns the normalized distribution.\n",
       "        Raises a ZeroDivisionError if the sum of the values is 0."""\n",
       "        total = sum(self.prob.values())\n",
       "        if not isclose(total, 1.0):\n",
       "            for val in self.prob:\n",
       "                self.prob[val] /= total\n",
       "        return self\n",
       "\n",
       "    def show_approx(self, numfmt='{:.3g}'):\n",
       "        """Show the probabilities rounded and sorted by key, for the\n",
       "        sake of portable doctests."""\n",
       "        return ', '.join([('{}: ' + numfmt).format(v, p)\n",
       "                          for (v, p) in sorted(self.prob.items())])\n",
       "\n",
       "    def __repr__(self):\n",
       "        return "P({})".format(self.varname)\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(ProbDist)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.75" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p = ProbDist('Flip')\n", "p['H'], p['T'] = 0.25, 0.75\n", "p['T']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The first parameter of the constructor **varname** has a default value of '?'. So if the name is not passed it defaults to ?. The keyword argument **freqs** can be a dictionary of values of random variable: probability. These are then normalized such that the probability values sum upto 1 using the **normalize** method." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'?'" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p = ProbDist(freqs={'low': 125, 'medium': 375, 'high': 500})\n", "p.varname" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(0.125, 0.375, 0.5)" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "(p['low'], p['medium'], p['high'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Besides the **prob** and **varname** the object also separately keeps track of all the values of the distribution in a list called **values**. Every time a new value is assigned a probability it is appended to this list, This is done inside the **_ _setitem_ _** method." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['low', 'medium', 'high']" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.values" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The distribution by default is not normalized if values are added incrementally. We can still force normalization by invoking the **normalize** method." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(50, 114, 64)" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p = ProbDist('Y')\n", "p['Cat'] = 50\n", "p['Dog'] = 114\n", "p['Mice'] = 64\n", "(p['Cat'], p['Dog'], p['Mice'])" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(0.21929824561403508, 0.5, 0.2807017543859649)" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.normalize()\n", "(p['Cat'], p['Dog'], p['Mice'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is also possible to display the approximate values upto decimals using the **show_approx** method." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Cat: 0.219, Dog: 0.5, Mice: 0.281'" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.show_approx()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Joint Probability Distribution\n", "\n", "The helper function **event_values** returns a tuple of the values of variables in event. An event is specified by a dict where the keys are the names of variables and the corresponding values are the value of the variable. Variables are specified with a list. The ordering of the returned tuple is same as those of the variables.\n", "\n", "\n", "Alternatively if the event is specified by a list or tuple of equal length of the variables. Then the events tuple is returned as it is." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(8, 10)" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "event = {'A': 10, 'B': 9, 'C': 8}\n", "variables = ['C', 'A']\n", "event_values(event, variables)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "_A probability model is completely determined by the joint distribution for all of the random variables._ (**Section 13.3**) The probability module implements these as the class **JointProbDist** which inherits from the **ProbDist** class. This class specifies a discrete probability distribute over a set of variables. " ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
class JointProbDist(ProbDist):\n",
       "    """A discrete probability distribute over a set of variables.\n",
       "    >>> P = JointProbDist(['X', 'Y']); P[1, 1] = 0.25\n",
       "    >>> P[1, 1]\n",
       "    0.25\n",
       "    >>> P[dict(X=0, Y=1)] = 0.5\n",
       "    >>> P[dict(X=0, Y=1)]\n",
       "    0.5"""\n",
       "\n",
       "    def __init__(self, variables):\n",
       "        self.prob = {}\n",
       "        self.variables = variables\n",
       "        self.vals = defaultdict(list)\n",
       "\n",
       "    def __getitem__(self, values):\n",
       "        """Given a tuple or dict of values, return P(values)."""\n",
       "        values = event_values(values, self.variables)\n",
       "        return ProbDist.__getitem__(self, values)\n",
       "\n",
       "    def __setitem__(self, values, p):\n",
       "        """Set P(values) = p.  Values can be a tuple or a dict; it must\n",
       "        have a value for each of the variables in the joint. Also keep track\n",
       "        of the values we have seen so far for each variable."""\n",
       "        values = event_values(values, self.variables)\n",
       "        self.prob[values] = p\n",
       "        for var, val in zip(self.variables, values):\n",
       "            if val not in self.vals[var]:\n",
       "                self.vals[var].append(val)\n",
       "\n",
       "    def values(self, var):\n",
       "        """Return the set of possible values for a variable."""\n",
       "        return self.vals[var]\n",
       "\n",
       "    def __repr__(self):\n",
       "        return "P({})".format(self.variables)\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(JointProbDist)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Values for a Joint Distribution is a an ordered tuple in which each item corresponds to the value associate with a particular variable. For Joint Distribution of X, Y where X, Y take integer values this can be something like (18, 19).\n", "\n", "To specify a Joint distribution we first need an ordered list of variables." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "P(['X', 'Y'])" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "variables = ['X', 'Y']\n", "j = JointProbDist(variables)\n", "j" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Like the **ProbDist** class **JointProbDist** also employes magic methods to assign probability to different values.\n", "The probability can be assigned in either of the two formats for all possible values of the distribution. The **event_values** call inside **_ _getitem_ _** and **_ _setitem_ _** does the required processing to make this work." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(0.2, 0.5)" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "j[1,1] = 0.2\n", "j[dict(X=0, Y=1)] = 0.5\n", "\n", "(j[1,1], j[0,1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is also possible to list all the values for a particular variable using the **values** method." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 0]" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "j.values('X')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Inference Using Full Joint Distributions\n", "\n", "In this section we use Full Joint Distributions to calculate the posterior distribution given some evidence. We represent evidence by using a python dictionary with variables as dict keys and dict values representing the values.\n", "\n", "This is illustrated in **Section 13.3** of the book. The functions **enumerate_joint** and **enumerate_joint_ask** implement this functionality. Under the hood they implement **Equation 13.9** from the book.\n", "\n", "$$\\textbf{P}(X | \\textbf{e}) = \\alpha \\textbf{P}(X, \\textbf{e}) = \\alpha \\sum_{y} \\textbf{P}(X, \\textbf{e}, \\textbf{y})$$\n", "\n", "Here **α** is the normalizing factor. **X** is our query variable and **e** is the evidence. According to the equation we enumerate on the remaining variables **y** (not in evidence or query variable) i.e. all possible combinations of **y**\n", "\n", "We will be using the same example as the book. Let us create the full joint distribution from **Figure 13.3**. " ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "full_joint = JointProbDist(['Cavity', 'Toothache', 'Catch'])\n", "full_joint[dict(Cavity=True, Toothache=True, Catch=True)] = 0.108\n", "full_joint[dict(Cavity=True, Toothache=True, Catch=False)] = 0.012\n", "full_joint[dict(Cavity=True, Toothache=False, Catch=True)] = 0.016\n", "full_joint[dict(Cavity=True, Toothache=False, Catch=False)] = 0.064\n", "full_joint[dict(Cavity=False, Toothache=True, Catch=True)] = 0.072\n", "full_joint[dict(Cavity=False, Toothache=False, Catch=True)] = 0.144\n", "full_joint[dict(Cavity=False, Toothache=True, Catch=False)] = 0.008\n", "full_joint[dict(Cavity=False, Toothache=False, Catch=False)] = 0.576" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let us now look at the **enumerate_joint** function returns the sum of those entries in P consistent with e,provided variables is P's remaining variables (the ones not in e). Here, P refers to the full joint distribution. The function uses a recursive call in its implementation. The first parameter **variables** refers to remaining variables. The function in each recursive call keeps on variable constant while varying others." ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def enumerate_joint(variables, e, P):\n",
       "    """Return the sum of those entries in P consistent with e,\n",
       "    provided variables is P's remaining variables (the ones not in e)."""\n",
       "    if not variables:\n",
       "        return P[e]\n",
       "    Y, rest = variables[0], variables[1:]\n",
       "    return sum([enumerate_joint(rest, extend(e, Y, y), P)\n",
       "                for y in P.values(Y)])\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(enumerate_joint)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let us assume we want to find **P(Toothache=True)**. This can be obtained by marginalization (**Equation 13.6**). We can use **enumerate_joint** to solve for this by taking Toothache=True as our evidence. **enumerate_joint** will return the sum of probabilities consistent with evidence i.e. Marginal Probability." ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.19999999999999998" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "evidence = dict(Toothache=True)\n", "variables = ['Cavity', 'Catch'] # variables not part of evidence\n", "ans1 = enumerate_joint(variables, evidence, full_joint)\n", "ans1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can verify the result from our definition of the full joint distribution. We can use the same function to find more complex probabilities like **P(Cavity=True and Toothache=True)** " ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.12" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "evidence = dict(Cavity=True, Toothache=True)\n", "variables = ['Catch'] # variables not part of evidence\n", "ans2 = enumerate_joint(variables, evidence, full_joint)\n", "ans2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Being able to find sum of probabilities satisfying given evidence allows us to compute conditional probabilities like **P(Cavity=True | Toothache=True)** as we can rewrite this as $$P(Cavity=True | Toothache = True) = \\frac{P(Cavity=True \\ and \\ Toothache=True)}{P(Toothache=True)}$$\n", "\n", "We have already calculated both the numerator and denominator." ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.6" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "ans2/ans1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We might be interested in the probability distribution of a particular variable conditioned on some evidence. This can involve doing calculations like above for each possible value of the variable. This has been implemented slightly differently using normalization in the function **enumerate_joint_ask** which returns a probability distribution over the values of the variable **X**, given the {var:val} observations **e**, in the **JointProbDist P**. The implementation of this function calls **enumerate_joint** for each value of the query variable and passes **extended evidence** with the new evidence having **X = xi**. This is followed by normalization of the obtained distribution." ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def enumerate_joint_ask(X, e, P):\n",
       "    """Return a probability distribution over the values of the variable X,\n",
       "    given the {var:val} observations e, in the JointProbDist P. [Section 13.3]\n",
       "    >>> P = JointProbDist(['X', 'Y'])\n",
       "    >>> P[0,0] = 0.25; P[0,1] = 0.5; P[1,1] = P[2,1] = 0.125\n",
       "    >>> enumerate_joint_ask('X', dict(Y=1), P).show_approx()\n",
       "    '0: 0.667, 1: 0.167, 2: 0.167'\n",
       "    """\n",
       "    assert X not in e, "Query variable must be distinct from evidence"\n",
       "    Q = ProbDist(X)  # probability distribution for X, initially empty\n",
       "    Y = [v for v in P.variables if v != X and v not in e]  # hidden variables.\n",
       "    for xi in P.values(X):\n",
       "        Q[xi] = enumerate_joint(Y, extend(e, X, xi), P)\n",
       "    return Q.normalize()\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(enumerate_joint_ask)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let us find **P(Cavity | Toothache=True)** using **enumerate_joint_ask**." ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(0.6, 0.39999999999999997)" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "query_variable = 'Cavity'\n", "evidence = dict(Toothache=True)\n", "ans = enumerate_joint_ask(query_variable, evidence, full_joint)\n", "(ans[True], ans[False])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can verify that the first value is the same as we obtained earlier by manual calculation." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## BAYESIAN NETWORKS\n", "\n", "A Bayesian network is a representation of the joint probability distribution encoding a collection of conditional independence statements.\n", "\n", "A Bayes Network is implemented as the class **BayesNet**. It consisits of a collection of nodes implemented by the class **BayesNode**. The implementation in the above mentioned classes focuses only on boolean variables. Each node is associated with a variable and it contains a **conditional probabilty table (cpt)**. The **cpt** represents the probability distribution of the variable conditioned on its parents **P(X | parents)**.\n", "\n", "Let us dive into the **BayesNode** implementation." ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
class BayesNode:\n",
       "    """A conditional probability distribution for a boolean variable,\n",
       "    P(X | parents). Part of a BayesNet."""\n",
       "\n",
       "    def __init__(self, X, parents, cpt):\n",
       "        """X is a variable name, and parents a sequence of variable\n",
       "        names or a space-separated string.  cpt, the conditional\n",
       "        probability table, takes one of these forms:\n",
       "\n",
       "        * A number, the unconditional probability P(X=true). You can\n",
       "          use this form when there are no parents.\n",
       "\n",
       "        * A dict {v: p, ...}, the conditional probability distribution\n",
       "          P(X=true | parent=v) = p. When there's just one parent.\n",
       "\n",
       "        * A dict {(v1, v2, ...): p, ...}, the distribution P(X=true |\n",
       "          parent1=v1, parent2=v2, ...) = p. Each key must have as many\n",
       "          values as there are parents. You can use this form always;\n",
       "          the first two are just conveniences.\n",
       "\n",
       "        In all cases the probability of X being false is left implicit,\n",
       "        since it follows from P(X=true).\n",
       "\n",
       "        >>> X = BayesNode('X', '', 0.2)\n",
       "        >>> Y = BayesNode('Y', 'P', {T: 0.2, F: 0.7})\n",
       "        >>> Z = BayesNode('Z', 'P Q',\n",
       "        ...    {(T, T): 0.2, (T, F): 0.3, (F, T): 0.5, (F, F): 0.7})\n",
       "        """\n",
       "        if isinstance(parents, str):\n",
       "            parents = parents.split()\n",
       "\n",
       "        # We store the table always in the third form above.\n",
       "        if isinstance(cpt, (float, int)):  # no parents, 0-tuple\n",
       "            cpt = {(): cpt}\n",
       "        elif isinstance(cpt, dict):\n",
       "            # one parent, 1-tuple\n",
       "            if cpt and isinstance(list(cpt.keys())[0], bool):\n",
       "                cpt = {(v,): p for v, p in cpt.items()}\n",
       "\n",
       "        assert isinstance(cpt, dict)\n",
       "        for vs, p in cpt.items():\n",
       "            assert isinstance(vs, tuple) and len(vs) == len(parents)\n",
       "            assert all(isinstance(v, bool) for v in vs)\n",
       "            assert 0 <= p <= 1\n",
       "\n",
       "        self.variable = X\n",
       "        self.parents = parents\n",
       "        self.cpt = cpt\n",
       "        self.children = []\n",
       "\n",
       "    def p(self, value, event):\n",
       "        """Return the conditional probability\n",
       "        P(X=value | parents=parent_values), where parent_values\n",
       "        are the values of parents in event. (event must assign each\n",
       "        parent a value.)\n",
       "        >>> bn = BayesNode('X', 'Burglary', {T: 0.2, F: 0.625})\n",
       "        >>> bn.p(False, {'Burglary': False, 'Earthquake': True})\n",
       "        0.375"""\n",
       "        assert isinstance(value, bool)\n",
       "        ptrue = self.cpt[event_values(event, self.parents)]\n",
       "        return ptrue if value else 1 - ptrue\n",
       "\n",
       "    def sample(self, event):\n",
       "        """Sample from the distribution for this variable conditioned\n",
       "        on event's values for parent_variables. That is, return True/False\n",
       "        at random according with the conditional probability given the\n",
       "        parents."""\n",
       "        return probability(self.p(True, event))\n",
       "\n",
       "    def __repr__(self):\n",
       "        return repr((self.variable, ' '.join(self.parents)))\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(BayesNode)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The constructor takes in the name of **variable**, **parents** and **cpt**. Here **variable** is a the name of the variable like 'Earthquake'. **parents** should a list or space separate string with variable names of parents. The conditional probability table is a dict {(v1, v2, ...): p, ...}, the distribution P(X=true | parent1=v1, parent2=v2, ...) = p. Here the keys are combination of boolean values that the parents take. The length and order of the values in keys should be same as the supplied **parent** list/string. In all cases the probability of X being false is left implicit, since it follows from P(X=true).\n", "\n", "The example below where we implement the network shown in **Figure 14.3** of the book will make this more clear.\n", "\n", "\n", "\n", "The alarm node can be made as follows: " ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "alarm_node = BayesNode('Alarm', ['Burglary', 'Earthquake'], \n", " {(True, True): 0.95,(True, False): 0.94, (False, True): 0.29, (False, False): 0.001})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is possible to avoid using a tuple when there is only a single parent. So an alternative format for the **cpt** is" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "john_node = BayesNode('JohnCalls', ['Alarm'], {True: 0.90, False: 0.05})\n", "mary_node = BayesNode('MaryCalls', 'Alarm', {(True, ): 0.70, (False, ): 0.01}) # Using string for parents.\n", "# Equivalant to john_node definition." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The general format used for the alarm node always holds. For nodes with no parents we can also use. " ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "burglary_node = BayesNode('Burglary', '', 0.001)\n", "earthquake_node = BayesNode('Earthquake', '', 0.002)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is possible to use the node for lookup function using the **p** method. The method takes in two arguments **value** and **event**. Event must be a dict of the type {variable:values, ..} The value corresponds to the value of the variable we are interested in (False or True).The method returns the conditional probability **P(X=value | parents=parent_values)**, where parent_values are the values of parents in event. (event must assign each parent a value.)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.09999999999999998" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "john_node.p(False, {'Alarm': True, 'Burglary': True}) # P(JohnCalls=False | Alarm=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With all the information about nodes present it is possible to construct a Bayes Network using **BayesNet**. The **BayesNet** class does not take in nodes as input but instead takes a list of **node_specs**. An entry in **node_specs** is a tuple of the parameters we use to construct a **BayesNode** namely **(X, parents, cpt)**. **node_specs** must be ordered with parents before children." ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
class BayesNet:\n",
       "    """Bayesian network containing only boolean-variable nodes."""\n",
       "\n",
       "    def __init__(self, node_specs=None):\n",
       "        """Nodes must be ordered with parents before children."""\n",
       "        self.nodes = []\n",
       "        self.variables = []\n",
       "        node_specs = node_specs or []\n",
       "        for node_spec in node_specs:\n",
       "            self.add(node_spec)\n",
       "\n",
       "    def add(self, node_spec):\n",
       "        """Add a node to the net. Its parents must already be in the\n",
       "        net, and its variable must not."""\n",
       "        node = BayesNode(*node_spec)\n",
       "        assert node.variable not in self.variables\n",
       "        assert all((parent in self.variables) for parent in node.parents)\n",
       "        self.nodes.append(node)\n",
       "        self.variables.append(node.variable)\n",
       "        for parent in node.parents:\n",
       "            self.variable_node(parent).children.append(node)\n",
       "\n",
       "    def variable_node(self, var):\n",
       "        """Return the node for the variable named var.\n",
       "        >>> burglary.variable_node('Burglary').variable\n",
       "        'Burglary'"""\n",
       "        for n in self.nodes:\n",
       "            if n.variable == var:\n",
       "                return n\n",
       "        raise Exception("No such variable: {}".format(var))\n",
       "\n",
       "    def variable_values(self, var):\n",
       "        """Return the domain of var."""\n",
       "        return [True, False]\n",
       "\n",
       "    def __repr__(self):\n",
       "        return 'BayesNet({0!r})'.format(self.nodes)\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(BayesNet)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The constructor of **BayesNet** takes each item in **node_specs** and adds a **BayesNode** to its **nodes** object variable by calling the **add** method. **add** in turn adds node to the net. Its parents must already be in the net, and its variable must not. Thus add allows us to grow a **BayesNet** given its parents are already present.\n", "\n", "**burglary** global is an instance of **BayesNet** corresponding to the above example.\n", "\n", " T, F = True, False\n", "\n", " burglary = BayesNet([\n", " ('Burglary', '', 0.001),\n", " ('Earthquake', '', 0.002),\n", " ('Alarm', 'Burglary Earthquake',\n", " {(T, T): 0.95, (T, F): 0.94, (F, T): 0.29, (F, F): 0.001}),\n", " ('JohnCalls', 'Alarm', {T: 0.90, F: 0.05}),\n", " ('MaryCalls', 'Alarm', {T: 0.70, F: 0.01})\n", " ])" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "BayesNet([('Burglary', ''), ('Earthquake', ''), ('Alarm', 'Burglary Earthquake'), ('JohnCalls', 'Alarm'), ('MaryCalls', 'Alarm')])" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "burglary" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**BayesNet** method **variable_node** allows to reach **BayesNode** instances inside a Bayes Net. It is possible to modify the **cpt** of the nodes directly using this method." ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "probability.BayesNode" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(burglary.variable_node('Alarm'))" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{(True, True): 0.95,\n", " (True, False): 0.94,\n", " (False, True): 0.29,\n", " (False, False): 0.001}" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "burglary.variable_node('Alarm').cpt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exact Inference in Bayesian Networks\n", "\n", "A Bayes Network is a more compact representation of the full joint distribution and like full joint distributions allows us to do inference i.e. answer questions about probability distributions of random variables given some evidence.\n", "\n", "Exact algorithms don't scale well for larger networks. Approximate algorithms are explained in the next section.\n", "\n", "### Inference by Enumeration\n", "\n", "We apply techniques similar to those used for **enumerate_joint_ask** and **enumerate_joint** to draw inference from Bayesian Networks. **enumeration_ask** and **enumerate_all** implement the algorithm described in **Figure 14.9** of the book." ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def enumerate_all(variables, e, bn):\n",
       "    """Return the sum of those entries in P(variables | e{others})\n",
       "    consistent with e, where P is the joint distribution represented\n",
       "    by bn, and e{others} means e restricted to bn's other variables\n",
       "    (the ones other than variables). Parents must precede children in variables."""\n",
       "    if not variables:\n",
       "        return 1.0\n",
       "    Y, rest = variables[0], variables[1:]\n",
       "    Ynode = bn.variable_node(Y)\n",
       "    if Y in e:\n",
       "        return Ynode.p(e[Y], e) * enumerate_all(rest, e, bn)\n",
       "    else:\n",
       "        return sum(Ynode.p(y, e) * enumerate_all(rest, extend(e, Y, y), bn)\n",
       "                   for y in bn.variable_values(Y))\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(enumerate_all)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**enumerate_all** recursively evaluates a general form of the **Equation 14.4** in the book.\n", "\n", "$$\\textbf{P}(X | \\textbf{e}) = α \\textbf{P}(X, \\textbf{e}) = α \\sum_{y} \\textbf{P}(X, \\textbf{e}, \\textbf{y})$$ \n", "\n", "such that **P(X, e, y)** is written in the form of product of conditional probabilities **P(variable | parents(variable))** from the Bayesian Network.\n", "\n", "**enumeration_ask** calls **enumerate_all** on each value of query variable **X** and finally normalizes them. \n" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def enumeration_ask(X, e, bn):\n",
       "    """Return the conditional probability distribution of variable X\n",
       "    given evidence e, from BayesNet bn. [Figure 14.9]\n",
       "    >>> enumeration_ask('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary\n",
       "    ...  ).show_approx()\n",
       "    'False: 0.716, True: 0.284'"""\n",
       "    assert X not in e, "Query variable must be distinct from evidence"\n",
       "    Q = ProbDist(X)\n",
       "    for xi in bn.variable_values(X):\n",
       "        Q[xi] = enumerate_all(bn.variables, extend(e, X, xi), bn)\n",
       "    return Q.normalize()\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(enumeration_ask)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let us solve the problem of finding out **P(Burglary=True | JohnCalls=True, MaryCalls=True)** using the **burglary** network. **enumeration_ask** takes three arguments **X** = variable name, **e** = Evidence (in form a dict like previously explained), **bn** = The Bayes Net to do inference on." ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.2841718353643929" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "ans_dist = enumeration_ask('Burglary', {'JohnCalls': True, 'MaryCalls': True}, burglary)\n", "ans_dist[True]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Variable Elimination\n", "\n", "The enumeration algorithm can be improved substantially by eliminating repeated calculations. In enumeration we join the joint of all hidden variables. This is of exponential size for the number of hidden variables. Variable elimination employes interleaving join and marginalization.\n", "\n", "Before we look into the implementation of Variable Elimination we must first familiarize ourselves with Factors. \n", "\n", "In general we call a multidimensional array of type P(Y1 ... Yn | X1 ... Xm) a factor where some of Xs and Ys maybe assigned values. Factors are implemented in the probability module as the class **Factor**. They take as input **variables** and **cpt**. \n", "\n", "\n", "#### Helper Functions\n", "\n", "There are certain helper functions that help creating the **cpt** for the Factor given the evidence. Let us explore them one by one." ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def make_factor(var, e, bn):\n",
       "    """Return the factor for var in bn's joint distribution given e.\n",
       "    That is, bn's full joint distribution, projected to accord with e,\n",
       "    is the pointwise product of these factors for bn's variables."""\n",
       "    node = bn.variable_node(var)\n",
       "    variables = [X for X in [var] + node.parents if X not in e]\n",
       "    cpt = {event_values(e1, variables): node.p(e1[var], e1)\n",
       "           for e1 in all_events(variables, bn, e)}\n",
       "    return Factor(variables, cpt)\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(make_factor)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**make_factor** is used to create the **cpt** and **variables** that will be passed to the constructor of **Factor**. We use **make_factor** for each variable. It takes in the arguments **var** the particular variable, **e** the evidence we want to do inference on, **bn** the bayes network.\n", "\n", "Here **variables** for each node refers to a list consisting of the variable itself and the parents minus any variables that are part of the evidence. This is created by finding the **node.parents** and filtering out those that are not part of the evidence.\n", "\n", "The **cpt** created is the one similar to the original **cpt** of the node with only rows that agree with the evidence." ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def all_events(variables, bn, e):\n",
       "    """Yield every way of extending e with values for all variables."""\n",
       "    if not variables:\n",
       "        yield e\n",
       "    else:\n",
       "        X, rest = variables[0], variables[1:]\n",
       "        for e1 in all_events(rest, bn, e):\n",
       "            for x in bn.variable_values(X):\n",
       "                yield extend(e1, X, x)\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(all_events)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The **all_events** function is a recursive generator function which yields a key for the orignal **cpt** which is part of the node. This works by extending evidence related to the node, thus all the output from **all_events** only includes events that support the evidence. Given **all_events** is a generator function one such event is returned on every call. \n", "\n", "We can try this out using the example on **Page 524** of the book. We will make **f**5(A) = P(m | A)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [], "source": [ "f5 = make_factor('MaryCalls', {'JohnCalls': True, 'MaryCalls': True}, burglary)" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f5" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{(True,): 0.7, (False,): 0.01}" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f5.cpt" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['Alarm']" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f5.variables" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here **f5.cpt** False key gives probability for **P(MaryCalls=True | Alarm = False)**. Due to our representation where we only store probabilities for only in cases where the node variable is True this is the same as the **cpt** of the BayesNode. Let us try a somewhat different example from the book where evidence is that the Alarm = True" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [], "source": [ "new_factor = make_factor('MaryCalls', {'Alarm': True}, burglary)" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{(True,): 0.7, (False,): 0.30000000000000004}" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "new_factor.cpt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here the **cpt** is for **P(MaryCalls | Alarm = True)**. Therefore the probabilities for True and False sum up to one. Note the difference between both the cases. Again the only rows included are those consistent with the evidence.\n", "\n", "#### Operations on Factors\n", "\n", "We are interested in two kinds of operations on factors. **Pointwise Product** which is used to created joint distributions and **Summing Out** which is used for marginalization." ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
    def pointwise_product(self, other, bn):\n",
       "        """Multiply two factors, combining their variables."""\n",
       "        variables = list(set(self.variables) | set(other.variables))\n",
       "        cpt = {event_values(e, variables): self.p(e) * other.p(e)\n",
       "               for e in all_events(variables, bn, {})}\n",
       "        return Factor(variables, cpt)\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(Factor.pointwise_product)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Factor.pointwise_product** implements a method of creating a joint via combining two factors. We take the union of **variables** of both the factors and then generate the **cpt** for the new factor using **all_events** function. Note that the given we have eliminated rows that are not consistent with the evidence. Pointwise product assigns new probabilities by multiplying rows similar to that in a database join." ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def pointwise_product(factors, bn):\n",
       "    return reduce(lambda f, g: f.pointwise_product(g, bn), factors)\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(pointwise_product)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**pointwise_product** extends this operation to more than two operands where it is done sequentially in pairs of two." ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
    def sum_out(self, var, bn):\n",
       "        """Make a factor eliminating var by summing over its values."""\n",
       "        variables = [X for X in self.variables if X != var]\n",
       "        cpt = {event_values(e, variables): sum(self.p(extend(e, var, val))\n",
       "                                               for val in bn.variable_values(var))\n",
       "               for e in all_events(variables, bn, {})}\n",
       "        return Factor(variables, cpt)\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(Factor.sum_out)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Factor.sum_out** makes a factor eliminating a variable by summing over its values. Again **events_all** is used to generate combinations for the rest of the variables." ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def sum_out(var, factors, bn):\n",
       "    """Eliminate var from all factors by summing over its values."""\n",
       "    result, var_factors = [], []\n",
       "    for f in factors:\n",
       "        (var_factors if var in f.variables else result).append(f)\n",
       "    result.append(pointwise_product(var_factors, bn).sum_out(var, bn))\n",
       "    return result\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(sum_out)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**sum_out** uses both **Factor.sum_out** and **pointwise_product** to finally eliminate a particular variable from all factors by summing over its values." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Elimination Ask\n", "\n", "The algorithm described in **Figure 14.11** of the book is implemented by the function **elimination_ask**. We use this for inference. The key idea is that we eliminate the hidden variables by interleaving joining and marginalization. It takes in 3 arguments **X** the query variable, **e** the evidence variable and **bn** the Bayes network. \n", "\n", "The algorithm creates factors out of Bayes Nodes in reverse order and eliminates hidden variables using **sum_out**. Finally it takes a point wise product of all factors and normalizes. Let us finally solve the problem of inferring \n", "\n", "**P(Burglary=True | JohnCalls=True, MaryCalls=True)** using variable elimination." ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def elimination_ask(X, e, bn):\n",
       "    """Compute bn's P(X|e) by variable elimination. [Figure 14.11]\n",
       "    >>> elimination_ask('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary\n",
       "    ...  ).show_approx()\n",
       "    'False: 0.716, True: 0.284'"""\n",
       "    assert X not in e, "Query variable must be distinct from evidence"\n",
       "    factors = []\n",
       "    for var in reversed(bn.variables):\n",
       "        factors.append(make_factor(var, e, bn))\n",
       "        if is_hidden(var, X, e):\n",
       "            factors = sum_out(var, factors, bn)\n",
       "    return pointwise_product(factors, bn).normalize()\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(elimination_ask)" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'False: 0.716, True: 0.284'" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "elimination_ask('Burglary', dict(JohnCalls=True, MaryCalls=True), burglary).show_approx()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Elimination Ask Optimizations\n", "\n", "`elimination_ask` has some critical point to consider and some optimizations could be performed:\n", "\n", "- **Operation on factors**:\n", "\n", " `sum_out` and `pointwise_product` function used in `elimination_ask` is where space and time complexity arise in the variable elimination algorithm (AIMA3e pg. 526).\n", "\n", ">The only trick is to notice that any factor that does not depend on the variable to be summed out can be moved outside the summation.\n", "\n", "- **Variable ordering**:\n", "\n", " Elimination ordering is important, every choice of ordering yields a valid algorithm, but different orderings cause different intermediate factors to be generated during the calculation (AIMA3e pg. 527). In this case the algorithm applies a reversed order.\n", "\n", "> In general, the time and space requirements of variable elimination are dominated by the size of the largest factor constructed during the operation of the algorithm. This in turn is determined by the order of elimination of variables and by the structure of the network. It turns out to be intractable to determine the optimal ordering, but several good heuristics are available. One fairly effective method is a greedy one: eliminate whichever variable minimizes the size of the next factor to be constructed. \n", "\n", "- **Variable relevance**\n", " \n", " Some variables could be irrelevant to resolve a query (i.e. sums to 1). A variable elimination algorithm can therefore remove all these variables before evaluating the query (AIMA3e pg. 528).\n", "\n", "> An optimization is to remove 'every variable that is not an ancestor of a query variable or evidence variable is irrelevant to the query'." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Runtime comparison\n", "Let's see how the runtimes of these two algorithms compare.\n", "We expect variable elimination to outperform enumeration by a large margin as we reduce the number of repetitive calculations significantly." ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "105 µs ± 11.9 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n" ] } ], "source": [ "%%timeit\n", "enumeration_ask('Burglary', dict(JohnCalls=True, MaryCalls=True), burglary).show_approx()" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "262 µs ± 54.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" ] } ], "source": [ "%%timeit\n", "elimination_ask('Burglary', dict(JohnCalls=True, MaryCalls=True), burglary).show_approx()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this test case we observe that variable elimination is slower than what we expected. It has something to do with number of threads, how Python tries to optimize things and this happens because the network is very small, with just 5 nodes. The `elimination_ask` has some critical point and some optimizations must be perfomed as seen above.\n", "
\n", "Of course, for more complicated networks, variable elimination will be significantly faster and runtime will drop not just by a constant factor, but by a polynomial factor proportional to the number of nodes, due to the reduction in repeated calculations." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Approximate Inference in Bayesian Networks\n", "\n", "Exact inference fails to scale for very large and complex Bayesian Networks. This section covers implementation of randomized sampling algorithms, also called Monte Carlo algorithms." ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
    def sample(self, event):\n",
       "        """Sample from the distribution for this variable conditioned\n",
       "        on event's values for parent_variables. That is, return True/False\n",
       "        at random according with the conditional probability given the\n",
       "        parents."""\n",
       "        return probability(self.p(True, event))\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(BayesNode.sample)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Before we consider the different algorithms in this section let us look at the **BayesNode.sample** method. It samples from the distribution for this variable conditioned on event's values for parent_variables. That is, return True/False at random according to with the conditional probability given the parents. The **probability** function is a simple helper from **utils** module which returns True with the probability passed to it.\n", "\n", "### Prior Sampling\n", "\n", "The idea of Prior Sampling is to sample from the Bayesian Network in a topological order. We start at the top of the network and sample as per **P(Xi | parents(Xi)** i.e. the probability distribution from which the value is sampled is conditioned on the values already assigned to the variable's parents. This can be thought of as a simulation." ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def prior_sample(bn):\n",
       "    """Randomly sample from bn's full joint distribution. The result\n",
       "    is a {variable: value} dict. [Figure 14.13]"""\n",
       "    event = {}\n",
       "    for node in bn.nodes:\n",
       "        event[node.variable] = node.sample(event)\n",
       "    return event\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(prior_sample)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The function **prior_sample** implements the algorithm described in **Figure 14.13** of the book. Nodes are sampled in the topological order. The old value of the event is passed as evidence for parent values. We will use the Bayesian Network in **Figure 14.12** to try out the **prior_sample**\n", "\n", "\n", "\n", "Traversing the graph in topological order is important.\n", "There are two possible topological orderings for this particular directed acyclic graph.\n", "
\n", "1. `Cloudy -> Sprinkler -> Rain -> Wet Grass`\n", "2. `Cloudy -> Rain -> Sprinkler -> Wet Grass`\n", "
\n", "
\n", "We can follow any of the two orderings to sample from the network.\n", "Any ordering other than these two, however, cannot be used.\n", "
\n", "One way to think about this is that `Cloudy` can be seen as a precondition of both `Rain` and `Sprinkler` and just like we have seen in planning, preconditions need to be satisfied before a certain action can be executed.\n", "
\n", "We store the samples on the observations. Let us find **P(Rain=True)** by taking 1000 random samples from the network." ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [], "source": [ "N = 1000\n", "all_observations = [prior_sample(sprinkler) for x in range(N)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we filter to get the observations where Rain = True" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [], "source": [ "rain_true = [observation for observation in all_observations if observation['Rain'] == True]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, we can find **P(Rain=True)**" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.503\n" ] } ], "source": [ "answer = len(rain_true) / N\n", "print(answer)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sampling this another time might give different results as we have no control over the distribution of the random samples" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.519\n" ] } ], "source": [ "N = 1000\n", "all_observations = [prior_sample(sprinkler) for x in range(N)]\n", "rain_true = [observation for observation in all_observations if observation['Rain'] == True]\n", "answer = len(rain_true) / N\n", "print(answer)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To evaluate a conditional distribution. We can use a two-step filtering process. We first separate out the variables that are consistent with the evidence. Then for each value of query variable, we can find probabilities. For example to find **P(Cloudy=True | Rain=True)**. We have already filtered out the values consistent with our evidence in **rain_true**. Now we apply a second filtering step on **rain_true** to find **P(Rain=True and Cloudy=True)**" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.8265895953757225\n" ] } ], "source": [ "rain_and_cloudy = [observation for observation in rain_true if observation['Cloudy'] == True]\n", "answer = len(rain_and_cloudy) / len(rain_true)\n", "print(answer)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Rejection Sampling\n", "\n", "Rejection Sampling is based on an idea similar to what we did just now. \n", "First, it generates samples from the prior distribution specified by the network. \n", "Then, it rejects all those that do not match the evidence. \n", "
\n", "Rejection sampling is advantageous only when we know the query beforehand.\n", "While prior sampling generally works for any query, it might fail in some scenarios.\n", "
\n", "Let's say we have a generic Bayesian network and we have evidence `e`, and we want to know how many times a state `A` is true, given evidence `e` is true.\n", "Normally, prior sampling can answer this question, but let's assume that the probability of evidence `e` being true in our actual probability distribution is very small.\n", "In this situation, it might be possible that sampling never encounters a data-point where `e` is true.\n", "If our sampled data has no instance of `e` being true, `P(e) = 0`, and therefore `P(A | e) / P(e) = 0/0`, which is undefined.\n", "We cannot find the required value using this sample.\n", "
\n", "We can definitely increase the number of sample points, but we can never guarantee that we will encounter the case where `e` is non-zero (assuming our actual probability distribution has atleast one case where `e` is true).\n", "To guarantee this, we would have to consider every single data point, which means we lose the speed advantage that approximation provides us and we essentially have to calculate the exact inference model of the Bayesian network.\n", "
\n", "
\n", "Rejection sampling will be useful in this situation, as we already know the query.\n", "
\n", "While sampling from the network, we will reject any sample which is inconsistent with the evidence variables of the given query (in this example, the only evidence variable is `e`).\n", "We will only consider samples that do not violate **any** of the evidence variables.\n", "In this way, we will have enough data with the required evidence to infer queries involving a subset of that evidence.\n", "
\n", "
\n", "The function **rejection_sampling** implements the algorithm described by **Figure 14.14**" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def rejection_sampling(X, e, bn, N=10000):\n",
       "    """Estimate the probability distribution of variable X given\n",
       "    evidence e in BayesNet bn, using N samples.  [Figure 14.14]\n",
       "    Raises a ZeroDivisionError if all the N samples are rejected,\n",
       "    i.e., inconsistent with e.\n",
       "    >>> random.seed(47)\n",
       "    >>> rejection_sampling('Burglary', dict(JohnCalls=T, MaryCalls=T),\n",
       "    ...   burglary, 10000).show_approx()\n",
       "    'False: 0.7, True: 0.3'\n",
       "    """\n",
       "    counts = {x: 0 for x in bn.variable_values(X)}  # bold N in [Figure 14.14]\n",
       "    for j in range(N):\n",
       "        sample = prior_sample(bn)  # boldface x in [Figure 14.14]\n",
       "        if consistent_with(sample, e):\n",
       "            counts[sample[X]] += 1\n",
       "    return ProbDist(X, counts)\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(rejection_sampling)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The function keeps counts of each of the possible values of the Query variable and increases the count when we see an observation consistent with the evidence. It takes in input parameters **X** - The Query Variable, **e** - evidence, **bn** - Bayes net and **N** - number of prior samples to generate.\n", "\n", "**consistent_with** is used to check consistency." ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def consistent_with(event, evidence):\n",
       "    """Is event consistent with the given evidence?"""\n",
       "    return all(evidence.get(k, v) == v\n",
       "               for k, v in event.items())\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(consistent_with)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To answer **P(Cloudy=True | Rain=True)**" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.8035019455252919" ] }, "execution_count": 59, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p = rejection_sampling('Cloudy', dict(Rain=True), sprinkler, 1000)\n", "p[True]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Likelihood Weighting\n", "\n", "Rejection sampling takes a long time to run when the probability of finding consistent evidence is low. It is also slow for larger networks and more evidence variables.\n", "Rejection sampling tends to reject a lot of samples if our evidence consists of a large number of variables. Likelihood Weighting solves this by fixing the evidence (i.e. not sampling it) and then using weights to make sure that our overall sampling is still consistent.\n", "\n", "The pseudocode in **Figure 14.15** is implemented as **likelihood_weighting** and **weighted_sample**." ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def weighted_sample(bn, e):\n",
       "    """Sample an event from bn that's consistent with the evidence e;\n",
       "    return the event and its weight, the likelihood that the event\n",
       "    accords to the evidence."""\n",
       "    w = 1\n",
       "    event = dict(e)  # boldface x in [Figure 14.15]\n",
       "    for node in bn.nodes:\n",
       "        Xi = node.variable\n",
       "        if Xi in e:\n",
       "            w *= node.p(e[Xi], event)\n",
       "        else:\n",
       "            event[Xi] = node.sample(event)\n",
       "    return event, w\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(weighted_sample)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "**weighted_sample** samples an event from Bayesian Network that's consistent with the evidence **e** and returns the event and its weight, the likelihood that the event accords to the evidence. It takes in two parameters **bn** the Bayesian Network and **e** the evidence.\n", "\n", "The weight is obtained by multiplying **P(xi | parents(xi))** for each node in evidence. We set the values of **event = evidence** at the start of the function." ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "({'Rain': True, 'Cloudy': False, 'Sprinkler': True, 'WetGrass': True}, 0.2)" ] }, "execution_count": 61, "metadata": {}, "output_type": "execute_result" } ], "source": [ "weighted_sample(sprinkler, dict(Rain=True))" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def likelihood_weighting(X, e, bn, N=10000):\n",
       "    """Estimate the probability distribution of variable X given\n",
       "    evidence e in BayesNet bn.  [Figure 14.15]\n",
       "    >>> random.seed(1017)\n",
       "    >>> likelihood_weighting('Burglary', dict(JohnCalls=T, MaryCalls=T),\n",
       "    ...   burglary, 10000).show_approx()\n",
       "    'False: 0.702, True: 0.298'\n",
       "    """\n",
       "    W = {x: 0 for x in bn.variable_values(X)}\n",
       "    for j in range(N):\n",
       "        sample, weight = weighted_sample(bn, e)  # boldface x, w in [Figure 14.15]\n",
       "        W[sample[X]] += weight\n",
       "    return ProbDist(X, W)\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(likelihood_weighting)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**likelihood_weighting** implements the algorithm to solve our inference problem. The code is similar to **rejection_sampling** but instead of adding one for each sample we add the weight obtained from **weighted_sampling**." ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'False: 0.2, True: 0.8'" ] }, "execution_count": 63, "metadata": {}, "output_type": "execute_result" } ], "source": [ "likelihood_weighting('Cloudy', dict(Rain=True), sprinkler, 200).show_approx()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Gibbs Sampling\n", "\n", "In likelihood sampling, it is possible to obtain low weights in cases where the evidence variables reside at the bottom of the Bayesian Network. This can happen because influence only propagates downwards in likelihood sampling.\n", "\n", "Gibbs Sampling solves this. The implementation of **Figure 14.16** is provided in the function **gibbs_ask** " ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def gibbs_ask(X, e, bn, N=1000):\n",
       "    """[Figure 14.16]"""\n",
       "    assert X not in e, "Query variable must be distinct from evidence"\n",
       "    counts = {x: 0 for x in bn.variable_values(X)}  # bold N in [Figure 14.16]\n",
       "    Z = [var for var in bn.variables if var not in e]\n",
       "    state = dict(e)  # boldface x in [Figure 14.16]\n",
       "    for Zi in Z:\n",
       "        state[Zi] = random.choice(bn.variable_values(Zi))\n",
       "    for j in range(N):\n",
       "        for Zi in Z:\n",
       "            state[Zi] = markov_blanket_sample(Zi, state, bn)\n",
       "            counts[state[X]] += 1\n",
       "    return ProbDist(X, counts)\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(gibbs_ask)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In **gibbs_ask** we initialize the non-evidence variables to random values. And then select non-evidence variables and sample it from **P(Variable | value in the current state of all remaining vars) ** repeatedly sample. In practice, we speed this up by using **markov_blanket_sample** instead. This works because terms not involving the variable get canceled in the calculation. The arguments for **gibbs_ask** are similar to **likelihood_weighting**" ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'False: 0.215, True: 0.785'" ] }, "execution_count": 65, "metadata": {}, "output_type": "execute_result" } ], "source": [ "gibbs_ask('Cloudy', dict(Rain=True), sprinkler, 200).show_approx()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Runtime analysis\n", "Let's take a look at how much time each algorithm takes." ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "13.2 ms ± 3.45 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" ] } ], "source": [ "%%timeit\n", "all_observations = [prior_sample(sprinkler) for x in range(1000)]\n", "rain_true = [observation for observation in all_observations if observation['Rain'] == True]\n", "len([observation for observation in rain_true if observation['Cloudy'] == True]) / len(rain_true)" ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "11 ms ± 687 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n" ] } ], "source": [ "%%timeit\n", "rejection_sampling('Cloudy', dict(Rain=True), sprinkler, 1000)" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2.12 ms ± 554 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" ] } ], "source": [ "%%timeit\n", "likelihood_weighting('Cloudy', dict(Rain=True), sprinkler, 200)" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "14.4 ms ± 2.16 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" ] } ], "source": [ "%%timeit\n", "gibbs_ask('Cloudy', dict(Rain=True), sprinkler, 200)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As expected, all algorithms have a very similar runtime.\n", "However, rejection sampling would be a lot faster and more accurate when the probabiliy of finding data-points consistent with the required evidence is small.\n", "
\n", "Likelihood weighting is the fastest out of all as it doesn't involve rejecting samples, but also has a quite high variance." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## HIDDEN MARKOV MODELS" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Often, we need to carry out probabilistic inference on temporal data or a sequence of observations where the order of observations matter.\n", "We require a model similar to a Bayesian Network, but one that grows over time to keep up with the latest evidences.\n", "If you are familiar with the `mdp` module or Markov models in general, you can probably guess that a Markov model might come close to representing our problem accurately.\n", "
\n", "A Markov model is basically a chain-structured Bayesian Network in which there is one state for each time step and each node has an identical probability distribution.\n", "The first node, however, has a different distribution, called the prior distribution which models the initial state of the process.\n", "A state in a Markov model depends only on the previous state and the latest evidence and not on the states before it.\n", "
\n", "A **Hidden Markov Model** or **HMM** is a special case of a Markov model in which the state of the process is described by a single discrete random variable.\n", "The possible values of the variable are the possible states of the world.\n", "
\n", "But what if we want to model a process with two or more state variables?\n", "In that case, we can still fit the process into the HMM framework by redefining our state variables as a single \"megavariable\".\n", "We do this because carrying out inference on HMMs have standard optimized algorithms.\n", "A HMM is very similar to an MDP, but we don't have the option of taking actions like in MDPs, instead, the process carries on as new evidence appears.\n", "
\n", "If a HMM is truncated at a fixed length, it becomes a Bayesian network and general BN inference can be used on it to answer queries.\n", "\n", "Before we start, it will be helpful to understand the structure of a temporal model. We will use the example of the book with the guard and the umbrella. In this example, the state $\\textbf{X}$ is whether it is a rainy day (`X = True`) or not (`X = False`) at Day $\\textbf{t}$. In the sensor or observation model, the observation or evidence $\\textbf{U}$ is whether the professor holds an umbrella (`U = True`) or not (`U = False`) on **Day** $\\textbf{t}$. Based on that, the transition model is \n", "\n", "| $X_{t-1}$ | $X_{t}$ | **P**$(X_{t}| X_{t-1})$| \n", "| ------------- |------------- | ----------------------------------|\n", "| ***${False}$*** | ***${False}$*** | 0.7 |\n", "| ***${False}$*** | ***${True}$*** | 0.3 |\n", "| ***${True}$*** | ***${False}$*** | 0.3 |\n", "| ***${True}$*** | ***${True}$*** | 0.7 |\n", "\n", "And the the sensor model will be,\n", "\n", "| $X_{t}$ | $U_{t}$ | **P**$(U_{t}|X_{t})$| \n", "| :-------------: |:-------------: | :------------------------:|\n", "| ***${False}$*** | ***${True}$*** | 0.2 |\n", "| ***${False}$*** | ***${False}$*** | 0.8 |\n", "| ***${True}$*** | ***${True}$*** | 0.9 |\n", "| ***${True}$*** | ***${False}$*** | 0.1 |\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "HMMs are implemented in the **`HiddenMarkovModel`** class.\n", "Let's have a look." ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
class HiddenMarkovModel:\n",
       "    """A Hidden markov model which takes Transition model and Sensor model as inputs"""\n",
       "\n",
       "    def __init__(self, transition_model, sensor_model, prior=None):\n",
       "        self.transition_model = transition_model\n",
       "        self.sensor_model = sensor_model\n",
       "        self.prior = prior or [0.5, 0.5]\n",
       "\n",
       "    def sensor_dist(self, ev):\n",
       "        if ev is True:\n",
       "            return self.sensor_model[0]\n",
       "        else:\n",
       "            return self.sensor_model[1]\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(HiddenMarkovModel)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We instantiate the object **`hmm`** of the class using a list of lists for both the transition and the sensor model." ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [], "source": [ "umbrella_transition_model = [[0.7, 0.3], [0.3, 0.7]]\n", "umbrella_sensor_model = [[0.9, 0.2], [0.1, 0.8]]\n", "hmm = HiddenMarkovModel(umbrella_transition_model, umbrella_sensor_model)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The **`sensor_dist()`** method returns a list with the conditional probabilities of the sensor model." ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0.9, 0.2]" ] }, "execution_count": 72, "metadata": {}, "output_type": "execute_result" } ], "source": [ "hmm.sensor_dist(ev=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we have defined an HMM object, our task here is to compute the belief $B_{t}(x)= P(X_{t}|U_{1:t})$ given evidence **U** at each time step **t**.\n", "
\n", "The basic inference tasks that must be solved are:\n", "1. **Filtering**: Computing the posterior probability distribution over the most recent state, given all the evidence up to the current time step.\n", "2. **Prediction**: Computing the posterior probability distribution over the future state.\n", "3. **Smoothing**: Computing the posterior probability distribution over a past state. Smoothing provides a better estimation as it incorporates more evidence.\n", "4. **Most likely explanation**: Finding the most likely sequence of states for a given observation\n", "5. **Learning**: The transition and sensor models can be learnt, if not yet known, just like in an information gathering agent\n", "
\n", "
\n", "\n", "There are three primary methods to carry out inference in Hidden Markov Models:\n", "1. The Forward-Backward algorithm\n", "2. Fixed lag smoothing\n", "3. Particle filtering\n", "\n", "Let's have a look at how we can carry out inference and answer queries based on our umbrella HMM using these algorithms." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### FORWARD-BACKWARD\n", "This is a general algorithm that works for all Markov models, not just HMMs.\n", "In the filtering task (inference) we are given evidence **U** in each time **t** and we want to compute the belief $B_{t}(x)= P(X_{t}|U_{1:t})$. \n", "We can think of it as a three step process:\n", "1. In every step we start with the current belief $P(X_{t}|e_{1:t})$\n", "2. We update it for time\n", "3. We update it for evidence\n", "\n", "The forward algorithm performs the step 2 and 3 at once. It updates, or better say reweights, the initial belief using the transition and the sensor model. Let's see the umbrella example. On **Day 0** no observation is available, and for that reason we will assume that we have equal possibilities to rain or not. In the **`HiddenMarkovModel`** class, the prior probabilities for **Day 0** are by default [0.5, 0.5]. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The observation update is calculated with the **`forward()`** function. Basically, we update our belief using the observation model. The function returns a list with the probabilities of **raining or not** on **Day 1**." ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def forward(HMM, fv, ev):\n",
       "    prediction = vector_add(scalar_vector_product(fv[0], HMM.transition_model[0]),\n",
       "                            scalar_vector_product(fv[1], HMM.transition_model[1]))\n",
       "    sensor_dist = HMM.sensor_dist(ev)\n",
       "\n",
       "    return normalize(element_wise_product(sensor_dist, prediction))\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(forward)" ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The probability of raining on day 1 is 0.82\n" ] } ], "source": [ "umbrella_prior = [0.5, 0.5]\n", "belief_day_1 = forward(hmm, umbrella_prior, ev=True)\n", "print ('The probability of raining on day 1 is {:.2f}'.format(belief_day_1[0]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In **Day 2** our initial belief is the updated belief of **Day 1**.\n", "Again using the **`forward()`** function we can compute the probability of raining in **Day 2**" ] }, { "cell_type": "code", "execution_count": 75, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The probability of raining in day 2 is 0.88\n" ] } ], "source": [ "belief_day_2 = forward(hmm, belief_day_1, ev=True)\n", "print ('The probability of raining in day 2 is {:.2f}'.format(belief_day_2[0]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the smoothing part we are interested in computing the distribution over past states given evidence up to the present. Assume that we want to compute the distribution for the time **k**, for $0\\leq k\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def backward(HMM, b, ev):\n",
       "    sensor_dist = HMM.sensor_dist(ev)\n",
       "    prediction = element_wise_product(sensor_dist, b)\n",
       "\n",
       "    return normalize(vector_add(scalar_vector_product(prediction[0], HMM.transition_model[0]),\n",
       "                                scalar_vector_product(prediction[1], HMM.transition_model[1])))\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(backward)" ] }, { "cell_type": "code", "execution_count": 77, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0.6272727272727272, 0.37272727272727274]" ] }, "execution_count": 77, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b = [1, 1]\n", "backward(hmm, b, ev=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Some may notice that the result is not the same as in the book. The main reason is that in the book the normalization step is not used. If we want to normalize the result, one can use the **`normalize()`** helper function.\n", "\n", "In order to find the smoothed estimate for raining in **Day k**, we will use the **`forward_backward()`** function. As in the example in the book, the umbrella is observed in both days and the prior distribution is [0.5, 0.5]" ] }, { "cell_type": "code", "execution_count": 78, "metadata": {}, "outputs": [ { "data": { "text/markdown": [ "### AIMA3e\n", "__function__ FORWARD-BACKWARD(__ev__, _prior_) __returns__ a vector of probability distributions \n", " __inputs__: __ev__, a vector of evidence values for steps 1,…,_t_ \n", "     _prior_, the prior distribution on the initial state, __P__(__X__0) \n", " __local variables__: __fv__, a vector of forward messages for steps 0,…,_t_ \n", "        __b__, a representation of the backward message, initially all 1s \n", "        __sv__, a vector of smoothed estimates for steps 1,…,_t_ \n", "\n", " __fv__\\[0\\] ← _prior_ \n", " __for__ _i_ = 1 __to__ _t_ __do__ \n", "   __fv__\\[_i_\\] ← FORWARD(__fv__\\[_i_ − 1\\], __ev__\\[_i_\\]) \n", " __for__ _i_ = _t_ __downto__ 1 __do__ \n", "   __sv__\\[_i_\\] ← NORMALIZE(__fv__\\[_i_\\] × __b__) \n", "   __b__ ← BACKWARD(__b__, __ev__\\[_i_\\]) \n", " __return__ __sv__\n", "\n", "---\n", "__Figure ??__ The forward\\-backward algorithm for smoothing: computing posterior probabilities of a sequence of states given a sequence of observations. The FORWARD and BACKWARD operators are defined by Equations (__??__) and (__??__), respectively." ], "text/plain": [ "" ] }, "execution_count": 78, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pseudocode('Forward-Backward')" ] }, { "cell_type": "code", "execution_count": 79, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The probability of raining in Day 0 is 0.65 and in Day 1 is 0.88\n" ] } ], "source": [ "umbrella_prior = [0.5, 0.5]\n", "prob = forward_backward(hmm, ev=[T, T], prior=umbrella_prior)\n", "print ('The probability of raining in Day 0 is {:.2f} and in Day 1 is {:.2f}'.format(prob[0][0], prob[1][0]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Since HMMs are represented as single variable systems, we can represent the transition model and sensor model as matrices.\n", "The `forward_backward` algorithm can be easily carried out on this representation (as we have done here) with a time complexity of $O({S}^{2} t)$ where t is the length of the sequence and each step multiplies a vector of size $S$ with a matrix of dimensions $SxS$.\n", "
\n", "Additionally, the forward pass stores $t$ vectors of size $S$ which makes the auxiliary space requirement equivalent to $O(St)$.\n", "
\n", "
\n", "Is there any way we can improve the time or space complexity?\n", "
\n", "Fortunately, the matrix representation of HMM properties allows us to do so.\n", "
\n", "If $f$ and $b$ represent the forward and backward messages respectively, we can modify the smoothing algorithm by first\n", "running the standard forward pass to compute $f_{t:t}$ (forgetting all the intermediate results) and then running\n", "backward pass for both $b$ and $f$ together, using them to compute the smoothed estimate at each step.\n", "This optimization reduces auxlilary space requirement to constant (irrespective of the length of the sequence) provided\n", "the transition matrix is invertible and the sensor model has no zeros (which is sometimes hard to accomplish)\n", "
\n", "
\n", "Let's look at another algorithm, that carries out smoothing in a more optimized way." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### FIXED LAG SMOOTHING\n", "The matrix formulation allows to optimize online smoothing with a fixed lag.\n", "
\n", "Since smoothing can be done in constant, there should exist an algorithm whose time complexity is independent of the length of the lag.\n", "For smoothing a time slice $t - d$ where $d$ is the lag, we need to compute $\\alpha f_{1:t-d}$ x $b_{t-d+1:t}$ incrementally.\n", "
\n", "As we already know, the forward equation is\n", "
\n", "$$f_{1:t+1} = \\alpha O_{t+1}{T}^{T}f_{1:t}$$\n", "
\n", "and the backward equation is\n", "
\n", "$$b_{k+1:t} = TO_{k+1}b_{k+2:t}$$\n", "
\n", "where $T$ and $O$ are the transition and sensor models respectively.\n", "
\n", "For smoothing, the forward message is easy to compute but there exists no simple relation between the backward message of this time step and the one at the previous time step, hence we apply the backward equation $d$ times to get\n", "
\n", "$$b_{t-d+1:t} = \\left ( \\prod_{i=t-d+1}^{t}{TO_i} \\right )b_{t+1:t} = B_{t-d+1:t}1$$\n", "
\n", "where $B_{t-d+1:t}$ is the product of the sequence of $T$ and $O$ matrices.\n", "
\n", "Here's how the `probability` module implements `fixed_lag_smoothing`.\n", "
" ] }, { "cell_type": "code", "execution_count": 80, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def fixed_lag_smoothing(e_t, HMM, d, ev, t):\n",
       "    """[Figure 15.6]\n",
       "    Smoothing algorithm with a fixed time lag of 'd' steps.\n",
       "    Online algorithm that outputs the new smoothed estimate if observation\n",
       "    for new time step is given."""\n",
       "    ev.insert(0, None)\n",
       "\n",
       "    T_model = HMM.transition_model\n",
       "    f = HMM.prior\n",
       "    B = [[1, 0], [0, 1]]\n",
       "    evidence = []\n",
       "\n",
       "    evidence.append(e_t)\n",
       "    O_t = vector_to_diagonal(HMM.sensor_dist(e_t))\n",
       "    if t > d:\n",
       "        f = forward(HMM, f, e_t)\n",
       "        O_tmd = vector_to_diagonal(HMM.sensor_dist(ev[t - d]))\n",
       "        B = matrix_multiplication(inverse_matrix(O_tmd), inverse_matrix(T_model), B, T_model, O_t)\n",
       "    else:\n",
       "        B = matrix_multiplication(B, T_model, O_t)\n",
       "    t += 1\n",
       "\n",
       "    if t > d:\n",
       "        # always returns a 1x2 matrix\n",
       "        return [normalize(i) for i in matrix_multiplication([f], B)][0]\n",
       "    else:\n",
       "        return None\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(fixed_lag_smoothing)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This algorithm applies `forward` as usual and optimizes the smoothing step by using the equations above.\n", "This optimization could be achieved only because HMM properties can be represented as matrices.\n", "
\n", "`vector_to_diagonal`, `matrix_multiplication` and `inverse_matrix` are matrix manipulation functions to simplify the implementation.\n", "
\n", "`normalize` is used to normalize the output before returning it." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here's how we can use `fixed_lag_smoothing` for inference on our umbrella HMM." ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [], "source": [ "umbrella_transition_model = [[0.7, 0.3], [0.3, 0.7]]\n", "umbrella_sensor_model = [[0.9, 0.2], [0.1, 0.8]]\n", "hmm = HiddenMarkovModel(umbrella_transition_model, umbrella_sensor_model)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Given evidence T, F, T, F and T, we want to calculate the probability distribution for the fourth day with a fixed lag of 2 days.\n", "
\n", "Let `e_t = False`" ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0.1111111111111111, 0.8888888888888888]" ] }, "execution_count": 82, "metadata": {}, "output_type": "execute_result" } ], "source": [ "e_t = F\n", "evidence = [T, F, T, F, T]\n", "fixed_lag_smoothing(e_t, hmm, d=2, ev=evidence, t=4)" ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0.9938650306748466, 0.006134969325153394]" ] }, "execution_count": 83, "metadata": {}, "output_type": "execute_result" } ], "source": [ "e_t = T\n", "evidence = [T, T, F, T, T]\n", "fixed_lag_smoothing(e_t, hmm, d=1, ev=evidence, t=4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We cannot calculate probability distributions when $t$ is less than $d$" ] }, { "cell_type": "code", "execution_count": 84, "metadata": {}, "outputs": [], "source": [ "fixed_lag_smoothing(e_t, hmm, d=5, ev=evidence, t=4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As expected, the output is `None`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### PARTICLE FILTERING\n", "The filtering problem is too expensive to solve using the previous methods for problems with large or continuous state spaces.\n", "Particle filtering is a method that can solve the same problem but when the state space is a lot larger, where we wouldn't be able to do these computations in a reasonable amount of time as fast, as time goes by, and we want to keep track of things as they happen.\n", "
\n", "The downside is that it is a sampling method and hence isn't accurate, but the more samples we're willing to take, the more accurate we'd get.\n", "
\n", "In this method, instead of keping track of the probability distribution, we will drop particles in a similar proportion at the required regions.\n", "The internal representation of this distribution is usually a list of particles with coordinates in the state-space.\n", "A particle is just a new name for a sample.\n", "\n", "Particle filtering can be divided into four steps:\n", "1. __Initialization__: \n", "If we have some idea about the prior probability distribution, we drop the initial particles accordingly, or else we just drop them uniformly over the state space.\n", "\n", "2. __Forward pass__: \n", "As time goes by and measurements come in, we are going to move the selected particles into the grid squares that makes the most sense in terms of representing the distribution that we are trying to track.\n", "When time goes by, we just loop through all our particles and try to simulate what could happen to each one of them by sampling its next position from the transition model.\n", "This is like prior sampling - samples' frequencies reflect the transition probabilities.\n", "If we have enough samples we are pretty close to exact values.\n", "We work through the list of particles, one particle at a time, all we do is stochastically simulate what the outcome might be.\n", "If we had no dimension of time, and we had no new measurements come in, this would be exactly the same as what we did in prior sampling.\n", "\n", "3. __Reweight__:\n", "As observations come in, don't sample the observations, fix them and downweight the samples based on the evidence just like in likelihood weighting.\n", "$$w(x) = P(e/x)$$\n", "$$B(X) \\propto P(e/X)B'(X)$$\n", "
\n", "As before, the probabilities don't sum to one, since most have been downweighted.\n", "They sum to an approximation of $P(e)$.\n", "To normalize the resulting distribution, we can divide by $P(e)$\n", "
\n", "Likelihood weighting wasn't the best thing for Bayesian networks, because we were not accounting for the incoming evidence so we were getting samples from the prior distribution, in some sense not the right distribution, so we might end up with a lot of particles with low weights. \n", "These samples were very uninformative and the way we fixed it then was by using __Gibbs sampling__.\n", "Theoretically, Gibbs sampling can be run on a HMM, but as we iterated over the process infinitely many times in a Bayesian network, we cannot do that here as we have new incoming evidence and we also need computational cycles to propagate through time.\n", "
\n", "A lot of samples with very low weight and they are not representative of the _actual probability distribution_.\n", "So if we keep running likelihood weighting, we keep propagating the samples with smaller weights and carry out computations for that even though these samples have no significant contribution to the actual probability distribution.\n", "Which is why we require this last step.\n", "\n", "4. __Resample__:\n", "Rather than tracking weighted samples, we _resample_.\n", "We choose from our weighted sample distribution as many times as the number of particles we initially had and we replace these particles too, so that we have a constant number of particles.\n", "This is equivalent to renormalizing the distribution.\n", "The samples with low weight are rarely chosen in the new distribution after resampling.\n", "This newer set of particles after resampling is in some sense more representative of the actual distribution and so we are better allocating our computational cycles.\n", "Now the update is complete for this time step, continue with the next one.\n", "\n", "
\n", "Let's see how this is implemented in the module." ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def particle_filtering(e, N, HMM):\n",
       "    """Particle filtering considering two states variables."""\n",
       "    dist = [0.5, 0.5]\n",
       "    # Weight Initialization\n",
       "    w = [0 for _ in range(N)]\n",
       "    # STEP 1\n",
       "    # Propagate one step using transition model given prior state\n",
       "    dist = vector_add(scalar_vector_product(dist[0], HMM.transition_model[0]),\n",
       "                      scalar_vector_product(dist[1], HMM.transition_model[1]))\n",
       "    # Assign state according to probability\n",
       "    s = ['A' if probability(dist[0]) else 'B' for _ in range(N)]\n",
       "    w_tot = 0\n",
       "    # Calculate importance weight given evidence e\n",
       "    for i in range(N):\n",
       "        if s[i] == 'A':\n",
       "            # P(U|A)*P(A)\n",
       "            w_i = HMM.sensor_dist(e)[0] * dist[0]\n",
       "        if s[i] == 'B':\n",
       "            # P(U|B)*P(B)\n",
       "            w_i = HMM.sensor_dist(e)[1] * dist[1]\n",
       "        w[i] = w_i\n",
       "        w_tot += w_i\n",
       "\n",
       "    # Normalize all the weights\n",
       "    for i in range(N):\n",
       "        w[i] = w[i] / w_tot\n",
       "\n",
       "    # Limit weights to 4 digits\n",
       "    for i in range(N):\n",
       "        w[i] = float("{0:.4f}".format(w[i]))\n",
       "\n",
       "    # STEP 2\n",
       "\n",
       "    s = weighted_sample_with_replacement(N, s, w)\n",
       "\n",
       "    return s\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(particle_filtering)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here, `scalar_vector_product` and `vector_add` are helper functions to help with vector math and `weighted_sample_with_replacement` resamples from a weighted sample and replaces the original sample, as is obvious from the name.\n", "
\n", "This implementation considers two state variables with generic names 'A' and 'B'.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here's how we can use `particle_filtering` on our umbrella HMM, though it doesn't make much sense using particle filtering on a problem with such a small state space.\n", "It is just to get familiar with the syntax." ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [], "source": [ "umbrella_transition_model = [[0.7, 0.3], [0.3, 0.7]]\n", "umbrella_sensor_model = [[0.9, 0.2], [0.1, 0.8]]\n", "hmm = HiddenMarkovModel(umbrella_transition_model, umbrella_sensor_model)" ] }, { "cell_type": "code", "execution_count": 87, "metadata": { "scrolled": false }, "outputs": [ { "data": { "text/plain": [ "['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A']" ] }, "execution_count": 87, "metadata": {}, "output_type": "execute_result" } ], "source": [ "particle_filtering(T, 10, hmm)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We got 5 samples from state `A` and 5 samples from state `B`" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['A', 'B', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B']" ] }, "execution_count": 88, "metadata": {}, "output_type": "execute_result" } ], "source": [ "particle_filtering([F, T, F, F, T], 10, hmm)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This time we got 2 samples from state `A` and 8 samples from state `B`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Comparing runtimes for these algorithms will not be useful, as each solves the filtering task efficiently for a different scenario.\n", "
\n", "`forward_backward` calculates the exact probability distribution.\n", "
\n", "`fixed_lag_smoothing` calculates an approximate distribution and its runtime will depend on the value of the lag chosen.\n", "
\n", "`particle_filtering` is an efficient method for approximating distributions for a very large or continuous state space." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## MONTE CARLO LOCALIZATION\n", "In the domain of robotics, particle filtering is used for _robot localization_.\n", "__Localization__ is the problem of finding out where things are, in this case, we want to find the position of a robot in a continuous state space.\n", "
\n", "__Monte Carlo Localization__ is an algorithm for robots to _localize_ using a _particle filter_.\n", "Given a map of the environment, the algorithm estimates the position and orientation of a robot as it moves and senses the environment.\n", "
\n", "Initially, particles are distributed uniformly over the state space, ie the robot has no information of where it is and assumes it is equally likely to be at any point in space.\n", "
\n", "When the robot moves, it analyses the incoming evidence to shift and change the probability to better approximate the probability distribution of its position.\n", "The particles are then resampled based on their weights.\n", "
\n", "Gradually, as more evidence comes in, the robot gets better at approximating its location and the particles converge towards the actual position of the robot.\n", "
\n", "The pose of a robot is defined by its two Cartesian coordinates with values $x$ and $y$ and its direction with value $\\theta$.\n", "We use the kinematic equations of motion to model a deterministic state prediction.\n", "This is our motion model (or transition model).\n", "
\n", "Next, we need a sensor model.\n", "There can be two kinds of sensor models, the first assumes that the sensors detect _stable_, _recognizable_ features of the environment called __landmarks__.\n", "The robot senses the location and bearing of each landmark and updates its belief according to that.\n", "We can also assume the noise in measurements to be Gaussian, to simplify things.\n", "
\n", "Another kind of sensor model is used for an array of range sensors, each of which has a fixed bearing relative to the robot.\n", "These sensors provide a set of range values in each direction.\n", "This will also be corrupted by Gaussian noise, but we can assume that the errors for different beam directions are independent and identically distributed.\n", "
\n", "After evidence comes in, the robot updates its belief state and reweights the particle distribution to better aproximate the actual distribution.\n", "
\n", "
\n", "Let's have a look at how this algorithm is implemented in the module" ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def monte_carlo_localization(a, z, N, P_motion_sample, P_sensor, m, S=None):\n",
       "    """Monte Carlo localization algorithm from Fig 25.9"""\n",
       "\n",
       "    def ray_cast(sensor_num, kin_state, m):\n",
       "        return m.ray_cast(sensor_num, kin_state)\n",
       "\n",
       "    M = len(z)\n",
       "    W = [0]*N\n",
       "    S_ = [0]*N\n",
       "    W_ = [0]*N\n",
       "    v = a['v']\n",
       "    w = a['w']\n",
       "\n",
       "    if S is None:\n",
       "        S = [m.sample() for _ in range(N)]\n",
       "\n",
       "    for i in range(N):\n",
       "        S_[i] = P_motion_sample(S[i], v, w)\n",
       "        W_[i] = 1\n",
       "        for j in range(M):\n",
       "            z_ = ray_cast(j, S_[i], m)\n",
       "            W_[i] = W_[i] * P_sensor(z[j], z_)\n",
       "\n",
       "    S = weighted_sample_with_replacement(N, S_, W_)\n",
       "    return S\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(monte_carlo_localization)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Our implementation of Monte Carlo Localization uses the range scan method.\n", "The `ray_cast` helper function casts rays in different directions and stores the range values.\n", "
\n", "`a` stores the `v` and `w` components of the robot's velocity.\n", "
\n", "`z` is a range scan.\n", "
\n", "`P_motion_sample` is the motion or transition model.\n", "
\n", "`P_sensor` is the range sensor noise model.\n", "
\n", "`m` is the 2D map of the environment\n", "
\n", "`S` is a vector of samples of size N" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We'll now define a simple 2D map to run Monte Carlo Localization on.\n", "
\n", "Let's say this is the map we want\n", "
" ] }, { "cell_type": "code", "execution_count": 90, "metadata": { "scrolled": true }, "outputs": [ { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAfAAAAFaCAYAAADhKw9uAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAASOUlEQVR4nO3df4ztd13n8dd779hAKSwlvaj9oaVaUJao0JGARFYpxIJIMbvZBcUUf6SJP6AQFIsmaGI0ZDWoiQZTC7aJDailArqKdPEHmrDVuQWEclEaiu2FSoclCLrGWnz7x5yScXrnzvSc750zn9PHI7mZ8+M75/v+3Dszz/s958w51d0BAMbyn5Y9AADw4Ak4AAxIwAFgQAIOAAMScAAYkIADwIAEHAAGJOBwiFXVx6vq2Tsue2lV/cUEt91V9dWL3g6wHAIOAAMScBhYVZ1bVW+tqs2quqOqXr7tuqdW1Xur6rNVdXdV/UpVnTG77j2zzT5QVf9YVf+zqr6lqk5U1aur6p7Z57ywqp5XVX9bVZ+pqp/Yz+3Pru+qenlVfayqPl1VP19VfubARHwzwaBmMfy9JB9Icl6SS5O8oqq+bbbJF5K8Msk5SZ4+u/6HkqS7nznb5uu7+6zu/q3Z+S9L8rDZ7b02ya8neUmSS5J8c5LXVtVFe93+Nt+ZZD3JU5JcnuT7plg7kJTXQofDq6o+nq1A3rft4jOS3JrkVUl+p7u/Ytv2r0ny+O7+3pPc1iuS/Nfu/s7Z+U5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3ywWz9TBjyZSyr6s1J3pvkCVV1oqq+P8nrkjynqj6arWc1v26ZM85rl7X9SpJHJrl59nPk15Y65Bx2WddK2GVtb0py0exXy96S5IpF7jnxUqoAMKBDewQOAOxOwAFgQAIOAAMScAAYkIADwIAEHAAGJOAAMKB/B24h+wUcnnY9AAAAAElFTkSuQmCC\n", "text/plain": [ "
" ] }, "metadata": { "needs_background": "light" }, "output_type": "display_data" } ], "source": [ "m = MCLmap([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0],\n", " [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0],\n", " [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0],\n", " [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0],\n", " [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0],\n", " [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0],\n", " [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0],\n", " [0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0],\n", " [0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],\n", " [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0],\n", " [0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0]])\n", "\n", "heatmap(m.m, cmap='binary')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's define the motion model as a function `P_motion_sample`." ] }, { "cell_type": "code", "execution_count": 91, "metadata": {}, "outputs": [], "source": [ "def P_motion_sample(kin_state, v, w):\n", " \"\"\"Sample from possible kinematic states.\n", " Returns from a single element distribution (no uncertainity in motion)\"\"\"\n", " pos = kin_state[:2]\n", " orient = kin_state[2]\n", "\n", " # for simplicity the robot first rotates and then moves\n", " orient = (orient + w)%4\n", " for _ in range(orient):\n", " v = (v[1], -v[0])\n", " pos = vector_add(pos, v)\n", " return pos + (orient,)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Define the sensor model as a function `P_sensor`." ] }, { "cell_type": "code", "execution_count": 92, "metadata": {}, "outputs": [], "source": [ "def P_sensor(x, y):\n", " \"\"\"Conditional probability for sensor reading\"\"\"\n", " # Need not be exact probability. Can use a scaled value.\n", " if x == y:\n", " return 0.8\n", " elif abs(x - y) <= 2:\n", " return 0.05\n", " else:\n", " return 0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Initializing variables." ] }, { "cell_type": "code", "execution_count": 93, "metadata": {}, "outputs": [], "source": [ "a = {'v': (0, 0), 'w': 0}\n", "z = (2, 4, 1, 6)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's run `monte_carlo_localization` with these parameters to find a sample distribution S." ] }, { "cell_type": "code", "execution_count": 94, "metadata": {}, "outputs": [], "source": [ "S = monte_carlo_localization(a, z, 1000, P_motion_sample, P_sensor, m)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's plot the values in the sample distribution `S`." ] }, { "cell_type": "code", "execution_count": 95, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "GRID:\n", " 0 0 12 0 143 14 0 0 0 0 0 0 0 0 0 0 0\n", " 0 0 0 0 17 52 201 6 0 0 0 0 0 0 0 0 0\n", " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", " 0 0 0 3 5 19 9 3 0 0 0 0 0 0 0 0 0\n", " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", " 0 0 6 166 0 21 0 0 0 0 0 0 0 0 0 0 0\n", " 0 0 0 1 11 75 0 0 0 0 0 0 0 0 0 0 0\n", " 73 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0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Jblo9v5FST64xFkmVVXnJ/nFJK/u7v+37Hmm0N2f7+6ndveZs68je5I8f/Z3cDv4oyQvTZKqekaSwzPH/7p2yAZ89uSMn0vykax+QfmD7r55uVNN4sVJfiKrZ6efnf16xbKHYlNvSHJ1VX0uyQ8k+ZUlzzOJ2aMK1yS5Mcnns/o1YciXsayq9yX5VJJnVtWeqvrpJO9Mcl5VfTmrz2p+5zJn3KoN9vZbSY5Nct3s68jvLHXILdhgX9vCBnt7b5KzZj9a9v4kF83zyImXUgWAAR2yZ+AAwMYEHAAGJOAAMCABB4ABCTgADEjAAWBAAg4AA/r/85kBLqIO9qEAAAAASUVORK5CYII=\n", "text/plain": [ "
" ] }, "metadata": { "needs_background": "light" }, "output_type": "display_data" } ], "source": [ "grid = [[0]*17 for _ in range(11)]\n", "for x, y, _ in S:\n", " if 0 <= x < 11 and 0 <= y < 17:\n", " grid[x][y] += 1\n", "print(\"GRID:\")\n", "print_table(grid)\n", "heatmap(grid, cmap='Oranges')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The distribution is highly concentrated at `(5, 3)`, but the robot is not very confident about its position as some other cells also have high probability values." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's look at another scenario." ] }, { "cell_type": "code", "execution_count": 96, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "GRID:\n", "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", "0 0 0 0 0 0 0 0 1000 0 0 0 0 0 0 0 0\n", "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0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OH5ySPX/M8J8oPJfnddQ+xClX14iSf6e471j3LCfDkJN9dVbdW1R9X1Xcu82CncsDrKLeN/Wlsq6o6K8k7k7y6u7+47nlWoapelOSB7r5t3bOs2L4klyZ5S3c/PcnfZO6p2K+weE74iiRPSnJekjOr6uXrnYqvRVX9dDaemrtx3bMsq6rOSPLTSd6w7llOkH1Jzs7G06c/keTXq+porTsup3LADyW5cNP1CzL01N5WVfUN2Yj3jd1987rnWaFnJ3lxVX0qG095PLeqfnW9I63EoSSHuvuRMyU3ZSPoe8HzktzT3Ye7+++S3Jzku9Y80yp9rqqekCSLj0udsjzVVNWVSV6U5D/23nhTj3+SjR8m71h8H7kgye1V9c1rnWp1DiW5uTf8STbOVO76RXqncsD/NMklVfWkqjo9Gy+sefeaZ1ra4qettya5q7vfvO55Vqm7X9/dF3T3Rdn4+/qD7h5/NNfdf5nkvqp6yuKmy5J8bI0jrdK9SZ5ZVWcs/m1elj3yAr2Fdye5cnH5yiTvWuMsK1VVlyf5ySQv7u7/u+55VqG7P9Ldj+/uixbfRw4luXTxNbgX/GaS5yZJVT05yelZ4v+6dsoGfPHijB9L8nvZ+Iby691953qnWolnJ/mBbBydfnjx54XrHoodvTLJjVX1Z0m+I8l/XfM8K7E4q3BTktuTfCQb3xNGvo1lVb09yQeTPKWqDlXVDyd5U5LnV9UnsvGq5jetc8bd2mZtv5jkMUluWXwf+eW1DrkL26xrT9hmbW9LcvHiV8vekeTKZc6ceCtVABjolD0CBwC2J+AAMJCAA8BAAg4AAwk4AAwk4AAwkIADwED/H3ZBvi8oWJldAAAAAElFTkSuQmCC\n", "text/plain": [ "
" ] }, "metadata": { "needs_background": "light" }, "output_type": "display_data" } ], "source": [ "a = {'v': (0, 1), 'w': 0}\n", "z = (2, 3, 5, 7)\n", "S = monte_carlo_localization(a, z, 1000, P_motion_sample, P_sensor, m, S)\n", "grid = [[0]*17 for _ in range(11)]\n", "for x, y, _ in S:\n", " if 0 <= x < 11 and 0 <= y < 17:\n", " grid[x][y] += 1\n", "print(\"GRID:\")\n", "print_table(grid)\n", "heatmap(grid, cmap='Oranges')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this case, the robot is 99.9% certain that it is at position `(6, 7)`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## DECISION THEORETIC AGENT\n", "We now move into the domain of probabilistic decision making.\n", "
\n", "To make choices between different possible plans in a certain situation in a given environment, an agent must have _preference_ between the possible outcomes of the various plans.\n", "
\n", "__Utility theory__ is used to represent and reason with preferences.\n", "The agent prefers states with a higher _utility_.\n", "While constructing multi-agent systems, one major element in the design is the mechanism the agents use for making decisions about which actions to adopt in order to achieve their goals.\n", "What is usually required is a mechanism which ensures that the actions adopted lead to benefits for both individual agents, and the community of which they are part.\n", "The utility of a state is _relative_ to an agent.\n", "
\n", "Preferences, as expressed by utilities, are combined with probabilities in the general theory of rational decisions called __decision theory__.\n", "
\n", "An agent is said to be _rational_ if and only if it chooses the action that yields the highest expected utility, averaged over all the possible outcomes of the action." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here we'll see how a decision-theoretic agent is implemented in the module." ] }, { "cell_type": "code", "execution_count": 97, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
def DTAgentProgram(belief_state):\n",
       "    """A decision-theoretic agent. [Figure 13.1]"""\n",
       "    def program(percept):\n",
       "        belief_state.observe(program.action, percept)\n",
       "        program.action = argmax(belief_state.actions(),\n",
       "                                key=belief_state.expected_outcome_utility)\n",
       "        return program.action\n",
       "    program.action = None\n",
       "    return program\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(DTAgentProgram)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `DTAgentProgram` function is pretty self-explanatory.\n", "
\n", "It encapsulates a function `program` that takes in an observation or a `percept`, updates its `belief_state` and returns the action that maximizes the `expected_outcome_utility`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## INFORMATION GATHERING AGENT\n", "Before we discuss what an information gathering agent is, we'll need to know what decision networks are.\n", "For an agent in an environment, a decision network represents information about the agent's current state, its possible actions, the state that will result from the agent's action, and the utility of that state.\n", "Decision networks have three primary kinds of nodes which are:\n", "1. __Chance nodes__: These represent random variables, just like in Bayesian networks.\n", "2. __Decision nodes__: These represent points where the decision-makes has a choice between different actions and the decision maker tries to find the optimal decision at these nodes with regard to the cost, safety and resulting utility.\n", "3. __Utility nodes__: These represent the agent's utility function.\n", "A description of the agent's utility as a function is associated with a utility node.\n", "
\n", "
\n", "To evaluate a decision network, we do the following:\n", "1. Initialize the evidence variables according to the current state.\n", "2. Calculate posterior probabilities for each possible value of the decision node and calculate the utility resulting from that action.\n", "3. Return the action with the highest utility.\n", "
\n", "Let's have a look at the implementation of the `DecisionNetwork` class." ] }, { "cell_type": "code", "execution_count": 98, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
class DecisionNetwork(BayesNet):\n",
       "    """An abstract class for a decision network as a wrapper for a BayesNet.\n",
       "    Represents an agent's current state, its possible actions, reachable states\n",
       "    and utilities of those states."""\n",
       "\n",
       "    def __init__(self, action, infer):\n",
       "        """action: a single action node\n",
       "        infer: the preferred method to carry out inference on the given BayesNet"""\n",
       "        super(DecisionNetwork, self).__init__()\n",
       "        self.action = action\n",
       "        self.infer = infer\n",
       "\n",
       "    def best_action(self):\n",
       "        """Return the best action in the network"""\n",
       "        return self.action\n",
       "\n",
       "    def get_utility(self, action, state):\n",
       "        """Return the utility for a particular action and state in the network"""\n",
       "        raise NotImplementedError\n",
       "\n",
       "    def get_expected_utility(self, action, evidence):\n",
       "        """Compute the expected utility given an action and evidence"""\n",
       "        u = 0.0\n",
       "        prob_dist = self.infer(action, evidence, self).prob\n",
       "        for item, _ in prob_dist.items():\n",
       "            u += prob_dist[item] * self.get_utility(action, item)\n",
       "\n",
       "        return u\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(DecisionNetwork)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `DecisionNetwork` class inherits from `BayesNet` and has a few extra helper methods.\n", "
\n", "`best_action` returns the best action in the network.\n", "
\n", "`get_utility` is an abstract method which is supposed to return the utility of a particular action and state in the network.\n", "
\n", "`get_expected_utility` computes the expected utility, given an action and evidence.\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Before we proceed, we need to know a few more terms.\n", "
\n", "Having __perfect information__ refers to a state of being fully aware of the current state, the cost functions and the outcomes of actions.\n", "This in turn allows an agent to find the exact utility value of each state.\n", "If an agent has perfect information about the environment, maximum expected utility calculations are exact and can be computed with absolute certainty.\n", "
\n", "In decision theory, the __value of perfect information__ (VPI) is the price that an agent would be willing to pay in order to gain access to _perfect information_.\n", "VPI calculations are extensively used to calculate expected utilities for nodes in a decision network.\n", "
\n", "For a random variable $E_j$ whose value is currently unknown, the value of discovering $E_j$, given current information $e$ must average over all possible values $e_{jk}$ that we might discover for $E_j$, using our _current_ beliefs about its value.\n", "The VPI of $E_j$ is then given by:\n", "
\n", "
\n", "$$VPI_e(E_j) = \\left(\\sum_{k}P(E_j=e_{jk}\\ |\\ e) EU(\\alpha_{e_{jk}}\\ |\\ e, E_j=e_{jk})\\right) - EU(\\alpha\\ |\\ e)$$\n", "
\n", "VPI is _non-negative_, _non-additive_ and _order-indepentent_." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "An information gathering agent is an agent with certain properties that explores decision networks as and when required with heuristics driven by VPI calculations of nodes.\n", "A sensible agent should ask questions in a reasonable order, should avoid asking irrelevant questions, should take into account the importance of each piece of information in relation to its cost and should stop asking questions when that is appropriate.\n", "_VPI_ is used as the primary heuristic to consider all these points in an information gathering agent as the agent ultimately wants to maximize the utility and needs to find the optimal cost and extent of finding the required information.\n", "
\n", "As an overview, an information gathering agent works by repeatedly selecting the observations with the highest information value, until the cost of the next observation is greater than its expected benefit.\n", "
\n", "The `InformationGatheringAgent` class is an abstract class that inherits from `Agent` and works on the principles discussed above.\n", "Let's have a look.\n", "
" ] }, { "cell_type": "code", "execution_count": 99, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
class InformationGatheringAgent(Agent):\n",
       "    """A simple information gathering agent. The agent works by repeatedly selecting\n",
       "    the observation with the highest information value, until the cost of the next\n",
       "    observation is greater than its expected benefit. [Figure 16.9]"""\n",
       "\n",
       "    def __init__(self, decnet, infer, initial_evidence=None):\n",
       "        """decnet: a decision network\n",
       "        infer: the preferred method to carry out inference on the given decision network\n",
       "        initial_evidence: initial evidence"""\n",
       "        self.decnet = decnet\n",
       "        self.infer = infer\n",
       "        self.observation = initial_evidence or []\n",
       "        self.variables = self.decnet.nodes\n",
       "\n",
       "    def integrate_percept(self, percept):\n",
       "        """Integrate the given percept into the decision network"""\n",
       "        raise NotImplementedError\n",
       "\n",
       "    def execute(self, percept):\n",
       "        """Execute the information gathering algorithm"""\n",
       "        self.observation = self.integrate_percept(percept)\n",
       "        vpis = self.vpi_cost_ratio(self.variables)\n",
       "        j = argmax(vpis)\n",
       "        variable = self.variables[j]\n",
       "\n",
       "        if self.vpi(variable) > self.cost(variable):\n",
       "            return self.request(variable)\n",
       "\n",
       "        return self.decnet.best_action()\n",
       "\n",
       "    def request(self, variable):\n",
       "        """Return the value of the given random variable as the next percept"""\n",
       "        raise NotImplementedError\n",
       "\n",
       "    def cost(self, var):\n",
       "        """Return the cost of obtaining evidence through tests, consultants or questions"""\n",
       "        raise NotImplementedError\n",
       "\n",
       "    def vpi_cost_ratio(self, variables):\n",
       "        """Return the VPI to cost ratio for the given variables"""\n",
       "        v_by_c = []\n",
       "        for var in variables:\n",
       "            v_by_c.append(self.vpi(var) / self.cost(var))\n",
       "        return v_by_c\n",
       "\n",
       "    def vpi(self, variable):\n",
       "        """Return VPI for a given variable"""\n",
       "        vpi = 0.0\n",
       "        prob_dist = self.infer(variable, self.observation, self.decnet).prob\n",
       "        for item, _ in prob_dist.items():\n",
       "            post_prob = prob_dist[item]\n",
       "            new_observation = list(self.observation)\n",
       "            new_observation.append(item)\n",
       "            expected_utility = self.decnet.get_expected_utility(variable, new_observation)\n",
       "            vpi += post_prob * expected_utility\n",
       "\n",
       "        vpi -= self.decnet.get_expected_utility(variable, self.observation)\n",
       "        return vpi\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(InformationGatheringAgent)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `cost` method is an abstract method that returns the cost of obtaining the evidence through tests, consultants, questions or any other means.\n", "
\n", "The `request` method returns the value of the given random variable as the next percept.\n", "
\n", "The `vpi_cost_ratio` method returns a list of VPI divided by cost for each variable in the `variables` list provided to it.\n", "
\n", "The `vpi` method calculates the VPI for a given variable\n", "
\n", "And finally, the `execute` method executes the general information gathering algorithm, as described in __figure 16.9__ in the book.\n", "
\n", "Our agent implements a form of information gathering that is called __myopic__ as the VPI formula is used shortsightedly here.\n", "It calculates the value of information as if only a single evidence variable will be acquired.\n", "This is similar to greedy search, where we do not look at the bigger picture and aim for local optimizations to hopefully reach the global optimum.\n", "This often works well in practice but a myopic agent might hastily take an action when it would have been better to request more variables before taking an action.\n", "A _conditional plan_, on the other hand might work better for some scenarios.\n", "
\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With this we conclude this notebook." ] } ], "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.6.9" } }, "nbformat": 4, "nbformat_minor": 2 }