-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsklearn_tutorial.py
More file actions
1721 lines (1443 loc) · 56.2 KB
/
sklearn_tutorial.py
File metadata and controls
1721 lines (1443 loc) · 56.2 KB
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
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
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
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.7
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# # Scikit-Learn (sklearn)
#
# Scikit-learn is a Python library containing hundreds of methods for machine learning purposes.
# It is designed to interoperate with the Python numerical and scientific libraries NumPy and SciPy.
#
# It leverages NumPy and c-extensions for performance and provides many out-of-the-box tools for performing data mining tasks.
#
# It's a free and open source library and is used in many scientific publications.
#
# 
# + [markdown] slideshow={"slide_type": "slide"}
# # Machine Learning (Supervised)
#
# ## Mathematical Notation and Problem Description
#
# I'll try to follow some naming conventions along this notebook.
#
# * Uppercase letters such as $X$ or $Y$ denote generic aspects of a variable (i.e. the actual random variable)
# * Observed values are written in lowercase. The ith observed value of $X$ is written as $x_i$
# * Matrices are written in bold uppercase letters as in $\mathbf{X}$
# * Observations map as *rows* in the matrix while the observed variables are the *columns*.
#
# So if I measure two observables $p = 2$ the size and weight of $N = 100$ people, I get a $N \times p$ matrix $\mathbf{X}$.
# One observation in that matrix is denoted as $x_i = [ size, weight ]$ while all observations of the variable size are denoted by $\mathbf{x}_j$
#
# Heres one possible definition of supervised machine learning:
#
# > Given a $N \times p$ matrix $\mathbf{X}$ and some associated output vector $\mathbf{Y} \in \mathbb{R}^N$,
# find a function $f(X) = \hat{Y}$ that takes a vector $X \in \mathbb{R}^p$ and returns a prediction for $\hat{Y}$
# where some "loss function" $L(Y, f(X))$ is minimized for all $X$.
#
# We usually identify two types of **Supervised Learning**
# * **Classification** when the output can take a finite set of values (classes)
# * **Regression** when the output is continuous
#
# We now look at an example to see what that actually entails.
# + [markdown] slideshow={"slide_type": "subslide"}
# ## The Titanic Example. Learning from disaster.
#
# In the spring of 1912 the R.M.S. Titanic embarked on a journey to cross the Atlantic ocean. Unfortunately it hit an iceberg on the night of April 14th and sank shortly afterwards.
#
# The disaster caused widespread outrage over what was seen as lax safety regulations and reckles behavoiur by some. New maritime safety laws were put in place after the sinking that are still in place today.
#
# What can _we_ learn from the Titanic just by looking at its passenger data?
#
# Our data contains a list of name, gender, age and ticket price for each (known) passenger.
#
# 
# + slideshow={"slide_type": "skip"}
# %matplotlib inline
from ml import plots
from ml import learning
from importlib import reload
reload(learning)
reload(plots)
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
def set_rc_params():
plt.rcParams['figure.figsize'] = (12, 8)
plt.rcParams['font.size'] = 14
plt.rcParams['lines.linewidth'] = 2
plt.rcParams['xtick.labelsize'] = 13
plt.rcParams['ytick.labelsize'] = 13
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['axes.titlesize'] = 14
plt.rcParams['legend.fontsize'] = 13
def set_sns():
sns.set(context='notebook')
set_rc_params()
def set_mpl():
sns.reset_orig()
set_rc_params()
set_sns()
pd.options.display.max_rows = 10
def read_titanic():
data = pd.read_csv('resources/titanic_train.csv', index_col='PassengerId').dropna(subset=['Age'])
data['Survived_Code'] = data.Survived
data['Pclass_Code'] = data.Pclass
data.Survived = pd.Categorical.from_codes(data.Survived, categories=['no', 'yes'])
data.Pclass = pd.Categorical.from_codes(data.Pclass - 1, categories=['1st', '2nd', '3rd'])
data.Sex = pd.Categorical(data.Sex)
data['Sex_Code'] = data.Sex.cat.codes
return data
data = read_titanic()
data
# + slideshow={"slide_type": "subslide"}
data.Survived.value_counts().plot.pie(autopct='%.2f %%')
plt.gca().set_aspect('equal')
# -
# __The task:__
#
# Given a vector $X = (Name, Class, Age, Sex)$ can we find a function $f_{survival}(x) \in \{{yes, no}\}$ that accurately predicts the survival of the passengers in most cases?
#
# How do we know if that function $f_{survival}(x)$ is any good?
# + [markdown] slideshow={"slide_type": "subslide"}
# ## Performance metrics
#
# To get some sense of the quality of this predictor we gather the following numbers.
#
# * __True Positives__ $TP$, The number of correctly predicted events that belong to the 'positive' class
# * __False Positives__ $FP$, The number of events falsely predicted as positive that actually belong to the 'negative' class
# * __True Negatives__ $TN$, The number of correctly predicted events that belong to the 'negative' class
# * __False Negatives__ $FN$, The number of events falsely predicted as negative that actually belong to the 'positive' class
#
#
# We can look at the fraction of correctly labeled observations in the data
#
# $$
# accuracy(\mathbf{y}, \mathbf{\hat{y}}) = \frac{1}{N} \sum_{i = 1}^N \mathbb{1}(y_i = \hat{y}_i)
# $$
#
# or simply put
#
# $$
# accuracy(\mathbf{y}, \mathbf{\hat{y}}) = \frac{TP + TN}{ TP + FP + FN + TN} = \frac{\text{correclty predicted}}{\text{total number of observations}}.
# $$
#
# In some cases, also **Precision** and **Recall** can be useful:
#
# $$
# precision=\frac{TP}{TP+FP}
# $$
#
# $$
# recall=\frac{TP}{TP+FN}
# $$
#
# Now we try to find a function where the accuracy is higher than 0.5
#
#
# __One possible solution__:
#
# Let's presume rich people get to go into lifeboats.
#
# ```
# def f_class(passenger):
# if passenger.Pclass == 1:
# return 'yes'
# else:
# return 'no'
# ```
# + slideshow={"slide_type": "-"}
def f_class(passenger_class):
return 'yes' if passenger_class == '1st' else 'no'
data = read_titanic()
prediction = data['Pclass'].apply(f_class)
truth = data['Survived']
plots.plot_bars_and_confusion(truth=truth, prediction=prediction)
# -
# What about the women? Maybe we get a better predictor.
#
# ```
# def f_survival(passenger):
# if passenger.Sex == 'female':
# return 'yes'
# else:
# return 'no'
# ```
# +
def f_sex(passenger_sex):
return 'yes' if passenger_sex == 'female' else 'no'
data = read_titanic()
truth = data['Survived']
prediction = data['Sex'].apply(f_sex)
# + slideshow={"slide_type": "subslide"}
plots.plot_bars_and_confusion(truth=truth, prediction=prediction)
# -
# But wouldn't accuracy be enough? Why do we need to compute the confusion matrix?
#
# In some cases a model may have a high accuracy but still present a bad performance. Let's see an example
# +
np.random.seed(0)
from sklearn.datasets import make_blobs
sample_size = 1000
ratio = 0.99
X, y = make_blobs(n_samples=[int(ratio*sample_size), int((1 - ratio)*sample_size)],
n_features=2, centers=[[0, 0], [-1, -1]], cluster_std=[1, 0.2])
df_anomaly = pd.DataFrame(X, columns=['x', 'y'])
df_anomaly['f_val'] = y
df_anomaly['f_code'] = 'no'
mask_no = y == 0
df_anomaly.loc[~mask_no, 'f_code'] = 'yes'
plt.scatter(df_anomaly[mask_no].x, df_anomaly[mask_no].y, c='b', zorder=0)
plt.scatter(df_anomaly[~mask_no].x, df_anomaly[~mask_no].y, c='red', s=50, zorder=10)
# -
# Imagine the points in red correspond to anomalies in a certain process and we want to build a model to detect them.
#
# Let's try.
# +
def is_anomaly(r):
return 'yes' if r.x > 2 else 'no'
prediction = df_anomaly.apply(is_anomaly, axis=1)
truth = df_anomaly.f_code
# -
plots.plot_bars_and_confusion(truth=truth, prediction=prediction)
# Looks like it works pretty well, but it doesn't.
pred_mask_no = prediction == 'no'
plt.scatter(df_anomaly[mask_no & pred_mask_no].x, df_anomaly[mask_no & pred_mask_no].y, c='b', zorder=0)
plt.scatter(df_anomaly[~pred_mask_no].x, df_anomaly[~pred_mask_no].y,
c='red', s=50, zorder=10, label='Predicted yes')
plt.scatter(df_anomaly[~mask_no].x, df_anomaly[~mask_no].y, c='limegreen',
s=50, zorder=10, label='Truth yes')
plt.legend()
# If we look closer, the number of True Positives is 0, so Precission and Recall will both be 0.
#
# __We need to take Precission and Recall into account__ specially with unbalanced datasets.
# Maybe we can do better by using some combination of variables for our prediction. But how do you find a good combination of variables?
#
# We could use visualizations to see correlations or obvious structures in the data.
#
# We could also try yo learn more about what happened on the Titanic.
#
# Perhaps even by watching that movie where Leonardo Di Caprio drowns in the end.
#
# 
# + [markdown] slideshow={"slide_type": "subslide"}
# ## Linear Models
#
#
# ### Linear regression
#
# Can we improve our predictor by combining more variables into one predictor?
#
# Lets presume a linear weighted combination of variables:
#
# $$
# f(X)= \hat{\beta}_0 + \sum_{j=1}^p X_j \hat{\beta}_j
# $$
#
# or in our case when combining sex and money:
#
# $$
# f(X)= \hat{\beta}_0 + X_{Class} \hat{\beta}_{Class} + X_{Sex} \hat{\beta}_{Sex}
# $$
#
# How do you find those weights?
#
# Choose and then optimize a loss function. In this case the popular residual sum of squares
#
# $$L(\beta) = RSS(\mathbf{\beta}) = \sum_{i=1}^N (Y_i - X_i^T \beta)^2 $$
#
# Rewrite the problem in matrix form:
#
# \begin{align}
# X^T &= (1, Class, Sex) \\
# \mathbf{\hat{\beta}}^T &= (\hat{\beta}_0, \hat{\beta}_{Class}, \hat{\beta}_{Sex}) \\
# \mathbf{y} &= {Y_1, \ldots, Y_N}
# \end{align}
#
# Makes the formulation more compact for the predictor
#
# $$
# \hat{\mathbf{y}} = X^T \hat{\beta}
# $$
#
# and the loss function
#
# $$
# RSS(\beta) = (\mathbf{y} - \mathbf{X} \beta)^T (\mathbf{y} - \mathbf{X} \beta )
# $$
#
# Now we optimize the loss function just like we would any other function, by setting the derivative equals to zero.
#
# $$
# {RSS}^\prime(\beta) = \mathbf{X}^T (\mathbf{y} - \mathbf{X} \beta ) \stackrel{!}{=} 0
# $$
#
# Solving for $\beta$ leads to
#
# $$
# \hat{\beta} = (\mathbf{X}^T \mathbf{X})^{-1} \mathbf{X}^T \mathbf{y}
# $$
#
#
# We just performed __Linear Least Squares__ regression.
#
# Now we can define a function to predict passenger survival according to
#
# $$
# \hat{Y} = \begin{cases}
# \text{Yes}, & \text{if $ f(X) \gt 0.5$} \\
# \text{No}, & \text{if $ f(X) \le 0.5$}
# \end{cases}
# $$
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# We just *learned* the parameters for a statistical model based on labeled data.
#
# Can a linear classification improve the classification of the Titanic dataset case?
#
# We have to evaluate our 'learned' model independent test set
#
# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5)
# + slideshow={"slide_type": "fragment"}
from sklearn import linear_model
from sklearn.model_selection import train_test_split
X = data[['Sex_Code', 'Pclass_Code', 'Fare', 'Age']]
y = data['Survived_Code']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.6)
reg = linear_model.LinearRegression()
reg.fit(X_train, y_train)
print('''intercept = {}
coefs = {}'''.format(reg.intercept_, reg.coef_))
y_prediction = reg.predict(X_test)
y_prediction = np.where(y_prediction > 0.5, 1, 0)
plots.plot_bars_and_confusion(truth=y_test, prediction=y_prediction)
# -
# We see that the coefficients for the __Fare__ and __Age__ are very small.
#
# * Are these fields necessary?
# * How do they correlate to the target?
# * And with other fields?
# * Can we just ignore them?
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(10., 10.))
plots.plot_bins_perc(data, 'Sex_Code', 'Survived_Code', var_type='discrete', ax=ax1)
plots.plot_bins_perc(data, 'Pclass_Code', 'Survived_Code', var_type='discrete', ax=ax2)
plots.plot_bins_perc(data, 'Fare', 'Survived_Code', var_type='continuous', ax=ax3)
plots.plot_bins_perc(data, 'Age', 'Survived_Code', var_type='continuous', ax=ax4)
plt.tight_layout()
# ## Regularization
#
# Add a penalty on the size of the coefficients. This is done to make the model more robust to colinearity and less prone to overfitting.
#
# ### Ridge
#
# Linear regression with L2 regularization
#
# $$
# L(\alpha) = ||y - Xw||^2_2 + \alpha * ||w||^2_2
# $$
#
# where
#
# $$
# ||w||_2 = \sqrt{\sum_{i=1}^N w_i^2}
# $$
#
# ### Lasso
#
# Linear regression with L1 regularization
#
# $$
# L(\alpha) = \frac{||y - Xw||^2_2}{2*n} + \alpha * ||w||_1
# $$
#
# where
#
# $$||w||_1 = \sum_{i=1}^N |w_i|$$
#
# We will have to decide which value of $\alpha$ to use. How?
# +
from sklearn import linear_model
from sklearn.model_selection import train_test_split
X = data[['Sex_Code', 'Pclass_Code', 'Fare', 'Age']]
y = data['Survived_Code']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.6)
alpha_range = np.power(10., np.arange(-4, 5))
lasso_v = []
ridge_v = []
for alpha in alpha_range:
# Lasso
reg = linear_model.Lasso(alpha=alpha)
reg.fit(X_train, y_train)
y_prediction = reg.predict(X_test)
y_prediction = np.where(y_prediction > 0.5, 1, 0)
lasso_v.append([(y_prediction == y_test).sum()/len(y_prediction),
np.linalg.norm(reg.coef_), np.isclose(reg.coef_, 0.).sum()])
# Ridge
reg = linear_model.Ridge(alpha=alpha)
reg.fit(X_train, y_train)
y_prediction = reg.predict(X_test)
y_prediction = np.where(y_prediction > 0.5, 1, 0)
ridge_v.append([(y_prediction == y_test).sum()/len(y_prediction),
np.linalg.norm(reg.coef_), np.isclose(reg.coef_, 0.).sum()])
lasso_v = np.array(lasso_v)
ridge_v = np.array(ridge_v)
# Linear Regression
reg = linear_model.LinearRegression()
reg.fit(X_train, y_train)
y_prediction = reg.predict(X_test)
y_prediction = np.where(y_prediction > 0.5, 1, 0)
acc = (y_prediction == y_test).sum()/len(y_prediction)
w = np.linalg.norm(reg.coef_)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 8))
ax1.plot(alpha_range, lasso_v[:, 0], 'r', label='Lasso')
ax1.plot(alpha_range, ridge_v[:, 0], 'g', label='Ridge')
ax1.axhline(acc, color='b', label='Linear Regression')
ax1.set_xscale('log')
ax1.set_title('Accuracy Lasso vs Ridge vs Linear Regression')
ax1.set_xlabel(r'$\alpha$')
ax1.set_ylabel('Accuracy')
ax1.legend(loc='center right')
ax2.plot(alpha_range, lasso_v[:, 1], 'r', label='Lasso')
ax2.plot(alpha_range, ridge_v[:, 1], 'g', label='Ridge')
ax2.axhline(w, color='b', label='Linear Regression')
ax2.set_xscale('log')
ax2.set_title('Weights Lasso vs Ridge vs Linear Regression')
ax2.set_xlabel(r'$\alpha$')
ax2.set_ylabel('L2 norm of the weights')
ax3 = ax2.twinx()
ax3.plot(alpha_range, lasso_v[:, 2], 'or', label='Lasso')
ax3.plot(alpha_range, ridge_v[:, 2], 'og', label='Ridge')
ax3.set_ylabel('Count weights == 0')
ax2.legend(loc='center right')
# -
# ## Feature scaling
#
# **Definition** Standardize the range of values that the features can take.
#
# **Motivation** Having variables with very different value ranges may cause the algorithm to give wrong results. Specially those relying on Euclidian distance (e.g. kNN). Also results can be less explanatory at first sight.
#
# **Types**
# * Standardization
# $$
# x' = \frac{x - \bar{x}}{\sigma}
# $$
#
# * Rescaling
# $$
# x' = \frac{x - min(x)}{max(x) - min(x)}
# $$
set_sns()
# + [markdown] slideshow={"slide_type": "slide"}
#
# ## Support Vector Machines (SVMs)
#
# The basic assumption underlying the least squares approach is that the model is linear in the observed variables.
# This works for data which can be separated by a linear function (a hyperplane in the parameter space).
#
# But how do we know that this method finds the 'best' hyperplane for separating the two classes?
#
# And what if the data cannot be seperated by a plane?
#
# + slideshow={"slide_type": "subslide"}
# many possible lines to separate the data. Which one is 'better'?
from sklearn.datasets import make_blobs
X, y = make_blobs(n_samples=150, centers=2,
random_state=3, cluster_std=0.70)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='winter')
xs = np.linspace(-6.5, 3, 2)
plt.plot(xs, -2 * xs - 2, color='gray', linestyle='--')
plt.plot(xs, -0.4 * xs + 2, color='gray', linestyle='--')
plt.xlim([-6, 3])
plt.ylim([-2, 6])
plt.axis('off')
None
# -
# Again we minimze a loss function.
#
# $$
# L(\beta) = C \max(0, 1 - y_i \beta^T x_i) + \frac{\lambda}{2}||{\beta}||^2
# $$
#
# Support Vector Machines try to find the hyperplane which maximimizes the margin to the points in different classes in the parameter space.
#
# $C$ and $\lambda$ are two parameters which can be chosen beforehand.
#
# <p style="color:gray"> Note that, to fit the definition above, the label encoding has to be $y_i \in {-1, 1}$</p>
# + slideshow={"slide_type": "subslide"}
from sklearn.svm import SVC
from sklearn.datasets import make_blobs
X, y = make_blobs(n_samples=150, centers=2,
random_state=3, cluster_std=0.70)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='winter')
clf = SVC(kernel='linear')
clf.fit(X, y)
plots.draw_svm_decission_function(clf, colors='black', label='SVM')
reg = linear_model.LinearRegression()
reg.fit(X, y)
plots.draw_linear_regression_function(reg, label='Linear Regression', color='gray', alpha=0.5)
plt.xlim([-6, 3])
plt.ylim([-2, 6])
plt.legend(loc='lower right', frameon=True, framealpha=0.95, facecolor='white')
None
# + [markdown] slideshow={"slide_type": "subslide"}
# So far the data has still been separable by a linear function.
#
# For many problems in real life however this isn't the case.
#
# Heres an example of (artificial) data which cannot be seperated by a line.
# + slideshow={"slide_type": "subslide"}
from sklearn.datasets import make_moons
X, y = make_moons(n_samples=200, noise=0.10)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='winter')
clf = SVC(kernel='linear')
clf.fit(X, y)
plots.draw_svm_decission_function(clf, colors='black')
# -
# Now what if we take that data and transform it into a new variable.
#
# Find a function $h$ to create a new variable $X_h = h(X_1, X_2, \ldots)$.
#
# In the case above some radial symmetry seems be an underlying feature of the data.
#
# We can exploit that
# + slideshow={"slide_type": "subslide"}
from mpl_toolkits import mplot3d
set_mpl()
# add a dimension by applying a transformation on the two variables in the data.
r = np.exp(-(X[:, 0] ** 2 + X[:, 1] ** 2))
fig = plt.figure(figsize=(16, 6))
ax = fig.add_subplot(1, 2, 1, projection='3d')
ax.scatter3D(X[:, 0], X[:, 1], r, c=y, s=50, cmap='winter')
ax.view_init(elev=45, azim=45)
ax.set_xlabel('X1')
ax.set_ylabel('X2')
ax.set_zlabel('r')
ax = fig.add_subplot(1, 2, 2, projection='3d')
ax.scatter3D(X[:, 0], X[:, 1], r, c=y, s=50, cmap='winter')
ax.view_init(elev=5, azim=70)
ax.set_xlabel('X1')
ax.set_ylabel('X2')
ax.set_zlabel('r')
# + slideshow={"slide_type": "skip"}
set_sns()
# + slideshow={"slide_type": "subslide"}
X, y = make_moons(n_samples=200, noise=0.10)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='winter')
clf = SVC(kernel='rbf', C=1) #use the radial basis function instead of the linear one.
clf.fit(X, y)
plots.draw_svm_decission_function(clf, colors='black', label='SVM')
# + slideshow={"slide_type": "subslide"}
gamma = 1
def compute_rbf(X, X0=None, gamma=1):
'''This method computes the RBF based on X'''
if X0 is None:
X0 = X
X_norm = np.sum(X ** 2, axis = -1)
X0_norm = np.sum(X0**2, axis = -1)
K = np.exp(-gamma * (X_norm[:,None] + X0_norm[None,:] - 2 * np.dot(X, X0.T)))
return K
# Generate the random data and plot it
X, y = make_moons(n_samples=200, noise=0.10)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='winter')
# Add additional features using RBF
K = compute_rbf(X, gamma=gamma)
XK = np.hstack([X, K])
# Train SVM model using a linear kernel
clf = SVC(kernel='linear', C=1)
clf.fit(XK, y)
# Plot the decision boundary
ax = plt.gca()
x_low, x_high = ax.get_xlim()
y_low, y_high = ax.get_ylim()
x1 = np.linspace(x_low, x_high, 40)
x2 = np.linspace(y_low, y_high, 40)
X1, X2 = np.meshgrid(x1, x2)
xy = np.vstack([X1.ravel(), X2.ravel()]).T
k = compute_rbf(xy, X0=X, gamma=gamma)
xyz = np.hstack([xy, k])
Z = clf.decision_function(xyz).reshape(X1.shape)
cs = ax.contour(X1, X2, Z, levels=[-1., 0, 1.0], linestyles=['--', '-', '--'], colors='k')
cs.collections[0].set_label('SVM Decission Boundary')
plt.axis('off');
# + [markdown] slideshow={"slide_type": "subslide"}
# The same approach works for other linear methods as well.
#
# What makes SVM's so special?:
#
# # + SVM's have proven to perform very well for many use-cases.
# # + SVM's handle large number of dimensions relativly fast.
# # + The kernel functions basically come for free.
# # + Easily extendable to multi-class problems.
#
# Kernel functions are constrained to fulfill certain criteria. *(See Chapter 12.3.1 in the Hastie Book)*
# + [markdown] slideshow={"slide_type": "slide"}
# ## Local Optimization and Decission Trees
#
# So far we looked at loss functions which optimized some global optimization criterion.
#
# In cases of non-linearity some a priori knowledge is necessary to transform the data to make it seperable by a hyperplane. (or you can use *Deep Learning*)
#
#
# Idea:
# * Split the parameter space into many subspaces where observations of the same class live.
#
# Problem:
# * Finding the *best* set of subspaces in the parameter space is an NP-complete problem (Its hard to solve. Really hard.)
#
# One can however try approximate the solution using binary recursive splits in the parameter space.
# +
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
from sklearn.datasets import make_moons
np.random.seed(1234)
X, y = make_moons(n_samples=1000, noise=0.30)
# -
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='winter')
clf = DecisionTreeClassifier(max_depth=5, criterion='entropy')
clf.fit(X, y)
# + slideshow={"slide_type": "subslide"}
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='winter')
plots.draw_decission_boundaries(clf)
# -
# Outline for a tree building algorithm.
#
# def build_tree(space)
# if stopping_criterion_fulfilled():
# return {}
#
# variable, split_point = find_best_split(space)
#
# left, right = split_space(space, variable, split_point)
#
# left_tree = build_tree(left)
# right_tree = build_tree(right)
#
# return {'node' : (variable, split_point), 'left': left_tree, 'right': right_tree}
#
tree.plot_tree(clf, max_depth=2, filled=True);
# For classification the best split in a node $m$ of the tree is found by minimizing an impurity measure $Q_m$.
#
# Popular ones include Information Gain, Cross-Entropy or the Gini index.
#
# They all work by looking at one variable at a time and then iterating over all the possible splits to find the minimal $Q_m$
#
# Implementations across languages/libraries are similar but differ in their choice of $Q_m$ and handling of continous variables.
# ### Apply Decision Trees to the Titanic example
#
# Use scikit-learn to find the best possible decission tree for the Titanic dataset.
#
# We will set different maximum depths.
#
# What's happening?
# +
from sklearn.model_selection import ParameterGrid, train_test_split
from sklearn.metrics import accuracy_score
from sklearn.tree import DecisionTreeClassifier
import seaborn as sns
import pandas as pd
import numpy as np
np.random.seed(1235)
data = read_titanic()
X = data[['Sex_Code', 'Pclass_Code', 'Fare', 'Age']]
y = data['Survived']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5)
records = []
ps = ParameterGrid({'max_depth':range(1, 20), 'criterion':['entropy', 'gini']})
for d in ps:
clf = DecisionTreeClassifier(max_depth=d['max_depth'], criterion=d['criterion'])
clf.fit(X_train, y_train)
acc = accuracy_score(y_test, clf.predict(X_test))
records.append({'max_depth': d['max_depth'],
'criterion': d['criterion'],
'accuracy': acc})
df = pd.DataFrame.from_records(records)
pivot_df = df.pivot(index='max_depth', columns='criterion', values='accuracy')
sns.heatmap(pivot_df, cmap='YlOrRd', annot=True, fmt='.3f')
# -
# ### Overfitting (Bias-Variance Tradeoff)
#
# Assume the target $y$ is generated by some function $f(x)$ with added gaussian noise $\epsilon$
#
# $$
# y = f(x) + \epsilon, \qquad \epsilon \propto \mathcal{N}(\mu=0, \sigma)
# $$
#
# The mean squared error ($mse$) of the predictor function $\hat{f}(x) = \hat{y}$ is
#
# $$
# mse(y, \hat{f}) = (y - \hat{f}(x))^2
# $$
#
# Calculate the expectation value $mse$
#
# $$
# E[mse(y, \hat{f}) ] = E[(y - \hat{f}(x))^2]
# $$
# Some mathematical definitions up front.
#
# __Variance__ of a random variable $X$
#
# $$
# Var(X) = E[(X - E[X])^2] = E[X^2] - E[X]^2 \iff E[X^2] = Var[X] + E[X]^2
# $$
#
# __Bias__ of an estimator $\hat{f}$
#
# $$
# Bias(\hat{f}) = E[\hat{f} - f] = E[\hat{f}] - E[f] = E[\hat{f}] - f
# $$
# Since $f$ is a fixed function
#
# $$
# E[f] = f
# $$
#
# Using these definition on $y$ gives
#
# \begin{align}
# Var[y] = Var[ f(x) + \epsilon] & = Var[f(x)] + Var[\epsilon] \\
# & = Var[f(x)] + \sigma^2 \\
# & = E[f(x)^2] - E[f(x)]^2 + \sigma^2 \\
# & = f(x)^2 - f(x)^2 + \sigma^2 \\
# & = \sigma^2
# \end{align}
#
# Finally calculating $E[mse(y, \hat{f})]$ yields
#
# \begin{align}
# E[(y - \hat{f}(x))^2] & = E[y^2 + \hat{f}^2 - 2y\hat{f}] \\
# & \ldots \\
# & = \sigma^2 + Var[\hat{f}] + Bias[\hat{f}]^2.
# \end{align}
# This so called Bias-Variance dillemma is a universal problem in supervised machine learning.
#
# There are two error sources:
#
# * High bias might decrease overall predictor performance.
# * High variance can make the learned parameters prone to noise in the training data.
#
# If the parameters are tuned to the noise in the training data, the model will not generalize to new data.
#
# This problem is called __overfitting__
#
# <table>
# <tr>
# <td><img src='./ml/images/bias_variance_1.jpeg'/></td>
# <td><img src='./ml/images/bias_variance_2.png'/></td>
# </tr>
# </table>
# Lets see a very good example, stolen from: https://gist.github.com/geopapa11
#
# Full explanation here: https://towardsdatascience.com/the-bias-variance-tradeoff-8818f41e39e9
from importlib import reload
import ml.bias_variance as bv
reload(bv)
# Assume we have a sample $x$, $y$ with an underlying relation
#
# $$f(x) = \frac{1}{2}x + \sqrt{\max{(x, 0)}} - \cos{x} + 2$$
#
# and some noise following a Gaussian distribution
#
# $$y = f(x) + \epsilon$$
#
# where $\epsilon \sim \mathcal{N}(0, 1)$
#
# Our dataset consists of 1000 points, we will assume this is the whole population.
bv.plot_sample()
# We want to model this relation with a polynomial function:
#
# $$ \hat{f}(x) = w_{0} + w_1x^1 + w_2x^2 .. w_dx^d $$
#
# We will try to fit functions of different degrees, but our training dataset consists of only 20 points. Imagine we do this experiment many times.
bv.plot_experiments()
# We see that the low degree function $d=1$ is more stable (low variance) but doesn't fit well to the data (high bias).
#
# On the other hand, the high degree polynomio $d=5$ fits better to the data (low bias), but it changes a lot when we change the training dataset (high variance).
#
# If we do this experiment 1000 times, and we get the prediction on $x_{test} = 3.2$ for each of the models, we will get a notion of the bias and variance introduced.
bv.plot_test_hists(2)
# We do the same exercise but instead of using one single test point, we use a set of 1000 test points and we compute the squared bias and the variance among all experiment on each test point and we average them.
bv.plot_bias_variance_tradeoff(R=1000, n_test=1000, d_arr=[0, 1, 2, 3, 4])
# ## Ensemble Methods
#
# We have used a decission tree to classifiy artificial data as well as the Titanic data.
#
# Theoretically a decission tree is not limited in its depth.
#
# This quickly leads to overfitted tree models.
#
# +
np.random.seed(1)
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import make_moons
X, y = make_moons(n_samples=5000, noise=0.30)
clf = DecisionTreeClassifier(max_depth=300, criterion='entropy')
clf.fit(X, y)
plt.scatter(X[:, 0], X[:, 1], c=y, s=3, cmap='winter')
plots.draw_decission_boundaries(clf)
# -
# As mentioned in the discussion about decission trees earlier, the tree building algorithms try to find the optimal split criterion in some local region of the parameter space.
#
# Finding the best overal split in parameter space is computationaly infeasible.
#
# This means the decission tree algorithm can run into a local optimum.
#
# The idea of _ensemble learning_ is to train several weak (high bias, low variance) base classifiers on different subsets of the data and then combine them into one big classifier.
# #### Bagging
#
# A popular way to build ensembles is called *bagging*.
#
# Split the training data into $B$ subsets using sampling with replacement (Bootstrapping). For each subset $b$ we train a classifier $\hat{f}_b$. Bagging then combines the overall prediction by taking the average.
#
# $$
# \hat{y} = \hat{f}_{\text{bag}}(x) = \frac{1}{B} \sum_{b=1}^B \hat{f}_b (x)
# $$
# #### Random Forests
#
# Random Forests are a modification to bagging in which a number of *randomized decission trees* are trained. These randomized decission trees use a random subset of variables to find the best split in each node.
#
# def build_random_tree(space)
# if stopping_criterion_fulfilled():
# return {}
#
# random_variable_choice = choose_random_selection_of_variables()
# variable, split_point = find_best_split(space, random_variable_choice)
#
# left, right = split_space(space, variable, split_point)
#
# left_tree = build_tree(left)
# right_tree = build_tree(right)
#
# return {'node' : (variable, split_point), 'left': left_tree, 'right': right_tree}
#
# Random Forests are a very popular choice for classification tasks since their parameters can be easily tuned and they often outperform other methods.
# +
np.random.seed(2)
from sklearn.metrics import roc_curve, roc_auc_score, make_scorer
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
data = read_titanic()
X = data[['Sex_Code', 'Pclass_Code', 'Fare', 'Age']]
y = data['Survived_Code']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5)
# +
rf = RandomForestClassifier(n_estimators=20, max_depth=5)
rf.fit(X_train, y_train)
plots.plot_bars_and_confusion(truth=y_test, prediction=rf.predict(X_test))
# +
records = []
ps = ParameterGrid({'max_depth':range(1, 20), 'criterion':['entropy', 'gini']})