-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnalysisWorkFlowModel.py.html
2331 lines (1703 loc) · 82.2 KB
/
AnalysisWorkFlowModel.py.html
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
# # Data science analysis: ttH(bb) dilepton channel
#
# **Notebook by Christian Contreras-Campana, PhD**
# ## Introduction
#
# Developing a data analytic report scheme for ttH(bb) multivariate analysis study using machine larning technologies.
#
# The columns in the file are:
# - mass_tag_tag_min_deltaR: Mass for b-tag jet pair with minimum $\Delta$R
# - median_mass_jet_jet: Median invariant mass of all combinations of jet pairs
# - maxDeltaEta_tag_tag: The $\Delta\eta$ between the two furthest b-tagged jets
# - mass_higgsLikeDijet: The invariant mass of a jet pair ordered in closeness to a Higgs mass
# - HT_tags: Scalar sum of transverse momentum for all jets
# - btagDiscriminatorAverage_tagged: Average CSV b-tag discriminant value for b-tagged jets
# - mass_jet_tag_min_deltaR: Invariant mass of jet pair (with at least one b-tagged) $\Delta$R
# - mass_jet_jet_min_deltaR: Invariant mass of jet pair $\Delta$R
# - mass_tag_tag_max_mass: Mass for b-tagged jet pair with maximum invariant mass combination
# - centrality_jets_leps: The ratio of the sum of the transverse momentum of all jets and leptons
# - maxDeltaEta_jet_jet: Invariant mass of jet pair $\Delta$R
# - centrality_tags: The ratio of the sum of the transverse momentum of all b-tagged jets
#
# While we have some grasp on the matter, we're not experts, so the following might contain inaccuracies or even outright errors. Feel free to point them out, either in the comments or privately.
# ## Load Libraries
#
# We load all the necessary python libraries that will permit us to load the data files, pre-process and clean the data, perform data validation, produce statistical summaries, conduct exploratory data analysis, as well as feature transformation, feature ranking, and feature selection. Python libraries will also be needed for model selection, evaluating overfitting, executing standard nested k-fold cross validation for hyper-parameter optimization and model evaluation.
# In[1]:
## Import common python libraries
import sys
import time
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import random
# Import from root_numpy library
import root_numpy
from root_numpy import root2array, rec2array
# Import panda library
from pandas.tools import plotting
from pandas.tools.plotting import scatter_matrix
from pandas.core.index import Index
import pandas.core.common as com
# Import scipy
import scipy
from scipy.stats import ks_2samp
import scipy as sp
# Import itertools
import itertools
from itertools import cycle
# Import Jupyter
from IPython.core.interactiveshell import InteractiveShell
# Import scikit-learn
import sklearn
from sklearn.feature_selection import VarianceThreshold
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
from sklearn.feature_selection import RFE
from sklearn.feature_selection import SelectFromModel
from sklearn.model_selection import ParameterGrid
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import KFold, StratifiedKFold, ShuffleSplit
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import learning_curve
from sklearn.svm import SVC, LinearSVC
from sklearn.naive_bayes import GaussianNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier, VotingClassifier
from sklearn.ensemble import GradientBoostingClassifier, AdaBoostClassifier, BaggingClassifier
from sklearn.linear_model import SGDClassifier
from sklearn.linear_model import RandomizedLasso
from sklearn.preprocessing import StandardScaler, RobustScaler, MinMaxScaler
from sklearn.feature_selection import SelectPercentile, f_classif
from sklearn.feature_selection import RFECV
from sklearn.calibration import calibration_curve, CalibratedClassifierCV
from sklearn.pipeline import make_pipeline, Pipeline
from sklearn.metrics import (confusion_matrix, roc_auc_score, roc_curve,
auc, average_precision_score, precision_score,
brier_score_loss, recall_score, f1_score, log_loss,
classification_report, precision_recall_curve)
from sklearn.dummy import DummyClassifier
from sklearn.externals import joblib
from sklearn import feature_selection
# Import imblearn
import imblearn
from imblearn.over_sampling import ADASYN, SMOTE, RandomOverSampler
from imblearn.under_sampling import RandomUnderSampler
from collections import defaultdict, Counter
import re
# Check the versions of libraries/packages
print("Python version " + sys.version)
print("Sklearn version " + sklearn.__version__)
print("Root_numpy version " + root_numpy.__version__)
print("Numpy version " + np.__version__)
print("Scipy version " + scipy.__version__)
print("Pandas version " + pd.__version__)
print("Matplotlib version " + matplotlib.__version__)
print("Seaborn version " + sns.__version__)
print("Imblance version " +imblearn.__version__)
# Fix random seed for reproducibility
seed = 7
np.random.seed(seed)
# Specifying which nodes should be run interactively
InteractiveShell.ast_node_interactivity = "all"
print(__doc__)
# ## Load Data Files
#
# Most data files contain approximately 15K events. There are a total of 4 files totaling 80K data events. We list the features and response names. We store the data in a Pandas DataFrame for greater ease of data manipulation.
#
# **Note: To reduce running time of the program we use our most signal-like category which is statistically limited**
# In[2]:
## Define data load function
def load(sig_filename, bkg_filename, category, features):
"""Multi class version of Logarithmic Loss metric.
https://www.kaggle.com/wiki/MultiClassLogLoss
Parameters
----------
sig_filename : array, shape = [n_samples]
true class, intergers in [0, n_classes - 1)
bkg_filename : array, shape = [n_samples, n_classes]
category: string
features: array, shape = [n_features]
Returns
-------
data : pandas.DataFrame
"""
signal = root2array(sig_filename, category, features)
signal = rec2array(signal)
backgr = root2array(bkg_filename, category, features)
backgr = rec2array(backgr)
# for sklearn data is usually organised
# into one 2D array of shape (n_samples x n_features)
# containing all the data and one array of categories
# of length n_samples
X = np.concatenate((signal, backgr))
y = np.concatenate((np.ones(signal.shape[0]), np.zeros(backgr.shape[0])))
# convert to numpy ndarray into pandas dataframe
dataframe_X = pd.DataFrame(data=X, columns=features)
dataframe_y = pd.DataFrame(data=y, columns=['y'])
data = pd.concat([dataframe_X, dataframe_y], axis=1)
return data
# In[3]:
## Load data files
# Feature names
branch_names = """mass_tag_tag_min_deltaR,median_mass_jet_jet,
maxDeltaEta_tag_tag,mass_higgsLikeDijet,HT_tags,
btagDiscriminatorAverage_tagged,mass_jet_tag_min_deltaR,
mass_jet_jet_min_deltaR,mass_tag_tag_max_mass,maxDeltaEta_jet_jet,
centrality_jets_leps,centrality_tags""".split(",")
features = [c.strip() for c in branch_names]
features = (b.replace(" ", "_") for b in features)
features = list(b.replace("-", "_") for b in features)
wall = time.time()
process = time.clock()
# Load dataset
signal_sample = "combined/signalData.root"
background_sample = "combined/backgroundData.root"
tree_category = "event_mvaVariables_step7_cate4"
data = load(signal_sample, background_sample, tree_category, features)
print "Total number of events: {}\nNumber of features: {}".format(data.shape[0], data.shape[1])
# Store a copy for later use
df_archived = data.copy(deep=True)
print "\nWall time to read in file input: ", time.time()-wall
print "Elapsed time to read in file input: ", time.clock()-process
# ## Statistical Summary
#
# We give a statistical summary below to make sure the data makes sense and that nothing anomolous is present. As we can see values look promising and have acceptable variances.
# In[4]:
## Print statistical summary of dataset
# To print out all rows and columns to the terminal
pd.set_option("display.max_rows", None)
pd.set_option("display.max_columns", None)
wall = time.time()
process = time.clock()
print "Head:"
data.head()
print "Information:"
data.info()
print "Describe:"
data.describe()
print "\nWall time to print statistical summary: ", time.time()-wall
print "Elapsed time to print statistical summary: ", time.clock()-process
# In[5]:
## Define class label counts and percentages
def class_info(classes):
# Store the number of signal and background events
class_count = {}
counts = Counter(classes)
total = sum(counts.values())
for cls in counts.keys():
class_count[class_label[cls]] = counts[cls]
print("%6s: % 7d = % 5.1f%%" % (class_label[cls], counts[cls], float(counts[cls])/float((total))*100.0))
return (class_count["signal"], class_count["background"])
# In[6]:
# Determine class label counts and percentages
class_label = {0.0: "background", 1.0: "signal"}
class_info(data.y);
# ## Feature Visualization: Basic Exploratory Data Analyses¶
# We conduct a basic exploratory data analyses by producing correlaiton matrices between all variables of interest. In addition, we visually depict the relationship signal and background rate and feature variables.
# In[7]:
## Define linear correlation matrix
def correlations(data, **kwds):
"""Multi class version of Logarithmic Loss metric.
https://www.kaggle.com/wiki/MultiClassLogLoss
Parameters
----------
data : array, shape = [n_samples]
true class, intergers in [0, n_classes - 1)
kwds : array, shape = [n_samples, n_classes]
Returns
-------
loss : float
"""
"""To calculate pairwise correlation between features.
Extra arguments are passed on to DataFrame.corr()
"""
# Select signal or background label for plot title
if (data["y"] > 0.5).all(axis=0):
label = "signal"
elif (data["y"] < 0.5).all(axis=0):
label = "background"
# simply call df.corr() to get a table of
# correlation values if you do not need
# the fancy plotting
data = data.drop("y", axis=1)
# Add colorbar, make sure to specify tick locations to match desired ticklabels
labels = data.corr(**kwds).columns.values
fig, ax1 = plt.subplots(ncols=1, figsize=(8,7))
opts = {"annot" : True,
"ax" : ax1,
"vmin": 0, "vmax": 1*100,
"annot_kws" : {"size": 8},
"cmap": plt.get_cmap("Blues", 20),
}
ax1.set_title("Correlations: " + label)
sns.heatmap(data.corr(method="spearman").iloc[::-1]*100, **opts)
plt.yticks(rotation=0)
plt.xticks(rotation=90)
for ax in (ax1,):
# shift location of ticks to center of the bins
ax.set_xticks(np.arange(len(labels))+0.5, minor=False)
ax.set_yticks(np.arange(len(labels))+0.5, minor=False)
ax.set_xticklabels(labels[::-1], minor=False, ha="right", rotation=70)
ax.set_yticklabels(np.flipud(labels), minor=False)
plt.tight_layout()
return plt.show()
# In[8]:
## Plot feature correlations (assuming linear correlations)
wall = time.time()
process = time.clock()
# Remove the y column from the correlation matrix
# after using it to select background and signal
sig = data[data["y"] > 0.5]
bg = data[data["y"] < 0.5]
# Correlation Matrix
correlations(sig)
correlations(bg)
print "Wall time to plot correlation matrix: ", time.time()-wall
print "Elapsed time to plot correlation matrix: ", time.clock()-process
# In[9]:
## Scatter Plot
sns.set(style="ticks", color_codes=True)
wall = time.time()
process = time.clock()
random.seed(a=seed)
#_ = sns.pairplot(data.drop(data.y, axis=0), size=2.5, hue="y")
_ = sns.pairplot(data.drop(data.y, axis=0), size=2.5, hue="y",
markers=["o", "s"], plot_kws={ "s":5,"alpha":0.7 })
sns.plt.show()
print "Wall time to plot scatter distribution: ", time.time()-wall
print "Elapsed time to plot scatter distribution: ", time.clock()-process
# In[10]:
## Plot signal and background distributions for some variables
# The first two arguments select what is "signal"
# and what is "background". This means you can
# use it for more general comparisons of two
# subsets as well.
def signal_background(data1, data2, column=None, grid=True,
xlabelsize=None, xrot=None, ylabelsize=None,
yrot=None, ax=None, sharex=False,
sharey=False, figsize=None,
layout=None, bins=10, **kwds):
"""Draw histogram of the DataFrame's series comparing the distribution
in `data1` to `data2`.
data1: DataFrame
data2: DataFrame
column: string or sequence
If passed, will be used to limit data to a subset of columns
grid : boolean, default True
Whether to show axis grid lines
xlabelsize : int, default None
If specified changes the x-axis label size
xrot : float, default None
rotation of x axis labels
ylabelsize : int, default None
If specified changes the y-axis label size
yrot : float, default None
rotation of y axis labels
ax : matplotlib axes object, default None
sharex : bool, if True, the X axis will be shared amongst all subplots.
sharey : bool, if True, the Y axis will be shared amongst all subplots.
figsize : tuple
The size of the figure to create in inches by default
layout: (optional) a tuple (rows, columns) for the layout of the histograms
bins: integer, default 10
Number of histogram bins to be used
kwds : other plotting keyword arguments
To be passed to hist function
"""
if "alpha" not in kwds:
kwds["alpha"] = 0.5
w, h = (12, 8)
figsize = (w, h)
if column is not None:
if not isinstance(column, (list, np.ndarray, Index)):
column = [column]
data1 = data1[column]
data2 = data2[column]
data1 = data1._get_numeric_data()
data2 = data2._get_numeric_data()
naxes = len(data1.columns)
fig, axes = plotting._subplots(naxes=naxes,
ax=ax,
squeeze=False,
sharex=sharex,
sharey=sharey,
figsize=figsize,
layout=layout)
xs = plotting._flatten(axes)
for i, col in enumerate(com._try_sort(data1.columns)):
ax = xs[i]
low = min(data1[col].min(), data2[col].min())
high = max(data1[col].max(), data2[col].max())
ax.hist(data1[col].dropna().values,
bins=bins, histtype='stepfilled', range=(low,high), **kwds)
ax.hist(data2[col].dropna().values,
bins=bins, histtype='stepfilled', range=(low,high), **kwds)
ax.set_title(col)
ax.legend(['background', 'signal'], loc='best')
ax.set_axis_bgcolor('white')
# Customize the major grid
ax.grid(which='major', linestyle='-', linewidth='0.2', color='gray')
ax.set_axis_bgcolor('white')
plotting._set_ticks_props(axes, xlabelsize=xlabelsize, xrot=xrot,
ylabelsize=ylabelsize, yrot=yrot)
fig.subplots_adjust(wspace=0.5, hspace=0.8)
return plt.show()
# In[11]:
## Plot feature hitograms
wall = time.time()
process = time.clock()
signal_background(data[data["y"] < 0.5], data[data["y"] > 0.5],
column=features, bins=40);
print "\nWall time to plot exploratory data features: ", time.time()-wall
print "Elapsed time to plot exploratory data features: ", time.clock()-process
# In[12]:
## Create features dataframe and target array
df_X = data.drop("y", axis=1, inplace=False)
df_y = data["y"]
# ## Model performance measure
#
# We investigate several machine learning models in order to establish which algorithm may be the most promising for the discrimination modeling of signal and background processes. Two performance measures wil be used to help select our model, namely, accuracy and the area under the receiver operating characteristic (ROC) curve. Receiver Operating Characteristic (ROC) curve number is equal to the probability that a random positive example will be ranked above a random negative example.
# In[13]:
## Compute ROC curve and area under the curve
def roc_plot(models, X, y):
"""Multi class version of Logarithmic Loss metric.
https://www.kaggle.com/wiki/MultiClassLogLoss
Parameters
----------
models : dictionary, shape = [n_models]
X : DataFrame, shape = [n_samples, n_classes]
y : DataFrame, shape = [n_classes]
Returns
-------
roc : matplotlib plot
"""
# Split data into a development and evaluation set
X_dev,X_eval, y_dev,y_eval = train_test_split(X, y, test_size=0.33, random_state=42)
# Split development set into a train and test set
X_train, X_test, y_train, y_test = train_test_split(X_dev, y_dev,
test_size=0.33, random_state=seed)
# contains rates for ML classifiers
fpr = {}
tpr = {}
roc_auc = {}
# Customize the major grid
fig, ax = plt.subplots()
ax.grid(which='major', linestyle='-', linewidth='0.2', color='gray')
ax.set_axis_bgcolor('white')
# Include random by chance 'luck' curve
plt.plot([1, 0], [0, 1], '--', color=(0.1, 0.1, 0.1), label='Luck')
# Loop through classifiers
for (name, model) in models.items():
print "\n\x1b[1;31mBuilding model ...\x1b[0m"
process = time.clock()
model.fit(X_train, y_train)
print "\t%s fit time: %.3f"%(name, time.clock()-process)
y_predicted = model.predict(X_test)
if hasattr(model, "predict_proba"):
decisions = model.predict_proba(X_test)[:, 1] # probability estimates of the positive class(as needed in the roc_curve function)
else: # use decision function
decisions = model.decision_function(X_test)
print "\tArea under ROC curve for %s: %.4f"%(name, roc_auc_score(y_test,decisions))
process = time.clock()
scores = cross_val_score(model, X_test, y_test, scoring="roc_auc",
n_jobs=1, cv=3) #n_jobs=-1
print "\tAUC ROC accuracy: %0.5f (+/- %0.5f)"%(scores.mean(), scores.std())
print classification_report(y_test, y_predicted, target_names=['signal', 'background'])
print "\tDuration of cross-validation score: ", time.clock()-process
print("\tScore of test dataset: {:.5f}".format(model.score(X_test, y_test)))
process = time.clock()
fpr[name], tpr[name], thresholds = roc_curve(y_test, decisions)
print "\tArea under ROC time: ", time.clock()-process
roc_auc[name] = auc(fpr[name], tpr[name])
# color choices: https://css-tricks.com/snippets/css/named-colors-and-hex-equivalents/
colors = cycle(['aqua', 'darkorange', 'cornflowerblue',
'green', 'yellow', 'SlateBlue', 'DarkSlateGrey',
'CadetBlue', 'Chocolate', 'darkred', 'GoldenRod'])
for (name, model), color in zip(models.items(), colors):
plt.plot(tpr[name], 1-fpr[name], color=color, lw=2,
label='%s (AUC = %0.3f)'%(name, roc_auc[name]))
# Plot all ROC curves
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title("Receiver operating characteristic ({} events)".format(X.shape[0]))
leg = plt.legend(loc="lower left", frameon=True, fancybox=True, fontsize=8) # loc='best'
leg.get_frame().set_edgecolor('w')
frame = leg.get_frame()
frame.set_facecolor('White')
return plt.show()
# In[14]:
# Plot AUC for ROC curve for several classifiers out-of-the-box
wall = time.time()
process = time.clock()
# Set feature scaling type
scaler = RobustScaler()
# NOTE: When using scikit-learn's DecisionTreeClassifier,
# always set min_samples_leaf to something like 5 or 10.
# Its default value of 1 is useless and is guaranteed to overfit.
# (This is why every example of DecisionTreeClassifier in their docs shows overfitting.)
# prepare models: create a mapping of ML classifier name to algorithm
pipe_classifiers = {
'SVM': make_pipeline(scaler, SVC()),
'NB' : make_pipeline(scaler, GaussianNB()),
'MLP': make_pipeline(scaler, MLPClassifier()),
'LR' : make_pipeline(scaler, LogisticRegression()),
'ADA': make_pipeline(None, AdaBoostClassifier()),
'KNN': make_pipeline(scaler, KNeighborsClassifier()),
'RFC': make_pipeline(None, RandomForestClassifier()),
'CART': make_pipeline(None, DecisionTreeClassifier(min_samples_leaf=10)),
'LDA': make_pipeline(scaler, LinearDiscriminantAnalysis()),
'GRAD': make_pipeline(None, GradientBoostingClassifier()),
'BAGG': make_pipeline(None, BaggingClassifier())
}
# Assessing a Classifier's Performance
roc_plot(pipe_classifiers, df_X, df_y)
print "\nWall time to generate ROC plots: ", time.time()-wall
print "Elapsed time to generate ROC plots: ", time.clock()-process
# In[15]:
# Plot AUC for ROC curve for several classifiers out-of-the-box
wall = time.time()
process = time.clock()
# Set feature scaling type
scaler = RobustScaler()
# NOTE: When using scikit-learn's DecisionTreeClassifier,
# always set min_samples_leaf to something like 5 or 10.
# Its default value of 1 is useless and is guaranteed to overfit.
# (This is why every example of DecisionTreeClassifier in their docs shows overfitting.)
# prepare models: create a mapping of ML classifier name to algorithm
pipe_classifiers = {
'SVM': make_pipeline(scaler, SVC(class_weight="balanced")),
'NB' : make_pipeline(scaler, GaussianNB()),
'MLP': make_pipeline(scaler, MLPClassifier()),
'LR' : make_pipeline(scaler, LogisticRegression(class_weight="balanced")),
'ADA': make_pipeline(None, AdaBoostClassifier()),
'KNN': make_pipeline(scaler, KNeighborsClassifier()),
'RFC': make_pipeline(None, RandomForestClassifier()),
'CART': make_pipeline(None, DecisionTreeClassifier(min_samples_leaf=10, class_weight="balanced")),
'LDA': make_pipeline(scaler, LinearDiscriminantAnalysis()),
'GRAD': make_pipeline(None, GradientBoostingClassifier()),
'BAGG': make_pipeline(None, BaggingClassifier())
}
# Assessing a Classifier's Performance
roc_plot(pipe_classifiers, df_X, df_y)
print "\nWall time to generate ROC plots: ", time.time()-wall
print "Elapsed time to generate ROC plots: ", time.clock()-process
# ## Precision-Recall Plots
#
# Precision-Recall metric to evaluate classifier output quality.
#
# Recall is a performance measure of the whole positive part of a dataset, whereas precision is a performance measure of positive predictions.
#
# In information retrieval, precision is a measure of result relevancy, while recall is a measure of how many truly relevant results are returned. A high area under the curve represents both high recall and high precision, where high precision relates to a low false positive rate, and high recall relates to a low false negative rate. High scores for both show that the classifier is returning accurate results (high precision), as well as returning a majority of all positive results (high recall).
#
# A system with high recall but low precision returns many results, but most of its predicted labels are incorrect when compared to the training labels. A system with high precision but low recall is just the opposite, returning very few results, but most of its predicted labels are correct when compared to the training labels. An ideal system with high precision and high recall will return many results, with all results labeled correctly.
#
# It is important to note that the precision may not decrease with recall. The definition of precision ($\frac{T_p}{T_p + F_p}$) shows that lowering the threshold of a classifier may increase the denominator, by increasing the number of results returned. If the threshold was previously set too high, the new results may all be true positives, which will increase precision. If the previous threshold was about right or too low, further lowering the threshold will introduce false positives, decreasing precision.
#
# Recall is defined as $\frac{T_p}{T_p+F_n}$, where $T_p+F_n$ does not depend on the classifier threshold. This means that lowering the classifier threshold may increase recall, by increasing the number of true positive results. It is also possible that lowering the threshold may leave recall unchanged, while the precision fluctuates.
#
# SOURCE: http://scikit-learn.org/stable/auto_examples/model_selection/plot_precision_recall.html
#
# "it has been shown by Davis & Goadrich that an algorithm that optimizes the area under the ROC curve is not guaranteed to optimize the area under the PR curve."
# In[16]:
## Define precision-recall curve
def plot_PR_curve(classifier, X, y, n_folds=5):
"""
Plot a basic precision/recall curve.
"""
# Customize the major grid
fig, ax = plt.subplots()
ax.grid(which='major', linestyle='-', linewidth='0.2', color='gray')
ax.set_axis_bgcolor('white')
# Calculate the random luck for PR
# (above the constant line is a classifier that is well modeled)
signal_count, background_count = class_info(y)
ratio = float(signal_count)/float(signal_count + background_count)
# store average precision calculation
avg_scores = []
# Loop through classifiers
for (name, model) in classifier.items():
skf = StratifiedKFold(n_splits=n_folds, shuffle=True, random_state=seed)
for i, (train, test) in enumerate(skf.split(X,y)):
model.fit(X[train], y[train])
if hasattr(model, "predict_proba"):
probas_ = model.predict_proba(X[test])[:, 1]
else: # use decision function
probas_ = model.decision_function(X[test])
# Compute ROC curve and area the curve
precision, recall, thresholds = precision_recall_curve(y[test],
probas_, pos_label=1)
average_precision = average_precision_score(y[test], probas_)
avg_scores.append(average_precision)
plt.plot(recall, precision, lw=1,
label='{0} (auc = {1:0.2f})'.format(name,np.mean(avg_scores, axis=0)))
plt.plot([ratio,ratio], '--', color=(0.1, 0.1, 0.1),
label='Luck (auc = {0:0.2f})'.format(ratio))
plt.xlim([-0.05, 1.05])
plt.ylim([-0.05, 1.05])
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('Precision-recall curve')
plt.legend(loc="lower left")
return plt.show()
# In[17]:
# Plot precision-recall curve for several classifiers out-of-the-box
wall = time.time()
process = time.clock()
plot_PR_curve(pipe_classifiers, df_X.values, df_y.values, n_folds=5)
print "\nWall time to generate Precision-Recall plots: ", time.time()-wall
print "Elapsed time to generate Precision-Recall plots: ", time.clock()-process
# Among the models with best performance on the test set:
#
# - Random forests
# - Gradient boosting
# - Boosting decision tree
#
# We observe that the GradientBoostingClassifier has relatively the best accuracy and area under the ROC curve value. Therefore, we select this predictive model and proceed to evaluate whether it is overfitting the model to the noise (e.g. statistical fluctuation) of the data.
# ## Overfitting Evaluation
#
# Comparing the ML classifier output distribution for the training and testing set to check for overtraining. By comparing the ML classifier's decision function for each class, as well as overlaying it with the shape of the decision function in the training set.
#
#
# Using the default parameters for the ML Classifiers we study whether the model is over-fitting the test data.
# In[18]:
## Defined overfitting plot
def compare_train_test(clf, X, y, bins=30):
"""Multi class version of Logarithmic Loss metric.
Parameters
----------
y_true : array, shape = [n_samples]
true class, intergers in [0, n_classes - 1)
y_pred : array, shape = [n_samples, n_classes]
Returns
-------
loss : float
"""
# Split data into a development and evaluation set
X_dev,X_eval, y_dev,y_eval = train_test_split(X, y, test_size=0.33, random_state=42)
# Split development set into a train and test set
X_train, X_test, y_train, y_test = train_test_split(X_dev, y_dev,
test_size=0.33, random_state=seed)
# use subplot to extract axis to add ks and p-value to plot
fig, ax = plt.subplots()
# Customize the major grid
ax.grid(which='major', linestyle='-', linewidth='0.2', color='gray')
ax.set_axis_bgcolor('white')
decisions = []
for X, y in ((X_train, y_train), (X_test, y_test)):
if hasattr(clf,"decision_function"):
d1 = clf.decision_function(X[y>0.5]).ravel()
d2 = clf.decision_function(X[y<0.5]).ravel()
else:
d1 = clf.predict_proba(X[y>0.5])[:, 1]
d2 = clf.predict_proba(X[y<0.5])[:, 1]
decisions += [d1, d2]
low = min(np.min(d) for d in decisions)
high = max(np.max(d) for d in decisions)
low_high = (low,high)
plt.hist(decisions[0],
color='r', alpha=0.5, range=low_high, bins=bins,
histtype='stepfilled', normed=True,
label='signal (train)')
plt.hist(decisions[1],
color='b', alpha=0.5, range=low_high, bins=bins,
histtype='stepfilled', normed=True,
label='background (train)')
hist, bins = np.histogram(decisions[2],
bins=bins, range=low_high, normed=True)
scale = len(decisions[2]) / sum(hist)
err = np.sqrt(hist * scale) / scale
width = (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
plt.errorbar(center, hist, yerr=err, fmt='o', c='r', label='signal (test)')
hist, bins = np.histogram(decisions[3],
bins=bins, range=low_high, normed=True)
scale = len(decisions[2]) / sum(hist)
err = np.sqrt(hist * scale) / scale
plt.errorbar(center, hist, yerr=err, fmt='o', c='b', label='background (test)')
# Define signal and background histograms for training & testing
hist_sig_train, bins = np.histogram(decisions[0], bins=bins, range=low_high, normed=True)
hist_bkg_train, bins = np.histogram(decisions[1], bins=bins, range=low_high, normed=True)
hist_sig_test, bins = np.histogram(decisions[2], bins=bins, range=low_high, normed=True)
hist_bkg_test, bins = np.histogram(decisions[3], bins=bins, range=low_high, normed=True)
# Estimate ks-test and p-values as an indicator of overtraining of fit model
s_ks, s_pv = ks_2samp(hist_sig_train, hist_sig_test)
b_ks, b_pv = ks_2samp(hist_bkg_train, hist_bkg_test)
if hasattr(clf, "steps"):
name = clf.steps[1][0]
else:
name = clf.__class__.__name__
ax.set_title("Classifier: %s\nsignal(background) ks: %f(%f), p-value: %f (%f)"
% (name, s_ks, b_ks, s_pv, b_pv))
plt.xlabel("Decision output")
plt.ylabel("Arbitrary units")
plt.legend(loc='best')
return plt.show()
# In[19]:
## Overfitting evaluation
wall = time.time()
process = time.clock()
# Uncalibrated model predictions
model = pipe_classifiers["GRAD"]
compare_train_test(model, df_X, df_y, bins=40)
# Calibrated with isotonic calibration
model_isotonic = CalibratedClassifierCV(model, cv=5, method='sigmoid')
model_isotonic.fit(df_X, df_y)
compare_train_test(model_isotonic, df_X, df_y, bins=40)
# Uncalibrated model predictions
model = pipe_classifiers["ADA"]
compare_train_test(model, df_X, df_y, bins=40)
# Calibrated with isotonic calibration
model_isotonic = CalibratedClassifierCV(model, cv=5, method='sigmoid')
model_isotonic.fit(df_X, df_y)
compare_train_test(model_isotonic, df_X, df_y, bins=40)
# Uncalibrated model predictions
model = pipe_classifiers["SVM"]
compare_train_test(model, df_X, df_y, bins=40)
# Calibrated with isotonic calibration
model_isotonic = CalibratedClassifierCV(model, cv=5, method='sigmoid')
model_isotonic.fit(df_X, df_y)
compare_train_test(model_isotonic, df_X, df_y, bins=40)
# Uncalibrated model predictions
model = pipe_classifiers["LDA"]
compare_train_test(model, df_X, df_y, bins=40)
# Calibrated with isotonic calibration
model_isotonic = CalibratedClassifierCV(model, cv=5, method='sigmoid')
model_isotonic.fit(df_X, df_y)
compare_train_test(model_isotonic, df_X, df_y, bins=40)
# Uncalibrated model predictions
model = pipe_classifiers["KNN"]
compare_train_test(model, df_X, df_y, bins=40)
# Calibrated with isotonic calibration
model_isotonic = CalibratedClassifierCV(model, cv=5, method='sigmoid')
model_isotonic.fit(df_X, df_y)
compare_train_test(model_isotonic, df_X, df_y, bins=40)
# Uncalibrated model predictions
model = pipe_classifiers["LR"]
compare_train_test(model, df_X, df_y, bins=40)
# Calibrated with isotonic calibration
model_isotonic = CalibratedClassifierCV(model, cv=5, method='sigmoid')
model_isotonic.fit(df_X, df_y)
compare_train_test(model_isotonic, df_X, df_y, bins=40)
# Uncalibrated model predictions
model = pipe_classifiers["CART"]
compare_train_test(model, df_X, df_y, bins=40)
# Calibrated with isotonic calibration
model_isotonic = CalibratedClassifierCV(model, cv=5, method='sigmoid')
model_isotonic.fit(df_X, df_y)
compare_train_test(model_isotonic, df_X, df_y, bins=40)
# Uncalibrated model predictions
model = pipe_classifiers["RFC"]
compare_train_test(model, df_X, df_y, bins=40)
# Calibrated with isotonic calibration
model_isotonic = CalibratedClassifierCV(model, cv=5, method='sigmoid')
model_isotonic.fit(df_X, df_y)
compare_train_test(model_isotonic, df_X, df_y, bins=40)
# Uncalibrated model predictions
model = pipe_classifiers["NB"]
compare_train_test(model, df_X, df_y, bins=40)
# Calibrated with isotonic calibration
model_isotonic = CalibratedClassifierCV(model, cv=5, method='sigmoid')
model_isotonic.fit(df_X, df_y)
compare_train_test(model_isotonic, df_X, df_y, bins=40)
print "\nWall time to generate over-training plots: ", time.time()-wall
print "Elapsed time to generate over-traing plots: ", time.clock()-process
# ## Probability calibration
#
# When performing classification you often want not only to predict the class label, but also obtain a probability of the respective label. This probability gives you some kind of confidence on the prediction. Some models can give you poor estimates of the class probabilities and some even do not not support probability prediction. Well calibrated classifiers are probabilistic classifiers for which the output of the predict_proba method can be directly interpreted as a confidence level.
#
# Two approaches for performing calibration of probabilistic predictions are provided:
# - a parametric approach based on Platt's sigmoid model and a non-parametric approach based on isotonic regression.
#
# Probability calibration should be done on new data not used for model fitting. The modelue uses a cross-validation generator and estimates for each split the model parameter on the train samples and the calibration of the test samples. The probabilities predicted for the folds are then averaged. Already fitted classifiers can be calibrated by CalibratedClassifierCV via the paramter cv="prefit". In this case, the user has to take care manually that data for model fitting and calibration are disjoint.
# In[20]:
## Define calibration curve (reliability curve)
def plot_calibration_curve(est, X, y, fig_index):
"""Plot calibration curve for est w/o and with calibration. """
# Split data into a development and evaluation set
X_dev,X_eval, y_dev,y_eval = train_test_split(X, y,
test_size=0.33, random_state=42)
# Split development set into a train and test set
X_train, X_test, y_train, y_test = train_test_split(X_dev, y_dev, test_size=0.33,
random_state=seed)
name = est.steps[1][0]
# Calibrated with isotonic calibration
isotonic = CalibratedClassifierCV(est, cv=2, method='isotonic')
# Calibrated with sigmoid calibration
sigmoid = CalibratedClassifierCV(est, cv=2, method='sigmoid')
# We take the no calibration as baseline
fig = plt.figure(fig_index, figsize=(6, 6))
ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2)
ax2 = plt.subplot2grid((3, 1), (2, 0))
ax1.plot([0, 1], [0, 1], "--", label="Perfectly calibrated")
for clf, name in [(est, name,)
(isotonic, name + ' + Isotonic'),
(sigmoid, name + ' + Sigmoid')]: # Also called Platt Scaling