nvidia-AI.summerschool17-no.../teaching-lw/101-intro-classification.ipynb
2017-09-22 19:26:46 +02:00

892 lines
No EOL
22 KiB
Text

{
"metadata": {
"name": "101-intro-classification"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Title: Introduction to Classification\n",
"Author: Thomas Breuel\n",
"Institution: UniKL"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"\n",
"import numpy,scipy,scipy.ndimage,zlib\n",
"import random as pyrandom\n",
"\n",
"from pylab import *\n",
"from pylab import random as arandom\n",
"\n",
"def method(cls):\n",
" import new\n",
" def _wrap(f):\n",
" cls.__dict__[f.func_name] = new.instancemethod(f,None,cls)\n",
" return None\n",
" return _wrap"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 18
},
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"An Object-Oriented View of Classification"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In regular software engineering, people think of software \n",
"development as starting from a specification. In pattern \n",
"recognition, however, you don't know the \"specification\". Instead, \n",
"you have a source of data that generates instances. Let's \n",
"look at how this works.\n",
"\n",
"First, we generate a problem instance. In this case, the problem instance is actually the \n",
"instantiation of a class, but in the real world, the problem instance \n",
"is usually some particular physical instance: a device, \n",
"a web site, a person, a book, etc.\n",
"\n",
"We may call the problem instance nature, \n",
"in order to emphasize that it is usually \n",
"given by physics and not another software system.\n",
"However, \"nature\" may well be another software system."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Nature\n",
"class Nature:\n",
" def training_sample(self):\n",
" return (c,r)\n",
" def challenge(self):\n",
" return c\n",
" def response(self,r):\n",
" return reward"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 19
},
{
"cell_type": "code",
"collapsed": true,
"input": [
"# An instance of \"nature\"\n",
"class SevenSegments(Nature):\n",
" def __init__(self):\n",
" self.vs = [None] * 10\n",
" self.vs[0] = array((1,1,1,1,1,1,0))\n",
" self.vs[1] = array((0,1,1,0,0,0,0))\n",
" self.vs[2] = array((1,1,0,1,1,0,1))\n",
" self.vs[3] = array((1,1,1,1,0,0,1))\n",
" self.vs[4] = array((0,1,1,0,0,1,1))\n",
" self.vs[5] = array((1,0,1,1,0,1,1))\n",
" self.vs[6] = array((1,0,1,1,1,1,1))\n",
" self.vs[7] = array((1,1,1,0,0,0,0))\n",
" self.vs[8] = array((1,1,1,1,1,1,1))\n",
" self.vs[9] = array((1,1,1,1,0,1,1))"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 20
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Nature gives us _training samples_ consisting of measurements and correct responses.\n"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"@method(SevenSegments)\n",
"def training_sample(self):\n",
" c = pyrandom.randint(0,9)\n",
" v = self.vs[c]\n",
" return (v,c)"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 21
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Based on these training samples, we need to build a model that then returns correct classifications. These are training samples without the classification.\n",
"\n"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"@method(SevenSegments)\n",
"def challenge(self):\n",
" v,self.c = self.training_sample()\n",
" return v"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 22
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Our classifier needs to respond with a class, and nature evaluates our response and gives us feedback.\n",
"\n"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"@method(SevenSegments)\n",
"def response(self,c):\n",
" return (c==self.c)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"nature = SevenSegments()\n",
"nature.training_sample()"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 23,
"text": [
"(array([1, 1, 1, 1, 1, 1, 0]), 0)"
]
}
],
"prompt_number": 23
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We are trying to build a _model_ of nature.\n",
"These respond to challenges by predicting a response.\n",
"\n"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Models\n",
"class Model:\n",
" def __init__(self,dataset):\n",
" self.dataset = dataset\n",
" def predict(self,v):\n",
" return 0"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 24
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Nature gives us training examples. These training examples consist of some kind of measurement vector v and a corresponding classification c.\n",
"\n"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"v,c = nature.training_sample()\n",
"print \"measurement vector\",v\n",
"print \"class\",c"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"measurement vector [1 0 1 1 0 1 1]\n",
"class 5\n"
]
}
],
"prompt_number": 25
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"At training time, we can request training samples.\n",
"Usually, generating labeled training samples costs money, so we only obtain a limited number of them. \n",
"These are usually collected in a dataset.\n",
"\n"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"trainingset = [nature.training_sample() for i in range(100)]\n",
"trainingset[:5]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 26,
"text": [
"[(array([1, 1, 0, 1, 1, 0, 1]), 2),\n",
" (array([1, 0, 1, 1, 1, 1, 1]), 6),\n",
" (array([1, 1, 1, 1, 1, 1, 0]), 0),\n",
" (array([1, 1, 1, 1, 1, 1, 0]), 0),\n",
" (array([1, 1, 1, 1, 0, 0, 1]), 3)]"
]
}
],
"prompt_number": 26
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We usually use the dataset to create a model. \n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"collapsed": true,
"input": [
"model = Model(trainingset)"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 27
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"After training, nature presents us with challenges or test samples.\n",
"\n"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"nature.challenge()"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 28,
"text": [
"array([1, 1, 1, 1, 0, 1, 1])"
]
}
],
"prompt_number": 28
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The task of the model is to predict a value based on the challenge.\n",
"\n"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"prediction = model.predict(nature.challenge())\n",
"print prediction"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"0\n"
]
}
],
"prompt_number": 29
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Our prediction is then handed back to nature for evaluation. We may or may not see this evaluation, but eventually, our model will be judged on the quality of its predictions.\n",
"\n"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"nature.response(prediction)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 30,
"text": [
"False"
]
}
],
"prompt_number": 30
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A second important question is how we validate model. In standard software engineering, \n",
"the assumption is (rightly or wrongly) that all we need to show is \n",
"conformance to the specification. However, pattern recognition and \n",
"machine learning methods do not have a specification. They do, however, \n",
"have lots of data, and that lets us make good empirical predictions about performance."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# evaluating the model\n",
"def count_errors(nature,model,trials=100):\n",
" errors = 0\n",
" for i in range(trials):\n",
" v = nature.challenge()\n",
" c = model.predict(v)\n",
" if nature.response(c)!=True:\n",
" errors += 1\n",
" return errors\n",
"count_errors(nature,model,trials=100)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 31,
"text": [
"93"
]
}
],
"prompt_number": 31
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"OK, that's not very good... the model is wrong about 90 percent of the time--chance level. Let's try for something better.\n",
"\n"
]
},
{
"cell_type": "code",
"collapsed": true,
"input": [
"class MemoryModel:\n",
" def __init__(self,dataset):\n",
" self.memory = {}\n",
" for v,c in dataset:\n",
" self.memory[tuple(v)] = c\n",
" def predict(self,v):\n",
" return self.memory.get(tuple(v),0)\n",
" "
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 32
},
{
"cell_type": "code",
"collapsed": true,
"input": [
"model = MemoryModel(trainingset)\n"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 33
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"count_errors(nature,model,trials=100)\n"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 34,
"text": [
"0"
]
}
],
"prompt_number": 34
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the noise free case, memorization of samples may give good response.\n",
"\n",
"It still lacks _generalization_: that is, it can't make good predictions for previously unseen samples that are similar to, but different from, existing samples."
]
},
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"Noisy Samples"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the above example, the model just generated fixed patterns\n",
"with a one-to-one correspondence to classes.\n",
"\n",
"In practice, there is usually noise.\n",
"\n",
"Noise means:\n",
"\n",
"- multiple patterns correspond to each class\n",
"- each pattern may correspond to multiple classes\n",
"- the correspondences are non-deterministic\n",
"\n",
"The overall goal is to minimize the *error rate*."
]
},
{
"cell_type": "code",
"collapsed": true,
"input": [
"from pylab import random as arandom\n",
"class NoisySevenSegments(SevenSegments):\n",
" def __init__(self):\n",
" self.p_noise = 0.07\n",
" self.vs = [None] * 10\n",
" self.vs[0] = array((1,1,1,1,1,1,0))\n",
" self.vs[1] = array((0,1,1,0,0,0,0))\n",
" self.vs[2] = array((1,1,0,1,1,0,1))\n",
" self.vs[3] = array((1,1,1,1,0,0,1))\n",
" self.vs[4] = array((0,1,1,0,0,1,1))\n",
" self.vs[5] = array((1,0,1,1,0,1,1))\n",
" self.vs[6] = array((1,0,1,1,1,1,1))\n",
" self.vs[7] = array((1,1,1,0,0,0,0))\n",
" self.vs[8] = array((1,1,1,1,1,1,1))\n",
" self.vs[9] = array((1,1,1,1,0,1,1))"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 62
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now the training samples consist of the true targets, but with some of the segments flipped.\n",
"\n"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"@method(NoisySevenSegments)\n",
"def training_sample(self):\n",
" c = pyrandom.randint(0,len(self.vs)-1)\n",
" v = self.vs[c]\n",
" flip = 1.0*(arandom(size=7)<self.p_noise)\n",
" v = 1.0*(v!=flip) \n",
" return (v,c)"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 63
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's see how well the memory model works.\n",
"\n"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"nature = NoisySevenSegments()\n",
"trainingset = [nature.training_sample() for i in range(100)]\n",
"model = MemoryModel(trainingset)\n",
"print count_errors(nature,model,trials=10000)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"3425\n"
]
}
],
"prompt_number": 64
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's use \"similarity\" to help improve performance.\n",
"\n"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from scipy.spatial import distance\n",
"distance.cdist(randn(1,10),randn(10,10))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 65,
"text": [
"array([[ 3.8478801 , 4.20201828, 3.70312897, 5.37046302, 3.23728652,\n",
" 4.94973151, 3.44314282, 2.96195443, 3.27705394, 3.53697688]])"
]
}
],
"prompt_number": 65
},
{
"cell_type": "code",
"collapsed": true,
"input": [
"# nearest neighbor models\n",
"class NearestNeighborModel:\n",
" def __init__(self,dataset):\n",
" self.centers = array([v for v,c in dataset],'f')\n",
" self.classes = array([c for v,c in dataset],'i')\n",
" def predict(self,v):\n",
" ds = distance.cdist(array([v],'f'),self.centers)\n",
" i = argmin(ds[0])\n",
" return self.classes[i]"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 66
},
{
"cell_type": "code",
"collapsed": true,
"input": [
"model = NearestNeighborModel(trainingset)"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 67
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"count_errors(nature,model,trials=10000)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 68,
"text": [
"2859"
]
}
],
"prompt_number": 68
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We often determine the *error rate*,\n",
"the percentage of samples that are *misclassified*."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"count_errors(nature,model,trials=10000)/10000.0"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 69,
"text": [
"0.2785"
]
}
],
"prompt_number": 69
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Test Sets\n",
"=========\n",
"\n",
"Above, we evaluated the model by trying it out in the real world\n",
"and getting feedback from nature. However, usually, we use\n",
"a *test set* instead, a set of samples obtained like training\n",
"samples.\n",
"\n",
"We can use this to estimate the error rate as well."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"testset = [nature.training_sample() for i in range(100)]\n",
"truth = [c for v,c in testset]\n",
"predictions = [model.predict(v) for v,c in testset]\n",
"sum(array(predictions)!=array(truth))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 70,
"text": [
"26"
]
}
],
"prompt_number": 70
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can wrap this up as a function,\n",
"a function that evaluates using a testset."
]
},
{
"cell_type": "code",
"collapsed": true,
"input": [
"def dataset_eval(testset,model):\n",
" truth = [c for v,c in testset]\n",
" predictions = [model.predict(v) for v,c in testset]\n",
" return sum(array(predictions)!=array(truth))*1.0/len(testset)"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 71
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"dataset_eval(testset,model)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 72,
"text": [
"0.26000000000000001"
]
}
],
"prompt_number": 72
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that we can also evaluate the performance of the\n",
"model on the training set itself.\n",
"This will, in general, give an error rate that is\n",
"too low.\n",
"For nearest neighbor classifiers, it is easy to see why."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"dataset_eval(trainingset,model)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 73,
"text": [
"0.13"
]
}
],
"prompt_number": 73
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Two important things to remember about test sets are:\n",
"\n",
"- the test set must be statistically representative of the training set\n",
"- the error rate on the training set itself is often lower than the error rate on the test set"
]
},
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"Manual Creation of Test/Training Sets"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In fact, often we just get a set of training samples. In that case, we need to\n",
"perform manually splitting of the data into training and test sets.\n",
"\n"
]
},
{
"cell_type": "code",
"collapsed": true,
"input": [
"import random as pyrandom\n",
"all_indexes = set(range(len(trainingset)))\n",
"test_indexes = set(pyrandom.sample(all_indexes,int(0.1*len(all_indexes))))\n",
"training_indexes = set(all_indexes-test_indexes)"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 74
},
{
"cell_type": "code",
"collapsed": true,
"input": [
"my_testset = [trainingset[i] for i in test_indexes]\n",
"my_trainingset = [trainingset[i] for i in training_indexes]"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 75
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In fact, often we split labeled data into three sets:\n",
"\n",
"- a *training set* that we use to train one or more models\n",
"- a *validation set* that we use to optimize parameter choices\n",
"- a *test set* that we use for final evaluation of error rates\n",
"\n",
"Note that you cannot use a test set too often, because just by chance\n",
"you may find a model that seems to work well by chance.\n",
"\n",
"We will talk about ways of dealing with this problem later."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [],
"language": "python",
"metadata": {},
"outputs": []
}
],
"metadata": {}
}
]
}