learning.ipynb 377 ko
Newer Older
   },
   "outputs": [],
   "source": [
    "pseudocode(\"Decision Tree Learning\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
C.G.Vedant's avatar
C.G.Vedant a validé
    "### Implementation\n",
    "The nodes of the tree constructed by our learning algorithm are stored using either `DecisionFork` or `DecisionLeaf` based on whether they are a parent node or a leaf node respectively."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
C.G.Vedant's avatar
C.G.Vedant a validé
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "psource(DecisionFork)"
C.G.Vedant's avatar
C.G.Vedant a validé
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`DecisionFork` holds the attribute, which is tested at that node, and a dict of branches. The branches store the child nodes, one for each of the attribute's values. Calling an object of this class as a function with input tuple as an argument returns the next node in the classification path based on the result of the attribute test."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
C.G.Vedant's avatar
C.G.Vedant a validé
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "psource(DecisionLeaf)"
C.G.Vedant's avatar
C.G.Vedant a validé
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The leaf node stores the class label in `result`. All input tuples' classification paths end on a `DecisionLeaf` whose `result` attribute decide their class."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
C.G.Vedant's avatar
C.G.Vedant a validé
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "psource(DecisionTreeLearner)"
C.G.Vedant's avatar
C.G.Vedant a validé
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The implementation of `DecisionTreeLearner` provided in [learning.py](https://github.com/aimacode/aima-python/blob/master/learning.py) uses information gain as the metric for selecting which attribute to test for splitting. The function builds the tree top-down in a recursive manner. Based on the input it makes one of the four choices:\n",
    "<ol>\n",
    "<li>If the input at the current step has no training data we return the mode of classes of input data recieved in the parent step (previous level of recursion).</li>\n",
    "<li>If all values in training data belong to the same class it returns a `DecisionLeaf` whose class label is the class which all the data belongs to.</li>\n",
    "<li>If the data has no attributes that can be tested we return the class with highest plurality value in the training data.</li>\n",
    "<li>We choose the attribute which gives the highest amount of entropy gain and return a `DecisionFork` which splits based on this attribute. Each branch recursively calls `decision_tree_learning` to construct the sub-tree.</li>\n",
C.G.Vedant's avatar
C.G.Vedant a validé
    "</ol>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
    "## NAIVE BAYES LEARNER\n",
    "\n",
    "### Overview\n",
    "\n",
    "#### Theory of Probabilities\n",
    "The Naive Bayes algorithm is a probabilistic classifier, making use of [Bayes' Theorem](https://en.wikipedia.org/wiki/Bayes%27_theorem). The theorem states that the conditional probability of **A** given **B** equals the conditional probability of **B** given **A** multiplied by the probability of **A**, divided by the probability of **B**.\n",
    "$$P(A|B) = \\dfrac{P(B|A)*P(A)}{P(B)}$$\n",
    "From the theory of Probabilities we have the Multiplication Rule, if the events *X* are independent the following is true:\n",
    "\n",
    "$$P(X_{1} \\cap X_{2} \\cap ... \\cap X_{n}) = P(X_{1})*P(X_{2})*...*P(X_{n})$$\n",
    "\n",
    "For conditional probabilities this becomes:\n",
    "\n",
    "$$P(X_{1}, X_{2}, ..., X_{n}|Y) = P(X_{1}|Y)*P(X_{2}|Y)*...*P(X_{n}|Y)$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Classifying an Item\n",
    "\n",
    "How can we use the above to classify an item though?\n",
    "\n",
    "We have a dataset with a set of classes (**C**) and we want to classify an item with a set of features (**F**). Essentially what we want to do is predict the class of an item given the features.\n",
    "\n",
    "For a specific class, **Class**, we will find the conditional probability given the item features:\n",
    "\n",
    "$$P(Class|F) = \\dfrac{P(F|Class)*P(Class)}{P(F)}$$\n",
    "\n",
    "We will do this for every class and we will pick the maximum. This will be the class the item is classified in.\n",
    "\n",
    "The features though are a vector with many elements. We need to break the probabilities up using the multiplication rule. Thus the above equation becomes:\n",
    "\n",
    "$$P(Class|F) = \\dfrac{P(Class)*P(F_{1}|Class)*P(F_{2}|Class)*...*P(F_{n}|Class)}{P(F_{1})*P(F_{2})*...*P(F_{n})}$$\n",
    "\n",
    "The calculation of the conditional probability then depends on the calculation of the following:\n",
    "\n",
    "*a)* The probability of **Class** in the dataset.\n",
    "\n",
    "*b)* The conditional probability of each feature occuring in an item classified in **Class**.\n",
    "\n",
    "*c)* The probabilities of each individual feature.\n",
    "\n",
    "For *a)*, we will count how many times **Class** occurs in the dataset (aka how many items are classified in a particular class).\n",
    "\n",
    "For *b)*, if the feature values are discrete ('Blue', '3', 'Tall', etc.), we will count how many times a feature value occurs in items of each class. If the feature values are not discrete, we will go a different route. We will use a distribution function to calculate the probability of values for a given class and feature. If we know the distribution function of the dataset, then great, we will use it to compute the probabilities. If we don't know the function, we can assume the dataset follows the normal (Gaussian) distribution without much loss of accuracy. In fact, it can be proven that any distribution tends to the Gaussian the larger the population gets (see [Central Limit Theorem](https://en.wikipedia.org/wiki/Central_limit_theorem)).\n",
    "\n",
    "*NOTE:* If the values are continuous but use the discrete approach, there might be issues if we are not lucky. For one, if we have two values, '5.0 and 5.1', with the discrete approach they will be two completely different values, despite being so close. Second, if we are trying to classify an item with a feature value of '5.15', if the value does not appear for the feature, its probability will be 0. This might lead to misclassification. Generally, the continuous approach is more accurate and more useful, despite the overhead of calculating the distribution function.\n",
    "\n",
    "The last one, *c)*, is tricky. If feature values are discrete, we can count how many times they occur in the dataset. But what if the feature values are continuous? Imagine a dataset with a height feature. Is it worth it to count how many times each value occurs? Most of the time it is not, since there can be miscellaneous differences in the values (for example, 1.7 meters and 1.700001 meters are practically equal, but they count as different values).\n",
    "\n",
    "So as we cannot calculate the feature value probabilities, what are we going to do?\n",
    "\n",
    "Let's take a step back and rethink exactly what we are doing. We are essentially comparing conditional probabilities of all the classes. For two classes, **A** and **B**, we want to know which one is greater:\n",
    "\n",
    "$$\\dfrac{P(F|A)*P(A)}{P(F)} vs. \\dfrac{P(F|B)*P(B)}{P(F)}$$\n",
    "\n",
    "Wait, **P(F)** is the same for both the classes! In fact, it is the same for every combination of classes. That is because **P(F)** does not depend on a class, thus being independent of the classes.\n",
    "\n",
    "So, for *c)*, we actually don't need to calculate it at all."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Wrapping It Up\n",
    "\n",
    "Classifying an item to a class then becomes a matter of calculating the conditional probabilities of feature values and the probabilities of classes. This is something very desirable and computationally delicious.\n",
    "\n",
    "Remember though that all the above are true because we made the assumption that the features are independent. In most real-world cases that is not true though. Is that an issue here? Fret not, for the the algorithm is very efficient even with that assumption. That is why the algorithm is called **Naive** Bayes Classifier. We (naively) assume that the features are independent to make computations easier."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Implementation\n",
    "\n",
    "The implementation of the Naive Bayes Classifier is split in two; *Learning* and *Simple*. The *learning* classifier takes as input a dataset and learns the needed distributions from that. It is itself split into two, for discrete and continuous features. The *simple* classifier takes as input not a dataset, but already calculated distributions (a dictionary of `CountingProbDist` objects)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Discrete\n",
    "\n",
    "The implementation for discrete values counts how many times each feature value occurs for each class, and how many times each class occurs. The results are stored in a `CountinProbDist` object."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With the below code you can see the probabilities of the class \"Setosa\" appearing in the dataset and the probability of the first feature (at index 0) of the same class having a value of 5. Notice that the second probability is relatively small, even though if we observe the dataset we will find that a lot of values are around 5. The issue arises because the features in the Iris dataset are continuous, and we are assuming they are discrete. If the features were discrete (for example, \"Tall\", \"3\", etc.) this probably wouldn't have been the case and we would see a much nicer probability distribution."
   ]
  },
  {
   "cell_type": "code",
C.G.Vedant's avatar
C.G.Vedant a validé
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.3333333333333333\n",
      "0.10588235294117647\n"
     ]
    }
   ],
   "source": [
    "dataset = iris\n",
    "\n",
    "target_vals = dataset.values[dataset.target]\n",
    "target_dist = CountingProbDist(target_vals)\n",
    "attr_dists = {(gv, attr): CountingProbDist(dataset.values[attr])\n",
    "              for gv in target_vals\n",
    "              for attr in dataset.inputs}\n",
    "for example in dataset.examples:\n",
    "        targetval = example[dataset.target]\n",
    "        target_dist.add(targetval)\n",
    "        for attr in dataset.inputs:\n",
    "            attr_dists[targetval, attr].add(example[attr])\n",
    "\n",
    "\n",
    "print(target_dist['setosa'])\n",
    "print(attr_dists['setosa', 0][5.0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First we found the different values for the classes (called targets here) and calculated their distribution. Next we initialized a dictionary of `CountingProbDist` objects, one for each class and feature. Finally, we iterated through the examples in the dataset and calculated the needed probabilites.\n",
    "\n",
    "Having calculated the different probabilities, we will move on to the predicting function. It will receive as input an item and output the most likely class. Using the above formula, it will multiply the probability of the class appearing, with the probability of each feature value appearing in the class. It will return the max result."
   ]
  },
  {
   "cell_type": "code",
C.G.Vedant's avatar
C.G.Vedant a validé
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "setosa\n"
     ]
    }
   ],
   "source": [
    "def predict(example):\n",
    "    def class_probability(targetval):\n",
    "        return (target_dist[targetval] *\n",
    "                product(attr_dists[targetval, attr][example[attr]]\n",
    "                        for attr in dataset.inputs))\n",
    "    return argmax(target_vals, key=class_probability)\n",
    "\n",
    "\n",
    "print(predict([5, 3, 1, 0.1]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can view the complete code by executing the next line:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "psource(NaiveBayesDiscrete)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Continuous\n",
    "\n",
    "In the implementation we use the Gaussian/Normal distribution function. To make it work, we need to find the means and standard deviations of features for each class. We make use of the `find_means_and_deviations` Dataset function. On top of that, we will also calculate the class probabilities as we did with the Discrete approach."
   ]
  },
  {
   "cell_type": "code",
C.G.Vedant's avatar
C.G.Vedant a validé
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[5.006, 3.418, 1.464, 0.244]\n",
      "[0.5161711470638634, 0.3137983233784114, 0.46991097723995795, 0.19775268000454405]\n"
     ]
    }
   ],
   "source": [
    "means, deviations = dataset.find_means_and_deviations()\n",
    "\n",
    "target_vals = dataset.values[dataset.target]\n",
    "target_dist = CountingProbDist(target_vals)\n",
    "\n",
    "\n",
    "print(means[\"setosa\"])\n",
    "print(deviations[\"versicolor\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can see the means of the features for the \"Setosa\" class and the deviations for \"Versicolor\".\n",
    "\n",
    "The prediction function will work similarly to the Discrete algorithm. It will multiply the probability of the class occuring with the conditional probabilities of the feature values for the class.\n",
    "\n",
    "Since we are using the Gaussian distribution, we will input the value for each feature into the Gaussian function, together with the mean and deviation of the feature. This will return the probability of the particular feature value for the given class. We will repeat for each class and pick the max value."
   ]
  },
  {
   "cell_type": "code",
C.G.Vedant's avatar
C.G.Vedant a validé
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "setosa\n"
     ]
    }
   ],
   "source": [
    "def predict(example):\n",
    "    def class_probability(targetval):\n",
    "        prob = target_dist[targetval]\n",
    "        for attr in dataset.inputs:\n",
    "            prob *= gaussian(means[targetval][attr], deviations[targetval][attr], example[attr])\n",
    "        return prob\n",
    "\n",
    "    return argmax(target_vals, key=class_probability)\n",
    "\n",
    "\n",
    "print(predict([5, 3, 1, 0.1]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The complete code of the continuous algorithm:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
    "collapsed": true
   "outputs": [],
   "source": [
    "psource(NaiveBayesContinuous)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Simple\n",
    "\n",
    "The simple classifier (chosen with the argument `simple`) does not learn from a dataset, instead it takes as input a dictionary of already calculated `CountingProbDist` objects and returns a predictor function. The dictionary is in the following form: `(Class Name, Class Probability): CountingProbDist Object`.\n",
    "\n",
    "Each class has its own probability distribution. The classifier given a list of features calculates the probability of the input for each class and returns the max. The only pre-processing work is to create dictionaries for the distribution of classes (named `targets`) and attributes/features.\n",
    "\n",
    "The complete code for the simple classifier:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "psource(NaiveBayesSimple)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This classifier is useful when you already have calculated the distributions and you need to predict future items."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Examples\n",
    "\n",
    "We will now use the Naive Bayes Classifier (Discrete and Continuous) to classify items:"
   ]
  },
  {
C.G.Vedant's avatar
C.G.Vedant a validé
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
C.G.Vedant's avatar
C.G.Vedant a validé
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Discrete Classifier\n",
      "setosa\n",
      "setosa\n",
      "setosa\n",
      "\n",
      "Continuous Classifier\n",
      "setosa\n",
      "versicolor\n",
      "virginica\n"
     ]
    }
   ],
   "source": [
C.G.Vedant's avatar
C.G.Vedant a validé
    "nBD = NaiveBayesLearner(iris, continuous=False)\n",
    "print(\"Discrete Classifier\")\n",
    "print(nBD([5, 3, 1, 0.1]))\n",
    "print(nBD([6, 5, 3, 1.5]))\n",
    "print(nBD([7, 3, 6.5, 2]))\n",
    "\n",
    "\n",
    "nBC = NaiveBayesLearner(iris, continuous=True)\n",
    "print(\"\\nContinuous Classifier\")\n",
    "print(nBC([5, 3, 1, 0.1]))\n",
    "print(nBC([6, 5, 3, 1.5]))\n",
    "print(nBC([7, 3, 6.5, 2]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice how the Discrete Classifier misclassified the second item, while the Continuous one had no problem.\n",
    "\n",
    "Let's now take a look at the simple classifier. First we will come up with a sample problem to solve. Say we are given three bags. Each bag contains three letters ('a', 'b' and 'c') of different quantities. We are given a string of letters and we are tasked with finding from which bag the string of letters came.\n",
    "\n",
    "Since we know the probability distribution of the letters for each bag, we can use the naive bayes classifier to make our prediction."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "bag1 = 'a'*50 + 'b'*30 + 'c'*15\n",
    "dist1 = CountingProbDist(bag1)\n",
    "bag2 = 'a'*30 + 'b'*45 + 'c'*20\n",
    "dist2 = CountingProbDist(bag2)\n",
    "bag3 = 'a'*20 + 'b'*20 + 'c'*35\n",
    "dist3 = CountingProbDist(bag3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that we have the `CountingProbDist` objects for each bag/class, we will create the dictionary. We assume that it is equally probable that we will pick from any bag."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "dist = {('First', 0.5): dist1, ('Second', 0.3): dist2, ('Third', 0.2): dist3}\n",
    "nBS = NaiveBayesLearner(dist, simple=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can start making predictions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First\n",
      "Second\n",
      "Third\n"
     ]
    }
   ],
   "source": [
    "print(nBS('aab'))        # We can handle strings\n",
    "print(nBS(['b', 'b']))   # And lists!\n",
    "print(nBS('ccbcc'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The results make intuitive sence. The first bag has a high amount of 'a's, the second has a high amount of 'b's and the third has a high amount of 'c's. The classifier seems to confirm this intuition.\n",
    "\n",
    "Note that the simple classifier doesn't distinguish between discrete and continuous values. It just takes whatever it is given. Also, the `simple` option on the `NaiveBayesLearner` overrides the `continuous` argument. `NaiveBayesLearner(d, simple=True, continuous=False)` just creates a simple classifier."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## PERCEPTRON CLASSIFIER\n",
    "\n",
    "### Overview\n",
    "\n",
    "The Perceptron is a linear classifier. It works the same way as a neural network with no hidden layers (just input and output). First it trains its weights given a dataset and then it can classify a new item by running it through the network.\n",
    "\n",
    "Its input layer consists of the the item features, while the output layer consists of nodes (also called neurons). Each node in the output layer has *n* synapses (for every item feature), each with its own weight. Then, the nodes find the dot product of the item features and the synapse weights. These values then pass through an activation function (usually a sigmoid). Finally, we pick the largest of the values and we return its index.\n",
    "\n",
    "Note that in classification problems each node represents a class. The final classification is the class/node with the max output value.\n",
    "\n",
    "Below you can see a single node/neuron in the outer layer. With *f* we denote the item features, with *w* the synapse weights, then inside the node we have the dot product and the activation function, *g*."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![perceptron](images/perceptron.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Implementation\n",
    "\n",
    "First, we train (calculate) the weights given a dataset, using the `BackPropagationLearner` function of `learning.py`. We then return a function, `predict`, which we will use in the future to classify a new item. The function computes the (algebraic) dot product of the item with the calculated weights for each node in the outer layer. Then it picks the greatest value and classifies the item in the corresponding class."
   "execution_count": null,
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "psource(PerceptronLearner)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
    "Note that the Perceptron is a one-layer neural network, without any hidden layers. So, in `BackPropagationLearner`, we will pass no hidden layers. From that function we get our network, which is just one layer, with the weights calculated.\n",
    "That function `predict` passes the input/example through the network, calculating the dot product of the input and the weights for each node and returns the class with the max dot product."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example\n",
    "\n",
    "We will train the Perceptron on the iris dataset. Because though the `BackPropagationLearner` works with integer indexes and not strings, we need to convert class names to integers. Then, we will try and classify the item/flower with measurements of 5, 3, 1, 0.1."
C.G.Vedant's avatar
C.G.Vedant a validé
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n"
     ]
    }
   ],
   "source": [
    "iris = DataSet(name=\"iris\")\n",
    "iris.classes_to_numbers()\n",
    "\n",
    "perceptron = PerceptronLearner(iris)\n",
    "print(perceptron([5, 3, 1, 0.1]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
    "The correct output is 0, which means the item belongs in the first class, \"setosa\". Note that the Perceptron algorithm is not perfect and may produce false classifications."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
    "## LEARNER EVALUATION\n",
    "In this section we will evaluate and compare algorithm performance. The dataset we will use will again be the iris one."
   ]
  },
  {
   "cell_type": "code",
C.G.Vedant's avatar
C.G.Vedant a validé
   "execution_count": 42,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "iris = DataSet(name=\"iris\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Naive Bayes\n",
    "First up we have the Naive Bayes algorithm. First we will test how well the Discrete Naive Bayes works, and then how the Continuous fares."
   ]
  },
  {
   "cell_type": "code",
C.G.Vedant's avatar
C.G.Vedant a validé
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
C.G.Vedant's avatar
C.G.Vedant a validé
      "Error ratio for Discrete: 0.040000000000000036\n",
      "Error ratio for Continuous: 0.040000000000000036\n"
     ]
    }
   ],
   "source": [
    "nBD = NaiveBayesLearner(iris, continuous=False)\n",
    "print(\"Error ratio for Discrete:\", err_ratio(nBD, iris))\n",
    "nBC = NaiveBayesLearner(iris, continuous=True)\n",
    "print(\"Error ratio for Continuous:\", err_ratio(nBC, iris))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The error for the Naive Bayes algorithm is very, very low; close to 0. There is also very little difference between the discrete and continuous version of the algorithm."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## k-Nearest Neighbors\n",
    "Now we will take a look at kNN, for different values of *k*. Note that *k* should have odd values, to break any ties between two classes."
   ]
  },
  {
   "cell_type": "code",
C.G.Vedant's avatar
C.G.Vedant a validé
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Error ratio for k=1: 0.0\n",
C.G.Vedant's avatar
C.G.Vedant a validé
      "Error ratio for k=3: 0.06000000000000005\n",
      "Error ratio for k=5: 0.1266666666666667\n",
      "Error ratio for k=7: 0.19999999999999996\n"
     ]
    }
   ],
   "source": [
    "kNN_1 = NearestNeighborLearner(iris, k=1)\n",
    "kNN_3 = NearestNeighborLearner(iris, k=3)\n",
    "kNN_5 = NearestNeighborLearner(iris, k=5)\n",
    "kNN_7 = NearestNeighborLearner(iris, k=7)\n",
    "print(\"Error ratio for k=1:\", err_ratio(kNN_1, iris))\n",
    "print(\"Error ratio for k=3:\", err_ratio(kNN_3, iris))\n",
    "print(\"Error ratio for k=5:\", err_ratio(kNN_5, iris))\n",
    "print(\"Error ratio for k=7:\", err_ratio(kNN_7, iris))"
   "metadata": {},
    "Notice how the error became larger and larger as *k* increased. This is generally the case with datasets where classes are spaced out, as is the case with the iris dataset. If items from different classes were closer together, classification would be more difficult. Usually a value of 1, 3 or 5 for *k* suffices.\n",
    "Also note that since the training set is also the testing set, for *k* equal to 1 we get a perfect score, since the item we want to classify each time is already in the dataset and its closest neighbor is itself."
   "cell_type": "markdown",
   "metadata": {},
    "For the Perceptron, we first need to convert class names to integers. Let's see how it performs in the dataset."
C.G.Vedant's avatar
C.G.Vedant a validé
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
C.G.Vedant's avatar
C.G.Vedant a validé
      "Error ratio for Perceptron: 0.31333333333333335\n"
     ]
    }
   ],
   "source": [
    "iris2 = DataSet(name=\"iris\")\n",
    "iris2.classes_to_numbers()\n",
    "\n",
    "perceptron = PerceptronLearner(iris2)\n",
    "print(\"Error ratio for Perceptron:\", err_ratio(perceptron, iris2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
    "The Perceptron didn't fare very well mainly because the dataset is not linearly separated. On simpler datasets the algorithm performs much better, but unfortunately such datasets are rare in real life scenarios."
   ]
  }
 ],
 "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.5.3"
 "nbformat_minor": 2