{
"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",
"\n",
"from notebook import pseudocode, psource"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## CONTENTS\n",
"\n",
"* Overview\n",
"* Current-Best Learning"
]
},
{
"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 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": {
"collapsed": true
},
"source": [
"## CURRENT-BEST LEARNING\n",
"\n",
"### Overview\n",
"\n",
"In **Current-Best Learning**, we start with a hypothesis and we refine it as we iterate through the examples. For each example, there are three possible outcomes: the example is consistent with the hypothesis, the example is a **false positive** (real value is false but got predicted as true) and the example is a **false negative** (real value is true but got predicted as false). Depending on the outcome we refine the hypothesis accordingly:\n",
"\n",
"* Consistent: We do not change the hypothesis and move on to the next example.\n",
"\n",
"* False Positive: We **specialize** the hypothesis, which means we add a conjunction.\n",
"\n",
"* False Negative: We **generalize** the hypothesis, either by removing a conjunction or a disjunction, or by adding a disjunction.\n",
"\n",
"When specializing or generalizing, we should make sure to not create inconsistencies with previous examples. To avoid that caveat, backtracking is needed. Thankfully, there is not just one specialization or generalization, so we have a lot to choose from. We will go through all the specializations/generalizations and we will refine our hypothesis as the first specialization/generalization consistent with all the examples seen up to that point."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Pseudocode"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"### AIMA3e\n",
"__function__ Current-Best-Learning(_examples_, _h_) __returns__ a hypothesis or fail \n",
" __if__ _examples_ is empty __then__ \n",
" __return__ _h_ \n",
" _e_ ← First(_examples_) \n",
" __if__ _e_ is consistent with _h_ __then__ \n",
" __return__ Current-Best-Learning(Rest(_examples_), _h_) \n",
" __else if__ _e_ is a false positive for _h_ __then__ \n",
" __for each__ _h'_ __in__ specializations of _h_ consistent with _examples_ seen so far __do__ \n",
" _h''_ ← Current-Best-Learning(Rest(_examples_), _h'_) \n",
" __if__ _h''_ ≠ _fail_ __then return__ _h''_ \n",
" __else if__ _e_ is a false negative for _h_ __then__ \n",
" __for each__ _h'_ __in__ generalizations of _h_ consistent with _examples_ seen so far __do__ \n",
" _h''_ ← Current-Best-Learning(Rest(_examples_), _h'_) \n",
" __if__ _h''_ ≠ _fail_ __then return__ _h''_ \n",
" __return__ _fail_ \n",
"\n",
"---\n",
"__Figure ??__ The current-best-hypothesis learning algorithm. It searches for a consistent hypothesis that fits all the examples and backtracks when no consistent specialization/generalization can be found. To start the algorithm, any hypothesis can be passed in; it will be specialized or generalized as needed."
],
"text/plain": [
"def current_best_learning(examples, h, examples_so_far=None):\n",
" """ [Figure 19.2]\n",
" The hypothesis is a list of dictionaries, with each dictionary representing\n",
" a disjunction."""\n",
" if not examples:\n",
" return h\n",
"\n",
" examples_so_far = examples_so_far or []\n",
" e = examples[0]\n",
" if is_consistent(e, h):\n",
" return current_best_learning(examples[1:], h, examples_so_far + [e])\n",
" elif false_positive(e, h):\n",
" for h2 in specializations(examples_so_far + [e], h):\n",
" h3 = current_best_learning(examples[1:], h2, examples_so_far + [e])\n",
" if h3 != 'FAIL':\n",
" return h3\n",
" elif false_negative(e, h):\n",
" for h2 in generalizations(examples_so_far + [e], h):\n",
" h3 = current_best_learning(examples[1:], h2, examples_so_far + [e])\n",
" if h3 != 'FAIL':\n",
" return h3\n",
"\n",
" return 'FAIL'\n",
"\n",
"\n",
"def specializations(examples_so_far, h):\n",
" """Specialize the hypothesis by adding AND operations to the disjunctions"""\n",
" hypotheses = []\n",
"\n",
" for i, disj in enumerate(h):\n",
" for e in examples_so_far:\n",
" for k, v in e.items():\n",
" if k in disj or k == 'GOAL':\n",
" continue\n",
"\n",
" h2 = h[i].copy()\n",
" h2[k] = '!' + v\n",
" h3 = h.copy()\n",
" h3[i] = h2\n",
" if check_all_consistency(examples_so_far, h3):\n",
" hypotheses.append(h3)\n",
"\n",
" shuffle(hypotheses)\n",
" return hypotheses\n",
"\n",
"\n",
"def generalizations(examples_so_far, h):\n",
" """Generalize the hypothesis. First delete operations\n",
" (including disjunctions) from the hypothesis. Then, add OR operations."""\n",
" hypotheses = []\n",
"\n",
" # Delete disjunctions\n",
" disj_powerset = powerset(range(len(h)))\n",
" for disjs in disj_powerset:\n",
" h2 = h.copy()\n",
" for d in reversed(list(disjs)):\n",
" del h2[d]\n",
"\n",
" if check_all_consistency(examples_so_far, h2):\n",
" hypotheses += h2\n",
"\n",
" # Delete AND operations in disjunctions\n",
" for i, disj in enumerate(h):\n",
" a_powerset = powerset(disj.keys())\n",
" for attrs in a_powerset:\n",
" h2 = h[i].copy()\n",
" for a in attrs:\n",
" del h2[a]\n",
"\n",
" if check_all_consistency(examples_so_far, [h2]):\n",
" h3 = h.copy()\n",
" h3[i] = h2.copy()\n",
" hypotheses += h3\n",
"\n",
" # Add OR operations\n",
" if hypotheses == [] or hypotheses == [{}]:\n",
" hypotheses = add_or(examples_so_far, h)\n",
" else:\n",
" hypotheses.extend(add_or(examples_so_far, h))\n",
"\n",
" shuffle(hypotheses)\n",
" return hypotheses\n",
"