Newer
Older
"deletable": true,
"editable": true
"source": [
"# Learning\n",
"\n",
"This notebook serves as supporting material for topics covered in **Chapter 18 - Learning from Examples** , **Chapter 19 - Knowledge in Learning**, **Chapter 20 - Learning Probabilistic Models** from the book *Artificial Intelligence: A Modern Approach*. This notebook uses implementations from [learning.py](https://github.com/aimacode/aima-python/blob/master/learning.py). Let's start by importing everything from the module:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"from learning import *"
"metadata": {
"deletable": true,
"editable": true
},
"## Contents\n",
"\n",
"* Machine Learning Overview\n",
"* Datasets\n",
"* Plurality Learner\n",
"* k-Nearest Neighbours\n",
"* Perceptron\n",
"* MNIST Handwritten Digits\n",
" * Loading and Visualising\n",
" * Testing\n",
" * kNN Classifier"
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Machine Learning Overview\n",
"\n",
"In this notebook, we learn about agents that can improve their behavior through diligent study of their own experiences.\n",
"\n",
"An agent is **learning** if it improves its performance on future tasks after making observations about the world.\n",
"\n",
"There are three types of feedback that determine the three main types of learning:\n",
"\n",
"* **Supervised Learning**:\n",
"\n",
"In Supervised Learning the agent observes some example input-output pairs and learns a function that maps from input to output.\n",
"\n",
"**Example**: Let's think of an agent to classify images containing cats or dogs. If we provide an image containing a cat or a dog, this agent should output a string \"cat\" or \"dog\" for that particular image. To teach this agent, we will give a lot of input-output pairs like {cat image-\"cat\"}, {dog image-\"dog\"} to the agent. The agent then learns a function that maps from an input image to one of those strings.\n",
"\n",
"* **Unsupervised Learning**:\n",
"\n",
"In Unsupervised Learning the agent learns patterns in the input even though no explicit feedback is supplied. The most common type is **clustering**: detecting potential useful clusters of input examples.\n",
"\n",
"**Example**: A taxi agent would develop a concept of *good traffic days* and *bad traffic days* without ever being given labeled examples.\n",
"\n",
"* **Reinforcement Learning**:\n",
"\n",
"In Reinforcement Learning the agent learns from a series of reinforcements—rewards or punishments.\n",
"\n",
"**Example**: Let's talk about an agent to play the popular Atari game—[Pong](http://www.ponggame.org). We will reward a point for every correct move and deduct a point for every wrong move from the agent. Eventually, the agent will figure out its actions prior to reinforcement were most responsible for it."
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Datasets\n",
"\n",
"For the following tutorials we will use a range of datasets, to better showcase the strengths and weaknesses of the algorithms. The datasests are the following:\n",
"\n",
"* [Fisher's Iris](https://github.com/aimacode/aima-data/blob/a21fc108f52ad551344e947b0eb97df82f8d2b2b/iris.csv): Each item represents a flower, with four measurements: the length and the width of the sepals and petals. Each item/flower is categorized into one of three species: Setosa, Versicolor and Virginica.\n",
"* [Zoo](https://github.com/aimacode/aima-data/blob/a21fc108f52ad551344e947b0eb97df82f8d2b2b/zoo.csv): The dataset holds different animals and their classification as \"mammal\", \"fish\", etc. The new animal we want to classify has the following measurements: 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 4, 1, 0, 1 (don't concern yourself with what the measurements mean)."
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"To make using the datasets easier, we have written a class, `DataSet`, in `learning.py`. The tutorials found here make use of this class.\n",
"Let's have a look at how it works before we get started with the algorithms."
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"### Intro\n",
"A lot of the datasets we will work with are .csv files (although other formats are supported too). We have a collection of sample datasets ready to use [on aima-data](https://github.com/aimacode/aima-data/tree/a21fc108f52ad551344e947b0eb97df82f8d2b2b). Two examples are the datasets mentioned above (*iris.csv* and *zoo.csv*). You can find plenty datasets online, and a good repository of such datasets is [UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets.html).\n",
"In such files, each line corresponds to one item/measurement. Each individual value in a line represents a *feature* and usually there is a value denoting the *class* of the item.\n",
"You can find the code for the dataset here:"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"%psource DataSet"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"### Class Attributes\n",
"* **examples**: Holds the items of the dataset. Each item is a list of values.\n",
"* **attrs**: The indexes of the features (by default in the range of [0,f), where *f* is the number of features. For example, `item[i]` returns the feature at index *i* of *item*.\n",
"* **attrnames**: An optional list with attribute names. For example, `item[s]`, where *s* is a feature name, returns the feature of name *s* in *item*.\n",
"* **target**: The attribute a learning algorithm will try to predict. By default the last attribute.\n",
"* **inputs**: This is the list of attributes without the target.\n",
"* **values**: A list of lists which holds the set of possible values for the corresponding attribute/feature. If initially `None`, it gets computed (by the function `setproblem`) from the examples.\n",
"* **distance**: The distance function used in the learner to calculate the distance between two items. By default `mean_boolean_error`.\n",
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
"* **name**: Name of the dataset.\n",
"\n",
"* **source**: The source of the dataset (url or other). Not used in the code.\n",
"\n",
"* **exclude**: A list of indexes to exclude from `inputs`. The list can include either attribute indexes (attrs) or names (attrnames)."
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"### Class Helper Functions\n",
"\n",
"These functions help modify a `DataSet` object to your needs.\n",
"\n",
"* **sanitize**: Takes as input an example and returns it with non-input (target) attributes replaced by `None`. Useful for testing. Keep in mind that the example given is not itself sanitized, but instead a sanitized copy is returned.\n",
"\n",
"* **classes_to_numbers**: Maps the class names of a dataset to numbers. If the class names are not given, they are computed from the dataset values. Useful for classifiers that return a numerical value instead of a string.\n",
"\n",
"* **remove_examples**: Removes examples containing a given value. Useful for removing examples with missing values, or for removing classes (needed for binary classifiers)."
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"### Importing a Dataset\n",
"\n",
"#### Importing from aima-data\n",
"\n",
"Datasets uploaded on aima-data can be imported with the following line:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"iris = DataSet(name=\"iris\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"To check that we imported the correct dataset, we can do the following:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[5.1, 3.5, 1.4, 0.2, 'setosa']\n",
"[0, 1, 2, 3]\n"
]
}
],
"source": [
"print(iris.examples[0])\n",
"print(iris.inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"Which correctly prints the first line in the csv file and the list of attribute indexes."
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"When importing a dataset, we can specify to exclude an attribute (for example, at index 1) by setting the parameter `exclude` to the attribute index or name."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0, 2, 3]\n"
]
}
],
"source": [
"iris2 = DataSet(name=\"iris\",exclude=[1])\n",
"print(iris2.inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"### Attributes\n",
"\n",
"Here we showcase the attributes.\n",
"\n",
"First we will print the first three items/examples in the dataset."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[5.1, 3.5, 1.4, 0.2, 'setosa'], [4.9, 3.0, 1.4, 0.2, 'setosa'], [4.7, 3.2, 1.3, 0.2, 'setosa']]\n"
]
}
],
"source": [
"print(iris.examples[:3])"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"Then we will print `attrs`, `attrnames`, `target`, `input`. Notice how `attrs` holds values in [0,4], but since the fourth attribute is the target, `inputs` holds values in [0,3]."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"attrs: [0, 1, 2, 3, 4]\n",
"attrnames (by default same as attrs): [0, 1, 2, 3, 4]\n",
"target: 4\n",
"inputs: [0, 1, 2, 3]\n"
]
}
],
"source": [
"print(\"attrs:\", iris.attrs)\n",
"print(\"attrnames (by default same as attrs):\", iris.attrnames)\n",
"print(\"target:\", iris.target)\n",
"print(\"inputs:\", iris.inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"Now we will print all the possible values for the first feature/attribute."
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[4.7, 5.5, 6.3, 5.0, 4.9, 5.1, 4.6, 5.4, 4.4, 4.8, 5.8, 7.0, 7.1, 4.5, 5.9, 5.6, 6.9, 6.6, 6.5, 6.4, 6.0, 6.1, 7.6, 7.4, 7.9, 4.3, 5.7, 5.3, 5.2, 6.7, 6.2, 6.8, 7.3, 7.2, 7.7]\n"
]
}
],
"source": [
"print(iris.values[0])"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"Finally we will print the dataset's name and source. Keep in mind that we have not set a source for the dataset, so in this case it is empty."
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"name: iris\n",
"source: \n"
]
}
],
"source": [
"print(\"name:\", iris.name)\n",
"print(\"source:\", iris.source)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"A useful combination of the above is `dataset.values[dataset.target]` which returns the possible values of the target. For classification problems, this will return all the possible classes. Let's try it:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['setosa', 'virginica', 'versicolor']\n"
]
}
],
"source": [
"print(iris.values[iris.target])"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"### Helper Functions"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"We will now take a look at the auxiliary functions found in the class.\n",
"\n",
"First we will take a look at the `sanitize` function, which sets the non-input values of the given example to `None`.\n",
"\n",
"In this case we want to hide the class of the first example, so we will sanitize it.\n",
"\n",
"Note that the function doesn't actually change the given example; it returns a sanitized *copy* of it."
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Sanitized: [5.1, 3.5, 1.4, 0.2, None]\n",
"Original: [5.1, 3.5, 1.4, 0.2, 'setosa']\n"
]
}
],
"source": [
"print(\"Sanitized:\",iris.sanitize(iris.examples[0]))\n",
"print(\"Original:\",iris.examples[0])"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"Currently the `iris` dataset has three classes, setosa, virginica and versicolor. We want though to convert it to a binary class dataset (a dataset with two classes). The class we want to remove is \"virginica\". To accomplish that we will utilize the helper function `remove_examples`."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['setosa', 'versicolor']\n"
]
}
],
"source": [
"iris.remove_examples(\"virginica\")\n",
"print(iris.values[iris.target])"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"Finally we take a look at `classes_to_numbers`. For a lot of the classifiers in the module (like the Neural Network), classes should have numerical values. With this function we map string class names to numbers."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Class of first example: setosa\n",
"Class of first example: 0\n"
]
}
],
"source": [
"print(\"Class of first example:\",iris.examples[0][iris.target])\n",
"iris.classes_to_numbers()\n",
"print(\"Class of first example:\",iris.examples[0][iris.target])"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"As you can see \"setosa\" was mapped to 0."
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
"## Plurality Learner Classifier\n",
"\n",
"### Overview\n",
"\n",
"The Plurality Learner is a simple algorithm, used mainly as a baseline comparison for other algorithms. It finds the most popular class in the dataset and classifies any subsequent item to that class. Essentially, it classifies every new item to the same class. For that reason, it is not used very often, instead opting for more complicated algorithms when we want accurate classification.\n",
"\n",
"\n",
"\n",
"Let's see how the classifier works with the plot above. There are three classes named **Class A** (orange-colored dots) and **Class B** (blue-colored dots) and **Class C** (green-colored dots). Every point in this plot has two **features** (i.e. X<sub>1</sub>, X<sub>2</sub>). Now, let's say we have a new point, a red star and we want to know which class this red star belongs to. Solving this problem by predicting the class of this new red star is our current classification problem.\n",
"\n",
"The Plurality Learner will find the class most represented in the plot. ***Class A*** has four items, ***Class B*** has three and ***Class C*** has seven. The most popular class is ***Class C***. Therefore, the item will get classified in ***Class C***, despite the fact that it is closer to the other two classes."
},
{
"cell_type": "markdown",
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"### Implementation\n",
"\n",
"Below follows the implementation of the PluralityLearner algorithm:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"def PluralityLearner(dataset):\n",
" \"\"\"A very dumb algorithm: always pick the result that was most popular\n",
" in the training data. Makes a baseline for comparison.\"\"\"\n",
" most_popular = mode([e[dataset.target] for e in dataset.examples])\n",
"\n",
" def predict(example):\n",
" \"Always return same result: the most popular from the training set.\"\n",
" return most_popular\n",
" return predict"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"It takes as input a dataset and returns a function. We can later call this function with the item we want to classify as the argument and it returns the class it should be classified in.\n",
"\n",
"The function first finds the most popular class in the dataset and then each time we call its \"predict\" function, it returns it. Note that the input (\"example\") does not matter. The function always returns the same class."
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"### Example\n",
"\n",
"For this example, we will not use the Iris dataset, since each class is represented the same. This will throw an error. Instead we will use the zoo dataset."
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"mammal\n"
]
}
],
"source": [
"zoo = DataSet(name=\"zoo\")\n",
"\n",
"pL = PluralityLearner(zoo)\n",
"print(pL([1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 4, 1, 0, 1]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"The output for the above code is \"mammal\", since that is the most popular and common class in the dataset."
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## k-Nearest Neighbours (kNN) Classifier\n",
"\n",
"### Overview\n",
"The k-Nearest Neighbors algorithm is a non-parametric method used for classification and regression. We are going to use this to classify Iris flowers. More about kNN on [Scholarpedia](http://www.scholarpedia.org/article/K-nearest_neighbor).\n",
"\n",
""
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"Let's see how kNN works with a simple plot shown in the above picture.\n",
"\n",
"We have co-ordinates (we call them **features** in Machine Learning) of this red star and we need to predict its class using the kNN algorithm. In this algorithm, the value of **k** is arbitrary. **k** is one of the **hyper parameters** for kNN algorithm. We choose this number based on our dataset and choosing a particular number is known as **hyper parameter tuning/optimising**. We learn more about this in coming topics.\n",
"\n",
"Let's put **k = 3**. It means you need to find 3-Nearest Neighbors of this red star and classify this new point into the majority class. Observe that smaller circle which contains three points other than **test point** (red star). As there are two violet points, which form the majority, we predict the class of red star as **violet- Class B**.\n",
"\n",
"Similarly if we put **k = 5**, you can observe that there are four yellow points, which form the majority. So, we classify our test point as **yellow- Class A**.\n",
"\n",
"In practical tasks, we iterate through a bunch of values for k (like [1, 3, 5, 10, 20, 50, 100]), see how it performs and select the best one. "
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"### Implementation\n",
"\n",
"Below follows the implementation of the kNN algorithm:"
]
},
{
"cell_type": "code",
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"def NearestNeighborLearner(dataset, k=1):\n",
" \"\"\"k-NearestNeighbor: the k nearest neighbors vote.\"\"\"\n",
" def predict(example):\n",
" \"\"\"Find the k closest items, and have them vote for the best.\"\"\"\n",
" best = heapq.nsmallest(k, ((dataset.distance(e, example), e)\n",
" for e in dataset.examples))\n",
" return mode(e[dataset.target] for (d, e) in best)\n",
" return predict"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"It takes as input a dataset and k (default value is 1) and it returns a function, which we can later use to classify a new item.\n",
"To accomplish that, the function uses a heap-queue, where the items of the dataset are sorted according to their distance from *example* (the item to classify). We then take the k smallest elements from the heap-queue and we find the majority class. We classify the item to this class."
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"### Example\n",
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
"We measured a new flower with the following values: 5.1, 3.0, 1.1, 0.1. We want to classify that item/flower in a class. To do that, we write the following:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"setosa\n"
]
}
],
"source": [
"iris = DataSet(name=\"iris\")\n",
"\n",
"kNN = NearestNeighborLearner(iris,k=3)\n",
"print(kNN([5.1,3.0,1.1,0.1]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"The output of the above code is \"setosa\", which means the flower with the above measurements is of the \"setosa\" species."
]
},
{
"cell_type": "markdown",
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
"metadata": {
"deletable": true,
"editable": true
},
"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",
"You can think of it as a single neuron. It has *n* synapses, each with its own weight. Each synapse corresponds to one item feature. Perceptron multiplies each item feature with the corresponding synapse weight and then adds them together (aka, the dot product) and checks whether this value is greater than the threshold. If yes, it returns 1. It returns 0 otherwise.\n",
"\n",
""
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"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. If the result is greater than a predefined threshold (usually 0.5, 0 or 1), it returns 1. If it is less than the threshold, it returns 0.\n",
"\n",
"NOTE: The current implementation of the algorithm classifies an item into one of two classes. It is a binary classifier and will not work well for multi-class datasets."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"def PerceptronLearner(dataset, learning_rate=0.01, epochs=100):\n",
" \"\"\"Logistic Regression, NO hidden layer\"\"\"\n",
" i_units = len(dataset.inputs)\n",
" o_units = 1 # As of now, dataset.target gives only one index.\n",
" hidden_layer_sizes = []\n",
" raw_net = network(i_units, hidden_layer_sizes, o_units)\n",
" learned_net = BackPropagationLearner(dataset, raw_net, learning_rate, epochs)\n",
"\n",
" def predict(example):\n",
" # Input nodes\n",
" i_nodes = learned_net[0]\n",
"\n",
" # Activate input layer\n",
" for v, n in zip(example, i_nodes):\n",
" n.value = v\n",
"\n",
" # Forward pass\n",
" for layer in learned_net[1:]:\n",
" for node in layer:\n",
" inc = [n.value for n in node.inputs]\n",
" in_val = dotproduct(inc, node.weights)\n",
" node.value = node.activation(in_val)\n",
"\n",
" # Hypothesis\n",
" o_nodes = learned_net[-1]\n",
" pred = [o_nodes[i].value for i in range(o_units)]\n",
" return 1 if pred[0] >= 0.5 else 0\n",
"\n",
" return predict"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"The weights are trained from the `BackPropagationLearner`. 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 node, with the weights calculated.\n",
"\n",
"`PerceptronLearner` returns `predict`, a function that can be used to classify a new item.\n",
"\n",
"That function passes the input/example through the network, calculating the dot product of the input and the weights. If that value is greater than or equal to 0.5, it returns 1. Otherwise it returns 0."
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"### Example\n",
"\n",
"We will train the Perceptron on the iris dataset. Because, though, the algorithm is a binary classifier (which means it classifies an item in one of two classes) and the iris dataset has three classes, we need to transform the dataset into a proper form, with only two classes. Therefore, we will remove the third and final class of the dataset, *Virginica*.\n",
"\n",
"Then, we will try and classify the item/flower with measurements of 5,3,1,0.1."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n"
]
}
],
"source": [
"iris = DataSet(name=\"iris\")\n",
"iris.remove_examples(\"virginica\")\n",
"iris.classes_to_numbers()\n",
"\n",
"perceptron = PerceptronLearner(iris)\n",
"print(perceptron([5,3,1,0.1]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"The output is 0, which means the item is classified in the first class, *setosa*. This is indeed correct. Note that the Perceptron algorithm is not perfect and may produce false classifications."
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## MNIST Handwritten Digits Classification\n",
"\n",
"The MNIST database, available from [this page](http://yann.lecun.com/exdb/mnist/), is a large database of handwritten digits that is commonly used for training and testing/validating in Machine learning.\n",
"\n",
"The dataset has **60,000 training images** each of size 28x28 pixels with labels and **10,000 testing images** of size 28x28 pixels with labels.\n",
"\n",
"In this section, we will use this database to compare performances of different learning algorithms.\n",
"\n",
"It is estimated that humans have an error rate of about **0.2%** on this problem. Let's see how our algorithms perform!\n",
"NOTE: We will be using external libraries to load and visualize the dataset smoothly ([numpy](http://www.numpy.org/) for loading and [matplotlib](http://matplotlib.org/) for visualization). You do not need previous experience of the libraries to follow along."
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"### Loading MNIST digits data\n",
"\n",
"Let's start by loading MNIST data into numpy arrays."
]
},
{
"cell_type": "code",
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"import os, struct\n",
"import array\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from collections import Counter\n",
"%matplotlib inline\n",