-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPSStabML.py
1480 lines (906 loc) · 42.1 KB
/
PSStabML.py
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
#!/usr/bin/env python
# coding: utf-8
# # Machine learning for Power System Stability Analysis
# <p style="background-color:azure;padding:10px;border:2px solid lightsteelblue"><b>Author:</b> Petar Sarajcev, PhD ([email protected])
# <br>
# University of Split, FESB, Department of Power Engineering <br>R. Boskovica 32, HR-21000 Split, Croatia, EU.</p>
# In[1]:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# In[2]:
from scipy import stats
# In[3]:
from sklearn import metrics
from sklearn import preprocessing
from sklearn import feature_selection
from sklearn import svm
from sklearn.manifold import TSNE
from sklearn.decomposition import PCA, TruncatedSVD
from sklearn.linear_model import LogisticRegression as LR
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.ensemble import VotingClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import RandomizedSearchCV
from sklearn.model_selection import KFold, StratifiedKFold
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import cross_val_predict
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline, FeatureUnion
# In[4]:
import keras
# In[5]:
import warnings
# In[7]:
warnings.filterwarnings(action='ignore', category=FutureWarning)
# In[8]:
# Inline figures
get_ipython().run_line_magic('matplotlib', 'inline')
# In[9]:
# Figure aesthetics
sns.set(context='notebook', style='white', font_scale=1.1)
sns.set_style('ticks', {'xtick.direction':'in', 'ytick.direction':'in'})
# In[10]:
# ancilary function from: https://github.com/amueller/introduction_to_ml_with_python/blob/master/mglearn/tools.py
def heatmap(values, xlabel, ylabel, xticklabels, yticklabels, cmap=None,
vmin=None, vmax=None, ax=None, fmt="%0.2f", fontsize=14):
if ax is None:
ax = plt.gca()
# plot the mean cross-validation scores
img = ax.pcolor(values, cmap=cmap, vmin=vmin, vmax=vmax)
img.update_scalarmappable()
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.set_xticks(np.arange(len(xticklabels)) + .5)
ax.set_yticks(np.arange(len(yticklabels)) + .5)
ax.set_xticklabels(xticklabels)
ax.set_yticklabels(yticklabels)
ax.set_aspect(1)
for p, color, value in zip(img.get_paths(), img.get_facecolors(),
img.get_array()):
x, y = p.vertices[:-2, :].mean(0)
if np.mean(color[:3]) > 0.5:
c = 'k'
else:
c = 'w'
ax.text(x, y, fmt % value, color=c, ha="center", va="center", fontsize=fontsize)
return img
# ### Transformer diagnostic data and health index values
# In[11]:
data = pd.read_csv('GridDictionary.csv')
data.head()
# In[9]:
#print(data.columns.values)
# In[12]:
# Percentage of "ones" in the "Stability" column
print('There is {:.1f}% of unstable cases in the dataset!'.format(data['Stability'].sum()/float(len(data['Stability']))*100.))
# ### Select a random subset of the original data
# In[11]:
# Select a random subset of the original dataset (without replacement)
#SUBSET_SIZE = 2000
#random_idx = np.random.choice(data.index, size=SUBSET_SIZE, replace=False)
#data = data.iloc[random_idx]
# ### Data preprocessing and splitting
# In[13]:
# Training dataset
no_features = len(data.columns) - 1
X_data = data.iloc[:,0:no_features] # features
print('X_data', X_data.shape)
y_data = data['Stability']
print('y_data', y_data.shape)
# In[14]:
# Split dataset into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, train_size=0.8, shuffle=True)
# In[15]:
print('X_train', X_train.shape)
print('y_train', y_train.shape)
print('X_test', X_test.shape)
print('y_test', y_test.shape)
# In[16]:
print('Unstable cases in training dataset: {:.1f}%:'.format(np.sum(y_train)/float(len(y_train))*100.))
print('Unstable cases in testing dataset {:.1f}%:'.format(np.sum(y_test)/float(len(y_test))*100.))
# In[17]:
print('Unstable cases in training dataset: {:.1f}%:'.format(np.sum(y_train)/float(len(y_train))*100.))
print('Unstable cases in testing dataset {:.1f}%:'.format(np.sum(y_test)/float(len(y_test))*100.))
# In[18]:
y_t = data[['Stability']].copy()
idx = y_test.index.values
y_t = y_t.loc[idx]
y_t.shape
# #### StandardScaler
# In[19]:
# Standardize the input data
scaler = preprocessing.StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# ### LogisticRegression
# In[20]:
# Grid-search with cross validation for optimal model hyper-parameters
parameters = {'C':[1., 10., 50., 100., 500., 1000.]}
lreg = GridSearchCV(estimator=LR(multi_class='auto', solver='newton-cg',
class_weight='balanced'), # class balancing
param_grid=parameters, cv=3, scoring='f1', # notice the "scoring" method!
refit=True, n_jobs=-1, iid=False)
# In this case GridSearchCV uses StratifiedKFold (with cv=3 folds) when
# the estimator is a classifier and y is either binary or multiclass!
lreg.fit(X_train, y_train)
# Best value of hyper-parameter "C"
best_c = lreg.best_params_['C']
print('Best value: C = {:g}'.format(best_c))
# In[21]:
# Average classification accuracy with cross validation
scores = cross_val_score(lreg, X_train, y_train, cv=3, scoring='f1') # it does not return a model!
print('Score using 3-fold CV: {:g} +/- {:g}'.format(np.mean(scores), np.std(scores)))
# In[22]:
pred = lreg.predict(X_test)
labels = ['Stable', 'Unstable']
# confusion matrix
scores_image = heatmap(metrics.confusion_matrix(y_test, pred), xlabel='Predicted label',
ylabel='True label', xticklabels=labels, yticklabels=labels,
cmap=plt.cm.gray_r, fmt="%d")
plt.title("Confusion matrix")
plt.gca().invert_yaxis()
plt.show()
# In[23]:
# classification report
print(metrics.classification_report(y_test, pred, target_names=labels))
# In[24]:
pd.DataFrame(data=[metrics.accuracy_score(y_test, pred), metrics.recall_score(y_test, pred),
metrics.precision_score(y_test, pred), metrics.roc_auc_score(y_test, pred)],
index=["accuracy", "recall", "precision", "roc_auc_score"], columns=['Values'])
# ### Principal components analysis
# In[25]:
# Let's first reduce all features in the dataset down to 3 principal components.
pca = PCA(n_components=3)
X3_train = pca.fit_transform(X_train)
X3_test = pca.transform(X_test)
idx_stable = y_test==0
# In[26]:
# Let's see what it looks like
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(8,8))
ax0 = fig.add_subplot(221)
ax0.scatter(X3_test[idx_stable,1], X3_test[idx_stable,2],
s=30, c='green', marker='o', edgecolors='k', alpha=0.5, label='Stable')
ax0.scatter(X3_test[~idx_stable,1], X3_test[~idx_stable,2],
s=30, c='red', marker='o', edgecolors='k', alpha=0.5, label='Unstable')
ax0.legend(loc='upper right')
ax0.set_xlabel('Second principal component')
ax0.set_ylabel('Third principal component')
ax0.grid()
ax1 = fig.add_subplot(222, projection='3d')
ax1.scatter(X3_test[idx_stable,0], X3_test[idx_stable,1], X3_test[idx_stable,2],
s=30, c='green', marker='o', edgecolors='k', alpha=0.5, label='Stable')
ax1.scatter(X3_test[~idx_stable,0], X3_test[~idx_stable,1], X3_test[~idx_stable,2],
s=30, c='red', marker='o', edgecolors='k', alpha=0.5, label='Unstable')
ax1.legend(loc='upper right')
ax1.set_xlabel('1st comp.')
ax1.set_ylabel('2nd comp.')
#ax1.set_zlabel('3rd comp.')
ax0 = fig.add_subplot(223)
ax0.scatter(X3_test[idx_stable,0], X3_test[idx_stable,1],
s=30, c='green', marker='o', edgecolors='k', alpha=0.5, label='Stable')
ax0.scatter(X3_test[~idx_stable,0], X3_test[~idx_stable,1],
s=30, c='red', marker='o', edgecolors='k', alpha=0.5, label='Unstable')
ax0.legend(loc='upper right')
ax0.set_xlabel('First principal component')
ax0.set_ylabel('Second principal component')
ax0.grid()
ax0 = fig.add_subplot(224)
ax0.scatter(X3_test[idx_stable,0], X3_test[idx_stable,2],
s=30, c='green', marker='o', edgecolors='k', alpha=0.5, label='Stable')
ax0.scatter(X3_test[~idx_stable,0], X3_test[~idx_stable,2],
s=30, c='red', marker='o', edgecolors='k', alpha=0.5, label='Unstable')
ax0.legend(loc='upper right')
ax0.set_xlabel('First principal component')
ax0.set_ylabel('Third principal component')
ax0.grid()
fig.tight_layout()
plt.savefig('PCA-3D.png', dpi=600)
plt.show()
# In[27]:
# Average LR accuracy with only three principal components as features
scores = cross_val_score(LR(C=best_c, multi_class='ovr', solver='newton-cg',
class_weight='balanced'),
X3_train, y_train, cv=3, scoring='f1')
print('Score using 3-fold CV: {:g} +/- {:g}'.format(np.mean(scores), np.std(scores)))
# ### Autoencoder
# In[28]:
# Reducing "no_features" to 2D space with autoencoder
input_layer = keras.layers.Input(shape=(no_features,))
# "encoded" is the encoded representation of the input
x = keras.layers.Dense(128, activation='relu',
kernel_initializer='glorot_normal')(input_layer)
x = keras.layers.Dense(64, activation='relu',
kernel_initializer='glorot_normal')(x)
encoded = keras.layers.Dense(2, activation='relu',
kernel_initializer='glorot_normal')(x)
# "decoded" is the lossy reconstruction of the input
x = keras.layers.Dense(64, activation='relu',
kernel_initializer='glorot_normal')(encoded)
x = keras.layers.Dense(128, activation='relu',
kernel_initializer='glorot_normal')(x)
decoded = keras.layers.Dense(no_features, activation='linear',
kernel_initializer='glorot_normal')(x)
# Autoencoder
autoencoder = keras.models.Model(input_layer, decoded)
# Encoder
encoder = keras.models.Model(input_layer, encoded)
# Compile the model
autoencoder.compile(optimizer='adadelta', loss='kullback_leibler_divergence')
# Define early stopping criteria
early_stopping = keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=0.01, patience=5, verbose=1)
history = autoencoder.fit(X_train, X_train, epochs=100, batch_size=256,
shuffle=True, validation_split=0.1,
callbacks=[early_stopping], verbose=0)
# In[29]:
plt.plot(history.history['loss'], label='loss')
plt.plot(history.history['val_loss'], label='val_loss')
plt.legend()
plt.show()
# In[30]:
encoded_data = encoder.predict(X_test)
# In[31]:
fig, ax = plt.subplots(figsize=(5,5))
ax.scatter(encoded_data[idx_stable,0], encoded_data[idx_stable,1],
s=30, c='green', marker='o', edgecolors='k', alpha=0.5, label='Stable')
ax.scatter(encoded_data[~idx_stable,0], encoded_data[~idx_stable,1],
s=30, c='red', marker='o', edgecolors='k', alpha=0.5, label='Unstable')
ax.legend(loc='best')
ax.set_xlabel('First component')
ax.set_ylabel('Second component')
ax.grid()
fig.tight_layout()
plt.savefig('Autoencode2D.png', dpi=600)
plt.show()
# ### Dimensionality reduction using truncated SVD
# In[32]:
svd = TruncatedSVD(n_components=2)
X_svd = svd.fit_transform(X_test)
# In[33]:
fig, ax = plt.subplots(figsize=(5,5))
ax.scatter(X_svd[idx_stable,0], X_svd[idx_stable,1],
s=30, c='green', marker='o', edgecolors='k', alpha=0.5, label='Stable')
ax.scatter(X_svd[~idx_stable,0], X_svd[~idx_stable,1],
s=30, c='red', marker='o', edgecolors='k', alpha=0.5, label='Unstable')
ax.legend(loc='best')
ax.set_xlabel('First component')
ax.set_ylabel('Second component')
ax.grid()
fig.tight_layout()
plt.show()
# ### t-distributed Stochastic Neighbor Embedding
# In[34]:
tsne = TSNE(n_components=2)
X_embedded = tsne.fit_transform(X_test)
# In[35]:
fig, ax = plt.subplots(figsize=(5,5))
ax.scatter(X_embedded[idx_stable,0], X_embedded[idx_stable,1],
s=30, c='green', marker='o', edgecolors='k', alpha=0.5, label='Stable')
ax.scatter(X_embedded[~idx_stable,0], X_embedded[~idx_stable,1],
s=30, c='red', marker='o', edgecolors='k', alpha=0.5, label='Unstable')
ax.legend(loc='best')
ax.set_xlabel('First component')
ax.set_ylabel('Second component')
ax.grid()
fig.tight_layout()
plt.show()
# #### Feature selection with Pipeline and GridSearch
# In[30]:
# Optimize the number of features and the classifier's hyper-parameters
# at the same time, using pipline and grid search with cross-validation
pca = PCA() # do NOT set "n_components" here!
logreg = LR(multi_class='ovr', solver='newton-cg', class_weight='balanced')
pipe = Pipeline([('pca',pca), ('logreg',logreg)])
param_grid = {'pca__n_components': [10, 20, 30, 50, 100], # PCA
'logreg__C': [1., 10., 50., 100.]} # LogisticRegression
grid_pipe = GridSearchCV(estimator=pipe, param_grid=param_grid, cv=3,
scoring='f1', refit=True, n_jobs=-1, iid=False)
grid_pipe.fit(X_train, y_train)
print('Best parameter (CV score = {:0.3f}):'.format(grid_pipe.best_score_))
print(grid_pipe.best_params_)
# In[31]:
# Predict probability on test data
y_lr = grid_pipe.predict_proba(X_test)
y_t['logreg'] = y_lr.argmax(axis=1)
# ### Support Vector Machine
# In[32]:
parameters ={'C':[1., 10., 100., 500., 1000.],
'gamma':[0.0001, 0.001, 0.01, 0.1, 1.]}
svc = GridSearchCV(estimator=svm.SVC(kernel='rbf', probability=True,
class_weight='balanced'), # class balancing
param_grid=parameters, cv=3,
scoring='f1', refit=True, n_jobs=-1, iid=False)
svc.fit(X_train, y_train)
# In[33]:
# Best model parameters
best_parameters = svc.best_params_
print("Best parameters from GridSearch: {}".format(svc.best_params_))
# In[34]:
scores = cross_val_score(svc, X_train, y_train, cv=3, scoring='f1')
print('Average score using 3-fold CV: {:g} +/- {:g}'.format(np.mean(scores), np.std(scores)))
# In[35]:
results = pd.DataFrame(svc.cv_results_)
scores = np.array(results.mean_test_score).reshape(len(parameters['C']), len(parameters['gamma']))
# In[36]:
fig, ax = plt.subplots(figsize=(5,5))
heatmap(scores, xlabel='gamma', xticklabels=parameters['gamma'],
ylabel='C', yticklabels=parameters['C'], cmap="viridis", ax=ax)
plt.show()
# #### RandomizedSearchCV
# In[37]:
parameters = {'C':stats.expon(scale=100), 'gamma':stats.expon(scale=.1)}
svc2 = RandomizedSearchCV(estimator=svm.SVC(kernel='rbf', probability=True,
class_weight='balanced'),
param_distributions=parameters, cv=3, n_iter=50, # 50 iterations!
scoring='f1', # notice the scoring method!
refit=True, n_jobs=-1, iid=False)
svc2.fit(X_train, y_train)
# In[38]:
# Best model parameters
best_parameters = svc2.best_params_
print("Best parameters from RandomSearch: {}".format(svc2.best_params_))
# In[39]:
scores = cross_val_score(svc2, X_train, y_train, cv=3, scoring='f1')
print('Average score using 3-fold CV: {:g} +/- {:g}'.format(np.mean(scores), np.std(scores)))
# In[40]:
# classification report
pred = svc2.predict(X_test)
print(metrics.classification_report(y_test, pred, target_names=labels))
# In[41]:
y_svc2 = svc2.predict_proba(X_test)
y_t['svc'] = y_svc2.argmax(axis=1)
# #### Precision-Recall Tradeoff
# In[42]:
y_probas = cross_val_predict(svm.SVC(**best_parameters, probability=True, class_weight='balanced'),
X_train, y_train, cv=3, method='predict_proba')
# In[43]:
y_scores = y_probas[:,1] # score == probability of positive class
precisions, recalls, thresholds = metrics.precision_recall_curve(y_train, y_scores)
# In[44]:
fig, ax = plt.subplots(figsize=(6,4))
#ax.set_title('SVM Precision-Recall tradeof')
ax.plot(thresholds, precisions[:-1], lw=2, label='Precision')
ax.plot(thresholds, recalls[:-1], lw=2, label='Recall')
plt.vlines(0.5, 0, 1, linestyles='--', label='Threshold = 0.5')
ax.set_xlabel('Thresholds')
ax.legend(loc='best')
ax.set_ylim(bottom=0.85, top=1.02)
ax.grid()
fig.tight_layout()
plt.savefig('SVM-Precision-Recall.png', dpi=600)
plt.show()
# In[45]:
fig, ax = plt.subplots(figsize=(4.5,4.5))
ax.plot(precisions, recalls, lw=2, label='SVC')
default = np.argmin(np.abs(thresholds - 0.5))
ax.plot(precisions[default], recalls[default], '^', c='k', markersize=10,
label='Threshold = 0.5', fillstyle='none', mew=2)
ax.set_xlabel('Precision')
ax.set_ylabel('Recall')
ax.legend(loc='best')
ax.grid()
fig.tight_layout()
plt.show()
# In[46]:
# Average precision-recall score
y_test_score = svc2.predict_proba(X_test)[:,1]
average_precision = metrics.average_precision_score(y_test, y_test_score)
print('Average precision-recall score: {0:0.2f}'.format(average_precision))
# In[48]:
# Determine a class from the predicted probability by using
# the user-specified threshold value (not a default of 0.5)
THRESHOLD = 0.52 # Example
preds = np.where(y_test_score > THRESHOLD, 1, 0)
# In[49]:
pd.DataFrame(data=[metrics.accuracy_score(y_test, preds), metrics.recall_score(y_test, preds),
metrics.precision_score(y_test, preds), metrics.roc_auc_score(y_test, preds)],
index=["accuracy", "recall", "precision", "roc_auc_score"], columns=['Values'])
# ### ExtraTreesClassifier
# In[50]:
# ExtraTreesClassifier (ensemble learner) with grid search
# and cross-validation for hyper-parameters optimisation
parameters = {'n_estimators':[5, 10, 15, 20],
'criterion':['gini', 'entropy'],
'max_depth':[2, 5, None]}
trees = GridSearchCV(estimator=ExtraTreesClassifier(class_weight='balanced'), param_grid=parameters,
cv=3, scoring='f1', refit=True, n_jobs=-1, iid=False)
trees.fit(X_train, y_train)
# In[51]:
# Best model parameters
best_parameters = trees.best_params_
print("Best parameters: {}".format(trees.best_params_))
# In[52]:
scores = cross_val_score(trees, X_train, y_train, cv=3, scoring='f1')
print('Average score using 3-fold CV: {:g} +/- {:g}'.format(np.mean(scores), np.std(scores)))
# In[53]:
# classification report
pred = trees.predict(X_test)
print(metrics.classification_report(y_test, pred, target_names=labels))
# In[54]:
y_trees = trees.predict_proba(X_test)
y_t['tree'] = y_trees.argmax(axis=1)
# #### Feature importance analysis
# In[55]:
trees = ExtraTreesClassifier(**best_parameters, class_weight='balanced')
trees.fit(X_train, y_train)
trees_feature_importance = trees.feature_importances_
trees_feature_importance = 100.0 * (trees_feature_importance / trees_feature_importance.max())
sorted_idx_trees = np.argsort(trees_feature_importance)
position = np.arange(sorted_idx_trees.shape[0]) + .5
# In[56]:
# Select top features considering their relative importance
# Top features are those above some preselect threshold of relative importance
IMPORTANCE = 20. # relative importance threshold
TOPT = np.sum(trees_feature_importance[sorted_idx_trees] > IMPORTANCE)
print(TOPT)
top_features_trees = data.columns.values[sorted_idx_trees][-TOPT:][::-1]
print('Most relevant {:d} features according to the ExtraTreesClassifier:'.format(TOPT))
print(top_features_trees)
# In[57]:
# Plot relative feature importance
fig, ax = plt.subplots(figsize=(5,7))
ax.barh(position[-TOPT:], trees_feature_importance[sorted_idx_trees][-TOPT:],
align='center', color='navy', alpha=0.6)
plt.yticks(position[-TOPT:], data.columns[sorted_idx_trees][-TOPT:])
ax.set_xlabel('Feature Relative Importance')
ax.grid(which='major', axis='x')
plt.tight_layout()
plt.show()
# ### RandomForest classifier (ensemble learner)
# In[58]:
# RandomForestClassifier (ensemble learner for classification)
parameters = {'n_estimators':[10, 15, 20],
'criterion':['gini', 'entropy'],
'max_features':[4, 'auto'],
'max_depth':[2, None]}
# grid search and cross-validation for hyper-parameters optimisation
forest = GridSearchCV(estimator=RandomForestClassifier(class_weight='balanced'), param_grid=parameters,
cv=3, scoring='f1', refit=True, n_jobs=-1, iid=False)
forest.fit(X_train, y_train)
# In[59]:
best_forest_parameters = forest.best_params_
print("Best parameters: {}".format(forest.best_params_))
# In[60]:
scores = cross_val_score(forest, X_train, y_train, cv=3, scoring='f1')
print('Average score using 3-fold CV: {:g} +/- {:g}'.format(np.mean(scores), np.std(scores)))
# In[61]:
# classification report
pred = forest.predict(X_test)
print(metrics.classification_report(y_test, pred, target_names=labels))
# In[62]:
pd.DataFrame(data=[metrics.accuracy_score(y_test, pred), metrics.recall_score(y_test, pred),
metrics.precision_score(y_test, pred), metrics.roc_auc_score(y_test, pred)],
index=["accuracy", "recall", "precision", "roc_auc_score"], columns=['Values'])
# In[63]:
y_forest = forest.predict_proba(X_test)
y_t['forest'] = y_forest.argmax(axis=1)
# In[64]:
forest_top = RandomForestClassifier(**best_forest_parameters, class_weight='balanced')
forest_top.fit(X_train, y_train)
forest_feature_importance = forest_top.feature_importances_
forest_feature_importance = 100.0 * (forest_feature_importance / forest_feature_importance.max())
sorted_idx_forest = np.argsort(forest_feature_importance)
position_forest = np.arange(sorted_idx_forest.shape[0]) + .5
# In[65]:
FOPT = np.sum(forest_feature_importance[sorted_idx_forest] > IMPORTANCE)
top_features_forest = data.columns.values[sorted_idx_forest][-FOPT:][::-1]
print('Most relevant {:d} features according to the RandomForestClassifier:'.format(FOPT))
print(top_features_forest)
# In[66]:
# Plot relative feature importance
fig, ax = plt.subplots(figsize=(5,7))
ax.barh(position_forest[-FOPT:], forest_feature_importance[sorted_idx_forest][-FOPT:],
align='center', color='navy', alpha=0.6)
plt.yticks(position_forest[-FOPT:], data.columns[sorted_idx_forest][-FOPT:])
ax.set_xlabel('Feature Relative Importance')
ax.grid(which='major', axis='x')
plt.tight_layout()
plt.savefig('Forest-Features.png', dpi=600)
plt.show()
# In[67]:
duplicate_features = set(top_features_trees).intersection(set(top_features_forest))
print(duplicate_features)
# ### GradientBoosting classifier with feature importance analysis
# In[68]:
# Train & evaluate model performance
def train_and_evaluate(model, X, y, ns=3):
# k-fold cross validation iterator
cv = StratifiedKFold(n_splits=ns, shuffle=True)
scores = cross_val_score(model, X, y, cv=cv, scoring='f1') # scoring='f1'
print('Average score using {:d}-fold CV: {:g} +/- {:g}'.format(ns, np.mean(scores), np.std(scores)))
# In[69]:
# Gradient Boosting Classifier
clf_gb = GradientBoostingClassifier()
train_and_evaluate(clf_gb, X_train, y_train, 3)
clf_gb.fit(X_train, y_train)
# In[70]:
# Feature importance
feature_importance = clf_gb.feature_importances_
feature_importance = 100.0 * (feature_importance / feature_importance.max())
sorted_idx = np.argsort(feature_importance)
pos = np.arange(sorted_idx.shape[0]) + .5
# In[71]:
# Select top features
TOP = 10
top_features = data.columns.values[sorted_idx][-TOP:][::-1]
print('Most relevant {:d} features according to the GradientBoostingClassifier:'.format(TOP))
print(top_features)
# In[72]:
# Plot relative feature importance
fig, ax = plt.subplots(figsize=(5,5))
ax.barh(pos[-TOP:], feature_importance[sorted_idx][-TOP:], align='center', color='magenta', alpha=0.6)
plt.yticks(pos[-TOP:], data.columns[sorted_idx][-TOP:])
ax.set_xlabel('Feature Relative Importance')
ax.grid(which='major', axis='x')
plt.tight_layout()
plt.show()
# In[73]:
print(set(top_features_trees).intersection(set(top_features)))
# In[74]:
# Correlation matrix of selected features
pearson = data[data.columns[sorted_idx][-TOP:]].corr('pearson')
pearson.iloc[-1][:-1].sort_values()
# Correlation matrix as heatmap (seaborn)
fig, ax = plt.subplots(figsize=(6.5,5.5))
sns.heatmap(pearson, annot=True, annot_kws=dict(size=9), vmin=-1, vmax=1, ax=ax)
#plt.tight_layout()
plt.show()
# In[75]:
# classification report
pred = clf_gb.predict(X_test)
print(metrics.classification_report(y_test, pred, target_names=labels))
# In[76]:
# Predict on new data
y_gb = clf_gb.predict_proba(X_test)
y_t['gbr'] = y_gb.argmax(axis=1)
# #### Re-train SVM using only top features from the GradientBoosting classifier
# In[77]:
# IMPORTANT: NTOP <= TOP
NTOP = 2 # using only top 2 features!
# In[78]:
top_features_index = []
for name in top_features:
top_features_index.append(data.columns.get_loc(name))
# In[79]:
X_train_best = X_train[:,top_features_index[:NTOP]]
X_test_best = X_test[:,top_features_index[:NTOP]]
print(X_train_best.shape)
print(X_test_best.shape)
# In[80]:
# Optimize SVM with only TOP features
parameters = {'C':stats.expon(scale=100), 'gamma':stats.expon(scale=.1)}
svc_top = RandomizedSearchCV(estimator=svm.SVC(kernel='rbf', probability=True, class_weight='balanced'),
param_distributions=parameters, cv=3, n_iter=100, # 100 iterations!
scoring='f1', # notice the scoring method!
refit=True, n_jobs=-1, iid=False)
svc_top.fit(X_train_best, y_train)
# In[81]:
# Best model parameters
best_parameters = svc_top.best_params_
print("Best parameters from RandomSearch: {}".format(svc_top.best_params_))
# In[82]:
scores = cross_val_score(svc_top, X_train_best, y_train, cv=3, scoring='f1')
print('Average score using 3-fold CV: {:g} +/- {:g}'.format(np.mean(scores), np.std(scores)))
# In[153]:
pred = svc_top.predict(X_test_best)
pd.DataFrame(data=[metrics.accuracy_score(y_test, pred), metrics.recall_score(y_test, pred),
metrics.precision_score(y_test, pred), metrics.roc_auc_score(y_test, pred),
metrics.f1_score(y_test, pred)],
index=["accuracy", "recall", "precision", "roc_auc_score", 'f1-score'], columns=['Values'])
# #### Graphical visualization of the top two features
# In[83]:
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
# In[84]:
idx_stable = y_test==0
# In[85]:
# Ploting data without standard scaler transformer
fig, ax = plt.subplots(figsize=(5.5,5.5))
ax.scatter(X_test_best[idx_stable,0], X_test_best[idx_stable,1],
s=30, c='green', marker='o', edgecolors='k', alpha=0.5, label='Stable')
ax.scatter(X_test_best[~idx_stable,0], X_test_best[~idx_stable,1],
s=30, c='red', marker='o', edgecolors='k', alpha=0.5, label='Unstable')
ax.legend(loc='upper left')
ax.set_xlabel(top_features[0])
ax.set_ylabel(top_features[1])
ax.set_xlim(-5,1)
ax.set_ylim(-6,1)