Newer
Older
},
"outputs": [],
"source": [
"pseudocode(\"Decision Tree Learning\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 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",
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
]
},
{
"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",
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
]
},
{
"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",
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
]
},
{
"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 received 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",
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Example\n",
"\n",
"We will now use the Decision Tree Learner to classify a sample with values: 5.1, 3.0, 1.1, 0.1."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"setosa\n"
]
}
],
"source": [
"iris = DataSet(name=\"iris\")\n",
"\n",
"DTL = DecisionTreeLearner(iris)\n",
"print(DTL([5.1, 3.0, 1.1, 0.1]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As expected, the Decision Tree learner classifies the sample as \"setosa\" as seen in the previous section."
]
},
"## NAIVE BAYES LEARNER\n",
"\n",
"### Overview\n",
"\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 occurring 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",
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
"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",
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
"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",
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
]
},
{
"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",
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
"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 occurring 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",
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
"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",
"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:"
]
},
{
"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"
]
}
],
"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": [
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
"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",
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
"\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": [
""
]
},
{
"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."
]
},
{
"cell_type": "code",
},
"outputs": [],
"source": [
]
},
{
"cell_type": "markdown",
"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",
"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."
]
},
{
"cell_type": "code",
"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",
"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",
"## 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",
"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",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"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",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Error ratio for k=1: 0.0\n",
"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))"
]
},
{
"cell_type": "markdown",
"source": [
"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": {},
"### Perceptron\n",
"For the Perceptron, we first need to convert class names to integers. Let's see how it performs in the dataset."
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
]
}
],
"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."
]
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## AdaBoost\n",
"\n",
"### Overview\n",
"\n",
"**AdaBoost** is an algorithm which uses **ensemble learning**. In ensemble learning the hypotheses in the collection, or ensemble, vote for what the output should be and the output with the majority votes is selected as the final answer.\n",
"\n",
"AdaBoost algorithm, as mentioned in the book, works with a **weighted training set** and **weak learners** (classifiers that have about 50%+epsilon accuracy i.e slightly better than random guessing). It manipulates the weights attached to the the examples that are showed to it. Importance is given to the examples with higher weights.\n",
"\n",
"All the examples start with equal weights and a hypothesis is generated using these examples. Examples which are incorrectly classified, their weights are increased so that they can be classified correctly by the next hypothesis. The examples that are correctly classified, their weights are reduced. This process is repeated *K* times (here *K* is an input to the algorithm) and hence, *K* hypotheses are generated.\n",
"\n",
"These *K* hypotheses are also assigned weights according to their performance on the weighted training set. The final ensemble hypothesis is the weighted-majority combination of these *K* hypotheses.\n",
"\n",
"The speciality of AdaBoost is that by using weak learners and a sufficiently large *K*, a highly accurate classifier can be learned irrespective of the complexity of the function being learned or the dullness of the hypothesis space."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Implementation\n",
"\n",
"As seen in the previous section, the `PerceptronLearner` does not perform that well on the iris dataset. We'll use perceptron as the learner for the AdaBoost algorithm and try to increase the accuracy. \n",
"\n",
"Let's first see what AdaBoost is exactly:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n",
" \"http://www.w3.org/TR/html4/strict.dtd\">\n",
"\n",
"<html>\n",
"<head>\n",
" <title></title>\n",
" <meta http-equiv=\"content-type\" content=\"text/html; charset=None\">\n",
" <style type=\"text/css\">\n",
"td.linenos { background-color: #f0f0f0; padding-right: 10px; }\n",
"span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\n",
"pre { line-height: 125%; }\n",
"body .hll { background-color: #ffffcc }\n",
"body { background: #f8f8f8; }\n",
"body .c { color: #408080; font-style: italic } /* Comment */\n",
"body .err { border: 1px solid #FF0000 } /* Error */\n",
"body .k { color: #008000; font-weight: bold } /* Keyword */\n",
"body .o { color: #666666 } /* Operator */\n",
"body .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
"body .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
"body .cp { color: #BC7A00 } /* Comment.Preproc */\n",
"body .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
"body .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
"body .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
"body .gd { color: #A00000 } /* Generic.Deleted */\n",
"body .ge { font-style: italic } /* Generic.Emph */\n",
"body .gr { color: #FF0000 } /* Generic.Error */\n",
"body .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
"body .gi { color: #00A000 } /* Generic.Inserted */\n",
"body .go { color: #888888 } /* Generic.Output */\n",
"body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
"body .gs { font-weight: bold } /* Generic.Strong */\n",
"body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
"body .gt { color: #0044DD } /* Generic.Traceback */\n",
"body .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
"body .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
"body .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
"body .kp { color: #008000 } /* Keyword.Pseudo */\n",
"body .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
"body .kt { color: #B00040 } /* Keyword.Type */\n",
"body .m { color: #666666 } /* Literal.Number */\n",
"body .s { color: #BA2121 } /* Literal.String */\n",
"body .na { color: #7D9029 } /* Name.Attribute */\n",
"body .nb { color: #008000 } /* Name.Builtin */\n",
"body .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
"body .no { color: #880000 } /* Name.Constant */\n",
"body .nd { color: #AA22FF } /* Name.Decorator */\n",
"body .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
"body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
"body .nf { color: #0000FF } /* Name.Function */\n",
"body .nl { color: #A0A000 } /* Name.Label */\n",
"body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
"body .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
"body .nv { color: #19177C } /* Name.Variable */\n",
"body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
"body .w { color: #bbbbbb } /* Text.Whitespace */\n",
"body .mb { color: #666666 } /* Literal.Number.Bin */\n",
"body .mf { color: #666666 } /* Literal.Number.Float */\n",
"body .mh { color: #666666 } /* Literal.Number.Hex */\n",
"body .mi { color: #666666 } /* Literal.Number.Integer */\n",
"body .mo { color: #666666 } /* Literal.Number.Oct */\n",
"body .sa { color: #BA2121 } /* Literal.String.Affix */\n",
"body .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
"body .sc { color: #BA2121 } /* Literal.String.Char */\n",
"body .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
"body .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
"body .s2 { color: #BA2121 } /* Literal.String.Double */\n",
"body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
"body .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
"body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
"body .sx { color: #008000 } /* Literal.String.Other */\n",
"body .sr { color: #BB6688 } /* Literal.String.Regex */\n",
"body .s1 { color: #BA2121 } /* Literal.String.Single */\n",
"body .ss { color: #19177C } /* Literal.String.Symbol */\n",
"body .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
"body .fm { color: #0000FF } /* Name.Function.Magic */\n",
"body .vc { color: #19177C } /* Name.Variable.Class */\n",
"body .vg { color: #19177C } /* Name.Variable.Global */\n",
"body .vi { color: #19177C } /* Name.Variable.Instance */\n",
"body .vm { color: #19177C } /* Name.Variable.Magic */\n",
"body .il { color: #666666 } /* Literal.Number.Integer.Long */\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"<h2></h2>\n",
"\n",
"<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">AdaBoost</span><span class=\"p\">(</span><span class=\"n\">L</span><span class=\"p\">,</span> <span class=\"n\">K</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""[Figure 18.34]"""</span>\n",
" <span class=\"k\">def</span> <span class=\"nf\">train</span><span class=\"p\">(</span><span class=\"n\">dataset</span><span class=\"p\">):</span>\n",
" <span class=\"n\">examples</span><span class=\"p\">,</span> <span class=\"n\">target</span> <span class=\"o\">=</span> <span class=\"n\">dataset</span><span class=\"o\">.</span><span class=\"n\">examples</span><span class=\"p\">,</span> <span class=\"n\">dataset</span><span class=\"o\">.</span><span class=\"n\">target</span>\n",
" <span class=\"n\">N</span> <span class=\"o\">=</span> <span class=\"nb\">len</span><span class=\"p\">(</span><span class=\"n\">examples</span><span class=\"p\">)</span>\n",
" <span class=\"n\">epsilon</span> <span class=\"o\">=</span> <span class=\"mf\">1.</span> <span class=\"o\">/</span> <span class=\"p\">(</span><span class=\"mi\">2</span> <span class=\"o\">*</span> <span class=\"n\">N</span><span class=\"p\">)</span>\n",
" <span class=\"n\">w</span> <span class=\"o\">=</span> <span class=\"p\">[</span><span class=\"mf\">1.</span> <span class=\"o\">/</span> <span class=\"n\">N</span><span class=\"p\">]</span> <span class=\"o\">*</span> <span class=\"n\">N</span>\n",
" <span class=\"n\">h</span><span class=\"p\">,</span> <span class=\"n\">z</span> <span class=\"o\">=</span> <span class=\"p\">[],</span> <span class=\"p\">[]</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">k</span> <span class=\"ow\">in</span> <span class=\"nb\">range</span><span class=\"p\">(</span><span class=\"n\">K</span><span class=\"p\">):</span>\n",
" <span class=\"n\">h_k</span> <span class=\"o\">=</span> <span class=\"n\">L</span><span class=\"p\">(</span><span class=\"n\">dataset</span><span class=\"p\">,</span> <span class=\"n\">w</span><span class=\"p\">)</span>\n",
" <span class=\"n\">h</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">(</span><span class=\"n\">h_k</span><span class=\"p\">)</span>\n",
" <span class=\"n\">error</span> <span class=\"o\">=</span> <span class=\"nb\">sum</span><span class=\"p\">(</span><span class=\"n\">weight</span> <span class=\"k\">for</span> <span class=\"n\">example</span><span class=\"p\">,</span> <span class=\"n\">weight</span> <span class=\"ow\">in</span> <span class=\"nb\">zip</span><span class=\"p\">(</span><span class=\"n\">examples</span><span class=\"p\">,</span> <span class=\"n\">w</span><span class=\"p\">)</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">example</span><span class=\"p\">[</span><span class=\"n\">target</span><span class=\"p\">]</span> <span class=\"o\">!=</span> <span class=\"n\">h_k</span><span class=\"p\">(</span><span class=\"n\">example</span><span class=\"p\">))</span>\n",
" <span class=\"c1\"># Avoid divide-by-0 from either 0% or 100% error rates:</span>\n",
" <span class=\"n\">error</span> <span class=\"o\">=</span> <span class=\"n\">clip</span><span class=\"p\">(</span><span class=\"n\">error</span><span class=\"p\">,</span> <span class=\"n\">epsilon</span><span class=\"p\">,</span> <span class=\"mi\">1</span> <span class=\"o\">-</span> <span class=\"n\">epsilon</span><span class=\"p\">)</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">j</span><span class=\"p\">,</span> <span class=\"n\">example</span> <span class=\"ow\">in</span> <span class=\"nb\">enumerate</span><span class=\"p\">(</span><span class=\"n\">examples</span><span class=\"p\">):</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">example</span><span class=\"p\">[</span><span class=\"n\">target</span><span class=\"p\">]</span> <span class=\"o\">==</span> <span class=\"n\">h_k</span><span class=\"p\">(</span><span class=\"n\">example</span><span class=\"p\">):</span>\n",
" <span class=\"n\">w</span><span class=\"p\">[</span><span class=\"n\">j</span><span class=\"p\">]</span> <span class=\"o\">*=</span> <span class=\"n\">error</span> <span class=\"o\">/</span> <span class=\"p\">(</span><span class=\"mf\">1.</span> <span class=\"o\">-</span> <span class=\"n\">error</span><span class=\"p\">)</span>\n",
" <span class=\"n\">w</span> <span class=\"o\">=</span> <span class=\"n\">normalize</span><span class=\"p\">(</span><span class=\"n\">w</span><span class=\"p\">)</span>\n",
" <span class=\"n\">z</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">(</span><span class=\"n\">math</span><span class=\"o\">.</span><span class=\"n\">log</span><span class=\"p\">((</span><span class=\"mf\">1.</span> <span class=\"o\">-</span> <span class=\"n\">error</span><span class=\"p\">)</span> <span class=\"o\">/</span> <span class=\"n\">error</span><span class=\"p\">))</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">WeightedMajority</span><span class=\"p\">(</span><span class=\"n\">h</span><span class=\"p\">,</span> <span class=\"n\">z</span><span class=\"p\">)</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">train</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"psource(AdaBoost)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"AdaBoost takes as inputs: **L** and *K* where **L** is the learner and *K* is the number of hypotheses to be generated. The learner **L** takes in as inputs: a dataset and the weights associated with the examples in the dataset. But the `PerceptronLearner` doesnot handle weights and only takes a dataset as its input. \n",
"To remedy that we will give as input to the PerceptronLearner a modified dataset in which the examples will be repeated according to the weights associated to them. Intuitively, what this will do is force the learner to repeatedly learn the same example again and again until it can classify it correctly. \n",
"\n",
"To convert `PerceptronLearner` so that it can take weights as input too, we will have to pass it through the **`WeightedLearner`** function."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"psource(WeightedLearner)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `WeightedLearner` function will then call the `PerceptronLearner`, during each iteration, with the modified dataset which contains the examples according to the weights associated with them."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Example\n",
"\n",
"We will pass the `PerceptronLearner` through `WeightedLearner` function. Then we will create an `AdaboostLearner` classifier with number of hypotheses or *K* equal to 5."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"WeightedPerceptron = WeightedLearner(PerceptronLearner)\n",
"AdaboostLearner = AdaBoost(WeightedPerceptron, 5)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [