{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## February 26, 2020\n", "\n", "AIMA Chapter 14" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "from probability import *\n", "from utils import print_table\n", "from notebook import psource, pseudocode, heatmap" ] }, { "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 consists 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": 16, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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": 17, "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": "code", "execution_count": 18, "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": 19, "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": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.09999999999999998" ] }, "execution_count": 20, "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": 21, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "BayesNet([('Burglary', ''), ('Earthquake', ''), ('Alarm', 'Burglary Earthquake'), ('JohnCalls', 'Alarm'), ('MaryCalls', 'Alarm')])" ] }, "execution_count": 22, "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": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "probability.BayesNode" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(burglary.variable_node('Alarm'))" ] }, { "cell_type": "code", "execution_count": 24, "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": 24, "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": 25, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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": 26, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.2841718353643929" ] }, "execution_count": 27, "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": 28, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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": 29, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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": 30, "metadata": {}, "outputs": [], "source": [ "f5 = make_factor('MaryCalls', {'JohnCalls': True, 'MaryCalls': True}, burglary)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f5" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{(True,): 0.7, (False,): 0.01}" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f5.cpt" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['Alarm']" ] }, "execution_count": 33, "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": 34, "metadata": {}, "outputs": [], "source": [ "new_factor = make_factor('MaryCalls', {'Alarm': True}, burglary)" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{(True,): 0.7, (False,): 0.30000000000000004}" ] }, "execution_count": 35, "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": 36, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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": 37, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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": 38, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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": 39, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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.\n", "\n", "#### 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": 40, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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": 41, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'False: 0.716, True: 0.284'" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "elimination_ask('Burglary', dict(JohnCalls=True, MaryCalls=True), burglary).show_approx()" ] }, { "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": 42, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "185 µs ± 524 ns 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": 43, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "445 µs ± 4.27 µ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": [ "We observe that variable elimination was faster than enumeration as we had expected but the gain in speed is not a lot, in fact it is just about 30% faster.\n", "
\n", "This happened because the bayesian network in question is pretty small, with just 5 nodes, some of which aren't even required in the inference process.\n", "For more complicated networks, variable elimination will be significantly faster and runtime will reduce 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": 44, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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": 45, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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": 46, "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": 47, "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": 48, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.489\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": 49, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.512\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": 50, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.7890625\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": 51, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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": 52, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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": 53, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.8264299802761341" ] }, "execution_count": 53, "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": 54, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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": 55, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "({'Rain': True, 'Cloudy': True, 'Sprinkler': False, 'WetGrass': True}, 0.8)" ] }, "execution_count": 55, "metadata": {}, "output_type": "execute_result" } ], "source": [ "weighted_sample(sprinkler, dict(Rain=True))" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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": 57, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'False: 0.194, True: 0.806'" ] }, "execution_count": 57, "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": 58, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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": 59, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'False: 0.185, True: 0.815'" ] }, "execution_count": 59, "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": 60, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "15.9 ms ± 60.5 µs 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": 61, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "19.3 ms ± 32.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" ] } ], "source": [ "%%timeit\n", "rejection_sampling('Cloudy', dict(Rain=True), sprinkler, 1000)" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3.16 ms ± 25.3 µ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": 63, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "15.6 ms ± 102 µs 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\n", "\n", "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": 64, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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": 65, "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": 66, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0.9, 0.2]" ] }, "execution_count": 66, "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": 67, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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": 68, "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": 69, "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 kt. In the umbrella example, we can compute the backward message from **Day 2** to **Day 1** by using the `backward` function. The `backward` function has as parameters the object created by the **`HiddenMarkovModel`** class, the evidence in **Day 2** (in our case is **True**), and the initial probabilities of being in state in time t+1. Since no observation is available then it will be [1, 1]. The `backward` function will return a list with the conditional probabilities." ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\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": 57, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0.6272727272727272, 0.37272727272727274]" ] }, "execution_count": 57, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b = [1, 1]\n", "backward(hmm, b, ev=True)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'hmm' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 6\u001b[0m scalar_vector_product(prediction[1], HMM.transition_model[1]))\n\u001b[1;32m 7\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 8\u001b[0;31m \u001b[0mxbackward\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mhmm\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mev\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: name 'hmm' is not defined" ] } ], "source": [ "def xbackward(HMM, b, ev):\n", " sensor_dist = HMM.sensor_dist(ev)\n", " prediction = element_wise_product(sensor_dist, b)\n", "\n", " return vector_add(scalar_vector_product(prediction[0], HMM.transition_model[0]),\n", " scalar_vector_product(prediction[1], HMM.transition_model[1]))\n", "\n", "xbackward(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": 58, "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": 58, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pseudocode('Forward-Backward')" ] }, { "cell_type": "code", "execution_count": 59, "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": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.6" } }, "nbformat": 4, "nbformat_minor": 2 }