-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path07-sklclass.tex
636 lines (350 loc) · 19.8 KB
/
07-sklclass.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
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
\documentclass[MASTER.tex]{subfiles}
\textbf{Classification with scikit-learn}
* In this segment, we
look into the problem of classification, a situation in which a response is a categorical variable.
% * We will build upon the techniques that we previously discussed in the context of regression and show how they can be transferred to classification problems.
* We will introduces a number of classification techniques, and
convey their corresponding strengths and weaknesses by visually inspecting the decision boundaries for each model.
* Here we will use \textbf{scikit-learn}, an easy-to-use, general-purpose toolbox for machine learning in Python
%* This is part of a series of blog posts showing how to do common statistical learning techniques with Python.
%* We provide only a small amount of background on the concepts and techniques we cover, so if you’d like a more thorough explanation check out Introduction to Statistical Learning or sign up for the free online course run by the book’s authors here.
<p>
<p>
\textbf{Scikit-learn}\\
* Scikit-learn is a library that provides a variety of both supervised and unsupervised machine learning techniques.
* Supervised machine learning refers to the problem of inferring a function from labeled training data, and it comprises both regression and classification.
<p>
\textbf{Unspervised Learning}
*
Unsupervised machine learning, on the other hand, refers to the problem of finding interesting patterns or structure in the data; it comprises techniques such as clustering and dimensionality reduction.
* In addition to statistical learning techniques, scikit-learn provides utilities for common tasks such as model selection, feature extraction, and feature selection.
<p>
\textbf{Estimators}
* Scikit-learn provides an object-oriented interface centered around the concept of an Estimator. * According to the scikit-learn tutorial “\textit{An estimator is any object that learns from data; it may be a classification, regression or clustering algorithm or a transformer that extracts/filters useful features from raw data.}”
<p>
* The \texttt{Estimator.fit} method sets the state of the estimator based on the training data.
* Usually, the data is comprised of a two-dimensional numpy array X of shape \texttt{(n\_samples, n\_predictors) }that holds the so-called feature matrix and a one-dimensional numpy array y that holds the responses.
* Some estimators allow the user to control the fitting behavior.
<p>
* For example, the \texttt{sklearn.linear\_model.LinearRegression} estimator allows the user to specify whether or not to fit an intercept term.
* This is done by setting the corresponding constructor arguments of the estimator object:
<p>
\begin{figure}
\centering
\includegraphics[width=1.1\linewidth]{sklcass/sklclass1a}
\end{figure}
<pre>
\begin{verbatim}
from sklearn.linear_model import LinearRegression
est = LinearRegression(fit_intercept=False)
\end{verbatim}
\end{framed}
%The docstring of the estimator shows you all available arguments – in IPython simply use LinearRegression? to view the docstring.
<p>
* During the fitting process, the state of the estimator is stored in instance attributes that have a trailing underscore ('\_').
* For example, the coefficients of a LinearRegression estimator are stored in the attribute \texttt{coef\_}:
<p>
<pre>
\begin{verbatim}
import numpy as np
# random training data
X = np.random.rand(10, 2)
y = np.random.randint(2, size=10)
est.fit(X, y)
est.coef_ # access coefficients
# Output : array([ 0.33176871, 0.34910639])
\end{verbatim}
\end{framed}
<p>
\textbf{Estimators}
* Estimators that can generate predictions provide a Estimator.predict method.
* In the case of regression, Estimator.predict will return the predicted regression values; it will return the corresponding class labels in the case of classification.
* Classifiers that can predict the probability of class membership have a method \texttt{Estimator.predict\_proba} that returns a two-dimensional numpy array of shape \texttt{(n\_samples, n\_classes)} where the classes are lexicographically ordered.
%<p>
%
%\textbf{Estimators: Transformers}
%
%* Finally, there is a special type of Estimator called Transformer which transforms the input data — e.g. selects a subset of the features or extracts new features based on the original ones.
%%* In addition to a fit method, a Transformer object provides the following methods:
%
%
%
%<p>
%
%
%<pre>
% \begin{verbatim}
%class Transformer(Estimator):
%
%def transform(self, X):
%"""Transforms the input data. """
%# transform ``X`` to ``X_prime``
%return X_prime
%\end{verbatim}
%\end{framed}
%
%<p>
%
%
%* Usually, a Transformer does not provide a predict method, but in some cases it may.
%* One transformer that we will use in this posting is \texttt{sklearn.preprocessing.StandardScaler}.
%* This transformer centers each predictor in X to have zero mean and unit variance:
%
%
%
<p>
%
%In [6]:
%from sklearn.preprocessing import StandardScaler
%scaler = StandardScaler(copy=True) # always copy input data (don't modify in-place)
%X_centered = scaler.fit(X).transform(X)
%scaler.mean_ # mean that will be subtracted upon transform
%Out[6]:
%array([ 0.48261456, 0.48636312])
%For more information on scikit-learn please consult the detailed user guide or walk through the excellent tutorial.
%
\huge
\[ \mbox{ Classification with Scikit-Learn} \]
<p>
\textbf{Understanding Classification}\\
Although regression and classification appear to be very different they are in fact similar problems.
* In regression our predictions for the response are real-valued numbers
* on the other hand, in classification the response is a mutually exclusive class label
* Example ``\textit{Is the email spam?}" or ``\textit{Is the credit card transaction fraudulent?}".
<p>
\textbf{Binary Classsification Problems}\\
* If the number of classes is equal to two, then we call it a binary classification problem; if there are more than two classes, then we call it a multiclass classification problem.
* In the following we will assume binary classification because it’s the more general case, and — we can always represent a multiclass problem as a sequence of binary classification problems.
<p>
\textbf{Credit Card Fraud}
* We can also think of classification as a function estimation problem where the function that we want to estimate separates the two classes.
* This is illustrated in the example below where our goal is to predict whether or not a credit card transaction is fraudulent
* he dataset is provided by James et al., \textbf{Introduction to Statistical Learning}.
<p>
\vspace{-1cm}
\textbf{Credit Card Fraud}
\begin{figure}
\centering
\includegraphics[width=1.2\linewidth]{sklcass/sklclass1}
\end{figure}
<p>
\textbf{Credit Card Fraud}
\begin{figure}
\centering
\includegraphics[width=0.7\linewidth]{sklcass/sklclass2}
\end{figure}
<p>
\textbf{Credit Card Fraud}
* On the left you can see a scatter plot where fraudulent cases are red dots and non-fraudulent cases are blue dots.
* A good separation seems to be a vertical line at around a balance of 1400 as indicated by the boxplots on the next slide.
<p>
\begin{figure}
\centering
\includegraphics[width=0.95\linewidth]{sklcass/sklclass3}
\end{figure}
%======================================================%
\begin{figure}
\centering
\includegraphics[width=0.9\linewidth]{sklcass/sklclass4}
\end{figure}
%======================================================%
\textbf{Simple Approach - Linear Regression}
* A simple approach to binary classification is to simply encode default as a numeric variable with 'Yes' == 1 and 'No' == -1; fit an Ordinary Least Squares regression model and use this model to predict the response as 'Yes' if the regressed value is higher than 0.0 and 'No' otherwise.
* The points for which the regression model predicts 0.0 lie on the so-called decision surface — since we are using a linear regression model, the decision surface is linear as well.
%======================================================%
%
%The example below illustrates this. Note that we use the \texttt{sklearn.linear\_model.LinearRegression} class in scikit-learn instead of the statsmodels.api.OLS class in statsmodels – they both implement the same procedure.
%
%======================================================%
\begin{figure}
\centering
\includegraphics[width=0.99\linewidth]{sklcass/sklclass6}
\end{figure}
%======================================================%
\begin{figure}
\centering
\includegraphics[width=0.99\linewidth]{sklcass/sklclass7}
\end{figure}
%======================================================%
* Points that lie on the left side of the decision boundary will be classified as negative;
* Points that lie on the right side, positive.
%The implementation of plot_surface can be found in the Appendix.
%======================================================%
\textbf{Confusion Matrix}
* We can assess the performance of the model by looking at the confusion matrix — a cross tabulation of the actual and the predicted class labels.
* The correct classifications are shown in the diagonal of the confusion matrix. The off-diagonal terms show you the \textbf{classification errors}.
* A condensed summary of the model performance is given by the \textbf{misclassification rate} determined simply by dividing the number of errors by the total number of cases.
%======================================================%
\textbf{Confusion Matrix}\begin{figure}
\centering
\includegraphics[width=0.95\linewidth]{sklcass/sklclass8}
\end{figure}
%======================================================%
\textbf{Confusion Matrix}
\begin{figure}
\centering
\includegraphics[width=0.7\linewidth]{sklcass/sklclass9}
\end{figure}
%======================================================%
\textbf{Cross Validation}
* In this example we are assessing the model performance on the same data that we used to fit the model.
* This might be a biased estimate of the models performance, for a classifier that simply memorizes the training data has zero training error but would be totally useless to make predictions.
* It is much better to assess the model performance on a separate dataset called the test data.
* Scikit-learn provides a number of ways to compute such held-out estimates of the model performance. * One way is to simply split the data into a \textbf{training set} and \textbf{testing set}.
%======================================================%
\begin{figure}
\centering
\includegraphics[width=0.99\linewidth]{sklcass/sklclass10}
\end{figure}
%======================================================%
\begin{figure}
\centering
\includegraphics[width=0.7\linewidth]{sklcass/sklclass11}
\end{figure}
%======================================================%
\textbf{Classification Techniques}
* Different classification techniques can often be compared using the type of decision surface they can learn. * The decision surfaces describe for what values of the predictors the model changes its predictions and it can take several different shapes: piece-wise constant, linear, quadratic, vornoi tessellation, \ldots
%======================================================%
This next part will introduce three popular classification techniques:
* [1] Logistic Regression,
* [2] Discriminant Analysis,
* [3] Nearest Neighbor.
We will investigate what their strengths and weaknesses are by looking at the decision boundaries they can model. In the following we will use three synthetic datasets that we adopted from this scikit-learn example.
%======================================================%
\textbf{Synthetic Data Sets}
\begin{figure}
\centering
\includegraphics[width=0.99\linewidth]{sklcass/sklclass12}
\end{figure}
%======================================================%
\textbf{Synthetic Data Sets}
* The task in each of the above examples is to separate the red from the blue points.
* Testing data points are plotted in lighter color.
* The left example contains two intertwined moon sickles; the middle example is a circle of blues framed by a ring of reds; and the right example shows two linearly separable gaussian blobs.
%======================================================%
\frametitle{Method 1: Logistic Regression}
\textbf{Logistic Regression}
* Logistic regression can be viewed as an extension of linear regression to classification problems. * One of the limitations of linear regression is that it cannot provide class probability estimates.
* This is often useful, for example, when we want to inspect manually the most fraudulent cases.
* Basically, we would like to constrain the predictions of the model to the range $[0,1]$ so that we can interpret them as probability estimates.
* In Logistic Regression, we use the logit function to clamp predictions from the range $[−infty,infty]$ to $[0,1]$.
%======================================================%
\frametitle{Method 1: Logistic Regression}
\textbf{Logistic Transformation}
\begin{figure}
\centering
\includegraphics[width=0.7\linewidth]{sklcass/sklclass13}
\end{figure}
%======================================================%
\frametitle{Method 1: Logistic Regression}
\textbf{Logistic Regression}
* Logistic regression is available in scikit-learn via the class \texttt{sklearn.linear\_model.LogisticRegression}.
%* It uses liblinear, so it can be used for problems involving millions of samples and hundred of thousands of predictors.
* Lets see how Logistic Regression does on our three toy datasets.
%======================================================%
\frametitle{Method 1: Logistic Regression}
<pre>
\begin{verbatim}
from sklearn.linear_model import LogisticRegression
est = LogisticRegression()
plot_datasets(est)
\end{verbatim}
\end{framed}
%======================================================%
\frametitle{Method 1: Logistic Regression}
\begin{figure}
\centering
\includegraphics[width=1.1\linewidth]{sklcass/sklclass21}
\end{figure}
%======================================================%
\frametitle{Method 1: Logistic Regression}
\textbf{Model Appraisal}
* As we can see, a linear decision boundary is not a poor approximation for the moon datasets, although we fail to separate the two tips of the sickles in the center.
* The cicles dataset, on the other hand, is not well suited for a linear decision boundary.
%======================================================%
\frametitle{Method 1: Logistic Regression}
\textbf{Model Appraisal}
* The error rate of 0.68 is in fact worse than random guessing. * For the linear dataset we picked in fact the correct model class — the error rate of 10\% is due to the noise component in our data.
* The gradient shows you the probability of class membership — white shows you that the model is very uncertain about its prediction.
%======================================================%
\frametitle{Method 2: Linear Discriminant Analysis}
\textbf{Linear Discriminant Analysis}
* Linear discriminant Analysis (LDA) is another popular technique which shares some similarities with Logistic Regression.
* LDA too finds linear boundary between the two classes where points on side are classified as one class and those on the other as classified as the other class.
%======================================================%
\frametitle{Method 2: Linear Discriminant Analysis}
<pre>
\begin{verbatim}
from sklearn.lda import LDA
est = LDA()
plot_datasets(est)
\end{verbatim}
\end{framed}
%%======================================================%
\frametitle{Method 2: Linear Discriminant Analysis}
\textbf{Model Appraisal}
\begin{figure}
\centering
\includegraphics[width=0.95\linewidth]{sklcass/sklclass15}
\end{figure}
(Remark - almost same as logistic regression)
%======================================================%
\frametitle{Method 2: Linear Discriminant Analysis}
\textbf{Linear Discriminant Analysis}
* The major difference between LDA and Logistic Regression is the way both techniques picks the linear decision boundary.
* Linear Discriminant Analysis models the decision boundary by making distributional assumptions about the data generating process
* Logistic Regression models the probability of a sample being member of a class given its feature values.
%======================================================%
\frametitle{Method 3: Nearest Neighbor}
\textbf{Nearest Neighbor}
* Nearest Neighbor uses the notion of similarity to assign class labels; it is based on the smoothness assumption that points which are nearby in input space should have similar outputs.
* It does this by specifying a similarity (or distance) metric, and at prediction time it simply searches for the k most similar among the training examples to a given test example.
%======================================================%
\frametitle{Method 3: Nearest Neighbor}
\textbf{Nearest Neighbor}
* The prediction is then either a majority vote of those k training examples or a vote weighted by similarity. * The parameter k specifies the smoothness of the decision surface.* The decision surface of a k-nearest neighbor classifier can be illustrated by the \textbf{Voronoi tesselation} of the training data, that show you the regions of constant respones.
%======================================================%
\frametitle{Method 3: Nearest Neighbor}
\begin{figure}
\centering
\includegraphics[width=1.1\linewidth]{sklcass/sklclass16}
\end{figure}
%======================================================%
\frametitle{Method 3: Nearest Neighbor}
\textbf{Nearest Neighbours}
* Yet Nearest Neighbor differs fundamentally from the above models in that it is a so-called non-parametric technique: the number of parameters of the model can grow infinitely as the size of the training data grows.
* Furthermore, it can model non-linear decision boundaries, something that is important for the first two datasets: moons and circles.
%======================================================%
\frametitle{Method 3: Nearest Neighbor}
<pre>
\begin{verbatim}
from sklearn.neighbors import KNeighborsClassifier
est = KNeighborsClassifier(n_neighbors=1)
plot_datasets(est)
\end{verbatim}
\end{framed}
%======================================================%
\frametitle{Method 3: Nearest Neighbor}
\begin{figure}
\centering
\includegraphics[width=1.1\linewidth]{sklcass/sklclass16}
\end{figure}
%======================================================%
\frametitle{Method 3: Nearest Neighbor}
* If we increase k we enforce the smoothness assumption.
* This can be seen by comparing the decision boundaries in the plots below where k=5 to those above where k=1.
{
<pre>
\begin{verbatim}
est = KNeighborsClassifier(n_neighbors=5)
plot_datasets(est)
\end{verbatim}
\end{framed}
}
%======================================================%
\frametitle{Method 3: Nearest Neighbor}
\begin{figure}
\centering
\includegraphics[width=1.1\linewidth]{sklcass/sklclass20}
\end{figure}
\end{document}