{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# KNOWLEDGE\n", "\n", "The [knowledge](https://github.com/aimacode/aima-python/blob/master/knowledge.py) module covers **Chapter 19: Knowledge in Learning** from Stuart Russel's and Peter Norvig's book *Artificial Intelligence: A Modern Approach*.\n", "\n", "Execute the cell below to get started." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "from knowledge import *\n", "from notebook import psource" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## CONTENTS\n", "\n", "* Overview\n", "* Inductive Logic Programming (FOIL)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## OVERVIEW\n", "\n", "Like the [learning module](https://github.com/aimacode/aima-python/blob/master/learning.ipynb), this chapter focuses on methods for generating a model/hypothesis for a domain; however, unlike the learning chapter, here we use prior knowledge to help us learn from new experiences and to find a proper hypothesis.\n", "\n", "### First-Order Logic\n", "\n", "Usually knowledge in this field is represented as **first-order logic**, a type of logic that uses variables and quantifiers in logical sentences. Hypotheses are represented by logical sentences with variables, while examples are logical sentences with set values instead of variables. The goal is to assign a value to a special first-order logic predicate, called **goal predicate**, for new examples given a hypothesis. We learn this hypothesis by infering knowledge from some given examples.\n", "\n", "### Representation\n", "\n", "In this module, we use dictionaries to represent examples, with keys being the attribute names and values being the corresponding example values. Examples also have an extra boolean field, 'GOAL', for the goal predicate. A hypothesis is represented as a list of dictionaries. Each dictionary in that list represents a disjunction. Inside these dictionaries/disjunctions we have conjunctions.\n", "\n", "For example, say we want to predict if an animal (cat or dog) will take an umbrella given whether or not it rains or the animal wears a coat. The goal value is 'take an umbrella' and is denoted by the key 'GOAL'. An example:\n", "\n", "`{'Species': 'Cat', 'Coat': 'Yes', 'Rain': 'Yes', 'GOAL': True}`\n", "\n", "A hypothesis can be the following:\n", "\n", "`[{'Species': 'Cat'}]`\n", "\n", "which means an animal will take an umbrella if and only if it is a cat.\n", "\n", "### Consistency\n", "\n", "We say that an example `e` is **consistent** with an hypothesis `h` if the assignment from the hypothesis for `e` is the same as `e['GOAL']`. If the above example and hypothesis are `e` and `h` respectively, then `e` is consistent with `h` since `e['Species'] == 'Cat'`. For `e = {'Species': 'Dog', 'Coat': 'Yes', 'Rain': 'Yes', 'GOAL': True}`, the example is no longer consistent with `h`, since the value assigned to `e` is *False* while `e['GOAL']` is *True*." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Inductive Logic Programming (FOIL)\n", "\n", "Inductive logic programming (ILP) combines inductive methods with the power of first-order representations, concentrating in particular on the representation of hypotheses as logic programs. The general knowledge-based induction problem is to solve the entailment constraint:

\n", "$ Background ∧ Hypothesis ∧ Descriptions \\vDash Classifications $\n", "\n", "for the __unknown__ $Hypothesis$, given the $Background$ knowledge described by $Descriptions$ and $Classifications$.\n", "\n", "\n", "\n", "The first approach to ILP works by starting with a very general rule and gradually specializing\n", "it so that it fits the data.
\n", "This is essentially what happens in decision-tree learning, where a\n", "decision tree is gradually grown until it is consistent with the observations.
To do ILP we\n", "use first-order literals instead of attributes, and the $Hypothesis$ is a set of clauses (set of first order rules, where each rule is similar to a Horn clause) instead of a decision tree.
\n", "\n", "\n", "The FOIL algorithm learns new rules, one at a time, in order to cover all given positive and negative examples.
\n", "More precicely, FOIL contains an inner and an outer while loop.
\n", "- __outer loop__: (function __foil()__) add rules until all positive examples are covered.
\n", " (each rule is a conjuction of literals, which are chosen inside the inner loop)\n", " \n", " \n", "- __inner loop__: (function __new_clause()__) add new literals until all negative examples are covered, and some positive examples are covered.
\n", " - In each iteration, we select/add the most promising literal, according to an estimate of its utility. (function __new_literal()__)
\n", " \n", " - The evaluation function to estimate utility of adding literal $L$ to a set of rules $R$ is (function __gain()__) : \n", " \n", " $$ FoilGain(L,R) = t \\big( \\log_2{\\frac{p_1}{p_1+n_1}} - \\log_2{\\frac{p_0}{p_0+n_0}} \\big) $$\n", " where: \n", " \n", " $p_0: \\text{is the number of possitive bindings of rule R } \\\\ n_0: \\text{is the number of negative bindings of R} \\\\ p_1: \\text{is the is the number of possitive bindings of rule R'}\\\\ n_0: \\text{is the number of negative bindings of R'}\\\\ t: \\text{is the number of possitive bindings of rule R that are still covered after adding literal L to R}$\n", " \n", " - Calculate the extended examples for the chosen literal (function __extend_example()__)
\n", " (the set of examples created by extending example with each possible constant value for each new variable in literal)\n", " \n", "- Finally, the algorithm returns a disjunction of first order rules (= conjuction of literals)\n", "\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
class FOIL_container(FolKB):\n",
       "    """Hold the kb and other necessary elements required by FOIL."""\n",
       "\n",
       "    def __init__(self, clauses=None):\n",
       "        self.const_syms = set()\n",
       "        self.pred_syms = set()\n",
       "        FolKB.__init__(self, clauses)\n",
       "\n",
       "    def tell(self, sentence):\n",
       "        if is_definite_clause(sentence):\n",
       "            self.clauses.append(sentence)\n",
       "            self.const_syms.update(constant_symbols(sentence))\n",
       "            self.pred_syms.update(predicate_symbols(sentence))\n",
       "        else:\n",
       "            raise Exception("Not a definite clause: {}".format(sentence))\n",
       "\n",
       "    def foil(self, examples, target):\n",
       "        """Learn a list of first-order horn clauses\n",
       "        'examples' is a tuple: (positive_examples, negative_examples).\n",
       "        positive_examples and negative_examples are both lists which contain substitutions."""\n",
       "        clauses = []\n",
       "\n",
       "        pos_examples = examples[0]\n",
       "        neg_examples = examples[1]\n",
       "\n",
       "        while pos_examples:\n",
       "            clause, extended_pos_examples = self.new_clause((pos_examples, neg_examples), target)\n",
       "            # remove positive examples covered by clause\n",
       "            pos_examples = self.update_examples(target, pos_examples, extended_pos_examples)\n",
       "            clauses.append(clause)\n",
       "\n",
       "        return clauses\n",
       "\n",
       "    def new_clause(self, examples, target):\n",
       "        """Find a horn clause which satisfies part of the positive\n",
       "        examples but none of the negative examples.\n",
       "        The horn clause is specified as [consequent, list of antecedents]\n",
       "        Return value is the tuple (horn_clause, extended_positive_examples)."""\n",
       "        clause = [target, []]\n",
       "        # [positive_examples, negative_examples]\n",
       "        extended_examples = examples\n",
       "        while extended_examples[1]:\n",
       "            l = self.choose_literal(self.new_literals(clause), extended_examples)\n",
       "            clause[1].append(l)\n",
       "            extended_examples = [sum([list(self.extend_example(example, l)) for example in\n",
       "                                      extended_examples[i]], []) for i in range(2)]\n",
       "\n",
       "        return (clause, extended_examples[0])\n",
       "\n",
       "    def extend_example(self, example, literal):\n",
       "        """Generate extended examples which satisfy the literal."""\n",
       "        # find all substitutions that satisfy literal\n",
       "        for s in self.ask_generator(subst(example, literal)):\n",
       "            s.update(example)\n",
       "            yield s\n",
       "\n",
       "    def new_literals(self, clause):\n",
       "        """Generate new literals based on known predicate symbols.\n",
       "        Generated literal must share atleast one variable with clause"""\n",
       "        share_vars = variables(clause[0])\n",
       "        for l in clause[1]:\n",
       "            share_vars.update(variables(l))\n",
       "        for pred, arity in self.pred_syms:\n",
       "            new_vars = {standardize_variables(expr('x')) for _ in range(arity - 1)}\n",
       "            for args in product(share_vars.union(new_vars), repeat=arity):\n",
       "                if any(var in share_vars for var in args):\n",
       "                    # make sure we don't return an existing rule\n",
       "                    if not Expr(pred, args) in clause[1]:\n",
       "                        yield Expr(pred, *[var for var in args])\n",
       "\n",
       "\n",
       "    def choose_literal(self, literals, examples): \n",
       "        """Choose the best literal based on the information gain."""\n",
       "\n",
       "        return max(literals, key = partial(self.gain , examples = examples))\n",
       "\n",
       "\n",
       "    def gain(self, l ,examples):\n",
       "        """\n",
       "        Find the utility of each literal when added to the body of the clause. \n",
       "        Utility function is: \n",
       "            gain(R, l) = T * (log_2 (post_pos / (post_pos + post_neg)) - log_2 (pre_pos / (pre_pos + pre_neg)))\n",
       "\n",
       "        where: \n",
       "        \n",
       "            pre_pos = number of possitive bindings of rule R (=current set of rules)\n",
       "            pre_neg = number of negative bindings of rule R \n",
       "            post_pos = number of possitive bindings of rule R' (= R U {l} )\n",
       "            post_neg = number of negative bindings of rule R' \n",
       "            T = number of possitive bindings of rule R that are still covered \n",
       "                after adding literal l \n",
       "\n",
       "        """\n",
       "        pre_pos = len(examples[0])\n",
       "        pre_neg = len(examples[1])\n",
       "        post_pos = sum([list(self.extend_example(example, l)) for example in examples[0]], [])           \n",
       "        post_neg = sum([list(self.extend_example(example, l)) for example in examples[1]], []) \n",
       "        if pre_pos + pre_neg ==0 or len(post_pos) + len(post_neg)==0:\n",
       "            return -1\n",
       "        # number of positive example that are represented in extended_examples\n",
       "        T = 0\n",
       "        for example in examples[0]:\n",
       "            represents = lambda d: all(d[x] == example[x] for x in example)\n",
       "            if any(represents(l_) for l_ in post_pos):\n",
       "                T += 1\n",
       "        value = T * (log(len(post_pos) / (len(post_pos) + len(post_neg)) + 1e-12,2) - log(pre_pos / (pre_pos + pre_neg),2))\n",
       "        return value\n",
       "\n",
       "\n",
       "    def update_examples(self, target, examples, extended_examples):\n",
       "        """Add to the kb those examples what are represented in extended_examples\n",
       "        List of omitted examples is returned."""\n",
       "        uncovered = []\n",
       "        for example in examples:\n",
       "            represents = lambda d: all(d[x] == example[x] for x in example)\n",
       "            if any(represents(l) for l in extended_examples):\n",
       "                self.tell(subst(example, target))\n",
       "            else:\n",
       "                uncovered.append(example)\n",
       "\n",
       "        return uncovered\n",
       "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "psource(FOIL_container)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Example Family \n", "Suppose we have the following family relations:\n", "
\n", "![title](images/knowledge_foil_family.png)\n", "
\n", "Given some positive and negative examples of the relation 'Parent(x,y)', we want to find a set of rules that satisfies all the examples.
\n", "\n", "A definition of Parent is $Parent(x,y) \\Leftrightarrow Mother(x,y) \\lor Father(x,y)$, which is the result that we expect from the algorithm. " ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "A, B, C, D, E, F, G, H, I, x, y, z = map(expr, 'ABCDEFGHIxyz')" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "small_family = FOIL_container([expr(\"Mother(Anne, Peter)\"),\n", " expr(\"Mother(Anne, Zara)\"),\n", " expr(\"Mother(Sarah, Beatrice)\"),\n", " expr(\"Mother(Sarah, Eugenie)\"),\n", " expr(\"Father(Mark, Peter)\"),\n", " expr(\"Father(Mark, Zara)\"),\n", " expr(\"Father(Andrew, Beatrice)\"),\n", " expr(\"Father(Andrew, Eugenie)\"),\n", " expr(\"Father(Philip, Anne)\"),\n", " expr(\"Father(Philip, Andrew)\"),\n", " expr(\"Mother(Elizabeth, Anne)\"),\n", " expr(\"Mother(Elizabeth, Andrew)\"),\n", " expr(\"Male(Philip)\"),\n", " expr(\"Male(Mark)\"),\n", " expr(\"Male(Andrew)\"),\n", " expr(\"Male(Peter)\"),\n", " expr(\"Female(Elizabeth)\"),\n", " expr(\"Female(Anne)\"),\n", " expr(\"Female(Sarah)\"),\n", " expr(\"Female(Zara)\"),\n", " expr(\"Female(Beatrice)\"),\n", " expr(\"Female(Eugenie)\"),\n", "])\n", "\n", "target = expr('Parent(x, y)')\n", "\n", "examples_pos = [{x: expr('Elizabeth'), y: expr('Anne')},\n", " {x: expr('Elizabeth'), y: expr('Andrew')},\n", " {x: expr('Philip'), y: expr('Anne')},\n", " {x: expr('Philip'), y: expr('Andrew')},\n", " {x: expr('Anne'), y: expr('Peter')},\n", " {x: expr('Anne'), y: expr('Zara')},\n", " {x: expr('Mark'), y: expr('Peter')},\n", " {x: expr('Mark'), y: expr('Zara')},\n", " {x: expr('Andrew'), y: expr('Beatrice')},\n", " {x: expr('Andrew'), y: expr('Eugenie')},\n", " {x: expr('Sarah'), y: expr('Beatrice')},\n", " {x: expr('Sarah'), y: expr('Eugenie')}]\n", "examples_neg = [{x: expr('Anne'), y: expr('Eugenie')},\n", " {x: expr('Beatrice'), y: expr('Eugenie')},\n", " {x: expr('Mark'), y: expr('Elizabeth')},\n", " {x: expr('Beatrice'), y: expr('Philip')}]" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[Parent(x, y), [Father(x, y)]], [Parent(x, y), [Mother(x, y)]]]\n" ] } ], "source": [ "# run the FOIL algorithm \n", "clauses = small_family.foil([examples_pos, examples_neg], target)\n", "print (clauses)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Indeed the algorithm returned the rule: \n", "
$Parent(x,y) \\Leftrightarrow Mother(x,y) \\lor Father(x,y)$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Suppose that we have some positive and negative results for the relation 'GrandParent(x,y)' and we want to find a set of rules that satisfies the examples.
\n", "One possible set of rules for the relation $Grandparent(x,y)$ could be:
\n", "![title](images/knowledge_FOIL_grandparent.png)\n", "
\n", "Or, if $Background$ included the sentence $Parent(x,y) \\Leftrightarrow [Mother(x,y) \\lor Father(x,y)]$ then: \n", "\n", "$$Grandparent(x,y) \\Leftrightarrow \\exists \\: z \\quad Parent(x,z) \\land Parent(z,y)$$\n" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[Grandparent(x, y), [Parent(x, v_6), Parent(v_6, y)]]]\n" ] } ], "source": [ "target = expr('Grandparent(x, y)')\n", "\n", "examples_pos = [{x: expr('Elizabeth'), y: expr('Peter')},\n", " {x: expr('Elizabeth'), y: expr('Zara')},\n", " {x: expr('Elizabeth'), y: expr('Beatrice')},\n", " {x: expr('Elizabeth'), y: expr('Eugenie')},\n", " {x: expr('Philip'), y: expr('Peter')},\n", " {x: expr('Philip'), y: expr('Zara')},\n", " {x: expr('Philip'), y: expr('Beatrice')},\n", " {x: expr('Philip'), y: expr('Eugenie')}]\n", "examples_neg = [{x: expr('Anne'), y: expr('Eugenie')},\n", " {x: expr('Beatrice'), y: expr('Eugenie')},\n", " {x: expr('Elizabeth'), y: expr('Andrew')},\n", " {x: expr('Elizabeth'), y: expr('Anne')},\n", " {x: expr('Elizabeth'), y: expr('Mark')},\n", " {x: expr('Elizabeth'), y: expr('Sarah')},\n", " {x: expr('Philip'), y: expr('Anne')},\n", " {x: expr('Philip'), y: expr('Andrew')},\n", " {x: expr('Anne'), y: expr('Peter')},\n", " {x: expr('Anne'), y: expr('Zara')},\n", " {x: expr('Mark'), y: expr('Peter')},\n", " {x: expr('Mark'), y: expr('Zara')},\n", " {x: expr('Andrew'), y: expr('Beatrice')},\n", " {x: expr('Andrew'), y: expr('Eugenie')},\n", " {x: expr('Sarah'), y: expr('Beatrice')},\n", " {x: expr('Mark'), y: expr('Elizabeth')},\n", " {x: expr('Beatrice'), y: expr('Philip')}, \n", " {x: expr('Peter'), y: expr('Andrew')}, \n", " {x: expr('Zara'), y: expr('Mark')},\n", " {x: expr('Peter'), y: expr('Anne')},\n", " {x: expr('Zara'), y: expr('Eugenie')}, ]\n", "\n", "clauses = small_family.foil([examples_pos, examples_neg], target)\n", "\n", "print(clauses)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Indeed the algorithm returned the rule: \n", "
$Grandparent(x,y) \\Leftrightarrow \\exists \\: v \\: \\: Parent(x,v) \\land Parent(v,y)$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Example Network\n", "\n", "Suppose that we have the following directed graph and we want to find a rule that describes the reachability between two nodes (Reach(x,y)).
\n", "Such a rule could be recursive, since y can be reached from x if and only if there is a sequence of adjacent nodes from x to y: \n", "\n", "$$ Reach(x,y) \\Leftrightarrow \\begin{cases} \n", " Conn(x,y), \\: \\text{(if there is a directed edge from x to y)} \\\\\n", " \\lor \\quad \\exists \\: z \\quad Reach(x,z) \\land Reach(z,y) \\end{cases}$$\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "\"\"\"\n", "A H\n", "|\\ /|\n", "| \\ / |\n", "v v v v\n", "B D-->E-->G-->I\n", "| / |\n", "| / |\n", "vv v\n", "C F\n", "\"\"\"\n", "small_network = FOIL_container([expr(\"Conn(A, B)\"),\n", " expr(\"Conn(A ,D)\"),\n", " expr(\"Conn(B, C)\"),\n", " expr(\"Conn(D, C)\"),\n", " expr(\"Conn(D, E)\"),\n", " expr(\"Conn(E ,F)\"),\n", " expr(\"Conn(E, G)\"),\n", " expr(\"Conn(G, I)\"),\n", " expr(\"Conn(H, G)\"),\n", " expr(\"Conn(H, I)\")])\n" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[Reach(x, y), [Conn(x, y)]], [Reach(x, y), [Reach(x, v_12), Reach(v_14, y), Reach(v_12, v_16), Reach(v_12, y)]], [Reach(x, y), [Reach(x, v_20), Reach(v_20, y)]]]\n" ] } ], "source": [ "target = expr('Reach(x, y)')\n", "examples_pos = [{x: A, y: B},\n", " {x: A, y: C},\n", " {x: A, y: D},\n", " {x: A, y: E},\n", " {x: A, y: F},\n", " {x: A, y: G},\n", " {x: A, y: I},\n", " {x: B, y: C},\n", " {x: D, y: C},\n", " {x: D, y: E},\n", " {x: D, y: F},\n", " {x: D, y: G},\n", " {x: D, y: I},\n", " {x: E, y: F},\n", " {x: E, y: G},\n", " {x: E, y: I},\n", " {x: G, y: I},\n", " {x: H, y: G},\n", " {x: H, y: I}]\n", "nodes = {A, B, C, D, E, F, G, H, I}\n", "examples_neg = [example for example in [{x: a, y: b} for a in nodes for b in nodes]\n", " if example not in examples_pos]\n", "clauses = small_network.foil([examples_pos, examples_neg], target)\n", "\n", "print(clauses)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The algorithm produced something close to the recursive rule: \n", " $$ Reach(x,y) \\Leftrightarrow [Conn(x,y)] \\: \\lor \\: [\\exists \\: z \\: \\: Reach(x,z) \\, \\land \\, Reach(z,y)]$$\n", " \n", "This happened because the size of the example is small. " ] } ], "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.5" }, "pycharm": { "stem_cell": { "cell_type": "raw", "source": [], "metadata": { "collapsed": false } } } }, "nbformat": 4, "nbformat_minor": 2 }