KNOWLEDGE

The knowledge module covers Chapter 19: Knowledge in Learning from Stuart Russel's and Peter Norvig's book Artificial Intelligence: A Modern Approach.

Execute the cell below to get started.


In [1]:
from knowledge import *
from notebook import psource

CONTENTS

  • Overview
  • Inductive Logic Programming (FOIL)

OVERVIEW

Like the learning module, 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.

First-Order Logic

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.

Representation

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.

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:

{'Species': 'Cat', 'Coat': 'Yes', 'Rain': 'Yes', 'GOAL': True}

A hypothesis can be the following:

[{'Species': 'Cat'}]

which means an animal will take an umbrella if and only if it is a cat.

Consistency

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.

Inductive Logic Programming (FOIL)

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:

$ Background ∧ Hypothesis ∧ Descriptions \vDash Classifications $

for the unknown $Hypothesis$, given the $Background$ knowledge described by $Descriptions$ and $Classifications$.

The first approach to ILP works by starting with a very general rule and gradually specializing it so that it fits the data.
This is essentially what happens in decision-tree learning, where a decision tree is gradually grown until it is consistent with the observations.
To do ILP we 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.

The FOIL algorithm learns new rules, one at a time, in order to cover all given positive and negative examples.
More precicely, FOIL contains an inner and an outer while loop.

  • outer loop: (function __foil()__) add rules until all positive examples are covered.
    (each rule is a conjuction of literals, which are chosen inside the inner loop)
  • inner loop: (function __new_clause()__) add new literals until all negative examples are covered, and some positive examples are covered.

    • In each iteration, we select/add the most promising literal, according to an estimate of its utility. (function __new_literal()__)

    • The evaluation function to estimate utility of adding literal $L$ to a set of rules $R$ is (function __gain()__) :

    $$ FoilGain(L,R) = t \big( \log_2{\frac{p_1}{p_1+n_1}} - \log_2{\frac{p_0}{p_0+n_0}} \big) $$ where:

    $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}$

    • Calculate the extended examples for the chosen literal (function __extend_example()__)
      (the set of examples created by extending example with each possible constant value for each new variable in literal)
  • Finally, the algorithm returns a disjunction of first order rules (= conjuction of literals)


In [2]:
psource(FOIL_container)


class FOIL_container(FolKB):
    """Hold the kb and other necessary elements required by FOIL."""

    def __init__(self, clauses=None):
        self.const_syms = set()
        self.pred_syms = set()
        FolKB.__init__(self, clauses)

    def tell(self, sentence):
        if is_definite_clause(sentence):
            self.clauses.append(sentence)
            self.const_syms.update(constant_symbols(sentence))
            self.pred_syms.update(predicate_symbols(sentence))
        else:
            raise Exception("Not a definite clause: {}".format(sentence))

    def foil(self, examples, target):
        """Learn a list of first-order horn clauses
        'examples' is a tuple: (positive_examples, negative_examples).
        positive_examples and negative_examples are both lists which contain substitutions."""
        clauses = []

        pos_examples = examples[0]
        neg_examples = examples[1]

        while pos_examples:
            clause, extended_pos_examples = self.new_clause((pos_examples, neg_examples), target)
            # remove positive examples covered by clause
            pos_examples = self.update_examples(target, pos_examples, extended_pos_examples)
            clauses.append(clause)

        return clauses

    def new_clause(self, examples, target):
        """Find a horn clause which satisfies part of the positive
        examples but none of the negative examples.
        The horn clause is specified as [consequent, list of antecedents]
        Return value is the tuple (horn_clause, extended_positive_examples)."""
        clause = [target, []]
        # [positive_examples, negative_examples]
        extended_examples = examples
        while extended_examples[1]:
            l = self.choose_literal(self.new_literals(clause), extended_examples)
            clause[1].append(l)
            extended_examples = [sum([list(self.extend_example(example, l)) for example in
                                      extended_examples[i]], []) for i in range(2)]

        return (clause, extended_examples[0])

    def extend_example(self, example, literal):
        """Generate extended examples which satisfy the literal."""
        # find all substitutions that satisfy literal
        for s in self.ask_generator(subst(example, literal)):
            s.update(example)
            yield s

    def new_literals(self, clause):
        """Generate new literals based on known predicate symbols.
        Generated literal must share atleast one variable with clause"""
        share_vars = variables(clause[0])
        for l in clause[1]:
            share_vars.update(variables(l))
        for pred, arity in self.pred_syms:
            new_vars = {standardize_variables(expr('x')) for _ in range(arity - 1)}
            for args in product(share_vars.union(new_vars), repeat=arity):
                if any(var in share_vars for var in args):
                    # make sure we don't return an existing rule
                    if not Expr(pred, args) in clause[1]:
                        yield Expr(pred, *[var for var in args])


    def choose_literal(self, literals, examples): 
        """Choose the best literal based on the information gain."""

        return max(literals, key = partial(self.gain , examples = examples))


    def gain(self, l ,examples):
        """
        Find the utility of each literal when added to the body of the clause. 
        Utility function is: 
            gain(R, l) = T * (log_2 (post_pos / (post_pos + post_neg)) - log_2 (pre_pos / (pre_pos + pre_neg)))

        where: 
        
            pre_pos = number of possitive bindings of rule R (=current set of rules)
            pre_neg = number of negative bindings of rule R 
            post_pos = number of possitive bindings of rule R' (= R U {l} )
            post_neg = number of negative bindings of rule R' 
            T = number of possitive bindings of rule R that are still covered 
                after adding literal l 

        """
        pre_pos = len(examples[0])
        pre_neg = len(examples[1])
        post_pos = sum([list(self.extend_example(example, l)) for example in examples[0]], [])           
        post_neg = sum([list(self.extend_example(example, l)) for example in examples[1]], []) 
        if pre_pos + pre_neg ==0 or len(post_pos) + len(post_neg)==0:
            return -1
        # number of positive example that are represented in extended_examples
        T = 0
        for example in examples[0]:
            represents = lambda d: all(d[x] == example[x] for x in example)
            if any(represents(l_) for l_ in post_pos):
                T += 1
        value = T * (log(len(post_pos) / (len(post_pos) + len(post_neg)) + 1e-12,2) - log(pre_pos / (pre_pos + pre_neg),2))
        return value


    def update_examples(self, target, examples, extended_examples):
        """Add to the kb those examples what are represented in extended_examples
        List of omitted examples is returned."""
        uncovered = []
        for example in examples:
            represents = lambda d: all(d[x] == example[x] for x in example)
            if any(represents(l) for l in extended_examples):
                self.tell(subst(example, target))
            else:
                uncovered.append(example)

        return uncovered

Example Family

Suppose we have the following family relations:

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.

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.


In [3]:
A, B, C, D, E, F, G, H, I, x, y, z = map(expr, 'ABCDEFGHIxyz')

In [4]:
small_family = FOIL_container([expr("Mother(Anne, Peter)"),
                               expr("Mother(Anne, Zara)"),
                               expr("Mother(Sarah, Beatrice)"),
                               expr("Mother(Sarah, Eugenie)"),
                               expr("Father(Mark, Peter)"),
                               expr("Father(Mark, Zara)"),
                               expr("Father(Andrew, Beatrice)"),
                               expr("Father(Andrew, Eugenie)"),
                               expr("Father(Philip, Anne)"),
                               expr("Father(Philip, Andrew)"),
                               expr("Mother(Elizabeth, Anne)"),
                               expr("Mother(Elizabeth, Andrew)"),
                               expr("Male(Philip)"),
                               expr("Male(Mark)"),
                               expr("Male(Andrew)"),
                               expr("Male(Peter)"),
                               expr("Female(Elizabeth)"),
                               expr("Female(Anne)"),
                               expr("Female(Sarah)"),
                               expr("Female(Zara)"),
                               expr("Female(Beatrice)"),
                               expr("Female(Eugenie)"),
])

target = expr('Parent(x, y)')

examples_pos = [{x: expr('Elizabeth'), y: expr('Anne')},
                {x: expr('Elizabeth'), y: expr('Andrew')},
                {x: expr('Philip'), y: expr('Anne')},
                {x: expr('Philip'), y: expr('Andrew')},
                {x: expr('Anne'), y: expr('Peter')},
                {x: expr('Anne'), y: expr('Zara')},
                {x: expr('Mark'), y: expr('Peter')},
                {x: expr('Mark'), y: expr('Zara')},
                {x: expr('Andrew'), y: expr('Beatrice')},
                {x: expr('Andrew'), y: expr('Eugenie')},
                {x: expr('Sarah'), y: expr('Beatrice')},
                {x: expr('Sarah'), y: expr('Eugenie')}]
examples_neg = [{x: expr('Anne'), y: expr('Eugenie')},
                {x: expr('Beatrice'), y: expr('Eugenie')},
                {x: expr('Mark'), y: expr('Elizabeth')},
                {x: expr('Beatrice'), y: expr('Philip')}]

In [5]:
# run the FOIL algorithm 
clauses = small_family.foil([examples_pos, examples_neg], target)
print (clauses)


[[Parent(x, y), [Father(x, y)]], [Parent(x, y), [Mother(x, y)]]]

Indeed the algorithm returned the rule:
$Parent(x,y) \Leftrightarrow Mother(x,y) \lor Father(x,y)$

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.
One possible set of rules for the relation $Grandparent(x,y)$ could be:

Or, if $Background$ included the sentence $Parent(x,y) \Leftrightarrow [Mother(x,y) \lor Father(x,y)]$ then:

$$Grandparent(x,y) \Leftrightarrow \exists \: z \quad Parent(x,z) \land Parent(z,y)$$

In [6]:
target = expr('Grandparent(x, y)')

examples_pos = [{x: expr('Elizabeth'), y: expr('Peter')},
                {x: expr('Elizabeth'), y: expr('Zara')},
                {x: expr('Elizabeth'), y: expr('Beatrice')},
                {x: expr('Elizabeth'), y: expr('Eugenie')},
                {x: expr('Philip'), y: expr('Peter')},
                {x: expr('Philip'), y: expr('Zara')},
                {x: expr('Philip'), y: expr('Beatrice')},
                {x: expr('Philip'), y: expr('Eugenie')}]
examples_neg = [{x: expr('Anne'), y: expr('Eugenie')},
                {x: expr('Beatrice'), y: expr('Eugenie')},
                {x: expr('Elizabeth'), y: expr('Andrew')},
                {x: expr('Elizabeth'), y: expr('Anne')},
                {x: expr('Elizabeth'), y: expr('Mark')},
                {x: expr('Elizabeth'), y: expr('Sarah')},
                {x: expr('Philip'), y: expr('Anne')},
                {x: expr('Philip'), y: expr('Andrew')},
                {x: expr('Anne'), y: expr('Peter')},
                {x: expr('Anne'), y: expr('Zara')},
                {x: expr('Mark'), y: expr('Peter')},
                {x: expr('Mark'), y: expr('Zara')},
                {x: expr('Andrew'), y: expr('Beatrice')},
                {x: expr('Andrew'), y: expr('Eugenie')},
                {x: expr('Sarah'), y: expr('Beatrice')},
                {x: expr('Mark'), y: expr('Elizabeth')},
                {x: expr('Beatrice'), y: expr('Philip')}, 
                {x: expr('Peter'), y: expr('Andrew')}, 
                {x: expr('Zara'), y: expr('Mark')},
                {x: expr('Peter'), y: expr('Anne')},
                {x: expr('Zara'), y: expr('Eugenie')},     ]

clauses = small_family.foil([examples_pos, examples_neg], target)

print(clauses)


[[Grandparent(x, y), [Parent(x, v_6), Parent(v_6, y)]]]

Indeed the algorithm returned the rule:
$Grandparent(x,y) \Leftrightarrow \exists \: v \: \: Parent(x,v) \land Parent(v,y)$

Example Network

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)).
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:

$$ Reach(x,y) \Leftrightarrow \begin{cases} Conn(x,y), \: \text{(if there is a directed edge from x to y)} \\ \lor \quad \exists \: z \quad Reach(x,z) \land Reach(z,y) \end{cases}$$

In [7]:
"""
A              H
|\            /|
| \          / |
v  v        v  v
B  D-->E-->G-->I
|  /   |
| /    |
vv     v
C      F
"""
small_network = FOIL_container([expr("Conn(A, B)"),
                               expr("Conn(A ,D)"),
                               expr("Conn(B, C)"),
                               expr("Conn(D, C)"),
                               expr("Conn(D, E)"),
                               expr("Conn(E ,F)"),
                               expr("Conn(E, G)"),
                               expr("Conn(G, I)"),
                               expr("Conn(H, G)"),
                               expr("Conn(H, I)")])

In [8]:
target = expr('Reach(x, y)')
examples_pos = [{x: A, y: B},
                {x: A, y: C},
                {x: A, y: D},
                {x: A, y: E},
                {x: A, y: F},
                {x: A, y: G},
                {x: A, y: I},
                {x: B, y: C},
                {x: D, y: C},
                {x: D, y: E},
                {x: D, y: F},
                {x: D, y: G},
                {x: D, y: I},
                {x: E, y: F},
                {x: E, y: G},
                {x: E, y: I},
                {x: G, y: I},
                {x: H, y: G},
                {x: H, y: I}]
nodes = {A, B, C, D, E, F, G, H, I}
examples_neg = [example for example in [{x: a, y: b} for a in nodes for b in nodes]
                    if example not in examples_pos]
clauses = small_network.foil([examples_pos, examples_neg], target)

print(clauses)


[[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)]]]

The algorithm produced something close to the recursive rule: $$ Reach(x,y) \Leftrightarrow [Conn(x,y)] \: \lor \: [\exists \: z \: \: Reach(x,z) \, \land \, Reach(z,y)]$$

This happened because the size of the example is small.