-
Notifications
You must be signed in to change notification settings - Fork 3
/
Model_methods.py
executable file
·1191 lines (1065 loc) · 59.4 KB
/
Model_methods.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
#-*- coding: utf-8 -*-
import scipy
import numpy
import gensim
import sklearn
from sklearn.feature_extraction.text import CountVectorizer
from sklearn import svm
from sklearn.ensemble import GradientBoostingClassifier
import xgboost
from sklearn.linear_model import LogisticRegression
import lightgbm
import random
from Model_metrics import F_score_multiclass_Kfolds
from sklearn.model_selection import train_test_split
from scipy.special import softmax
##############################
### Support Vector Machine ###
##############################
def SVM_Train(x, y, test_size=None, shuffle=True, C=1.0, kernel ='linear', gamma=0.001):
'''
Trains a Support Vector Classifier using the data and test_size given to split it into training data and testing data.
Returns the classifier, and the predictions and true values for performance testing.
Parameters for train_test_split:
Originally, the method has more parameters available, but for simplicity I only use the following:
*arrays: sequence of indexables with same length / shape[0]
Allowed inputs are lists, numpy arrays, scipy-sparse matrices or pandas dataframes.
:param (array or indexable) x: input data
:param (array or indexable) y: target data
:param (float or int) test_size: If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split.
If int, represents the absolute number of test samples.
If None, the value is set to the complement of the train size.
If train_size is also None, it will be set to 0.25.
:param (bool) shuffle: Whether or not to shuffle the data before splitting. If shuffle=False then stratify must be None.
Parameters for SVC:
Originally, the method has more parameters available, but for simplicity I only use the following:
:param (float) C: Regularization parameter. The strength of the regularization is inversely proportional to C.
Must be strictly positive. The penalty is a squared l2 penalty.
:param (str) kernel: Specifies the kernel type to be used in the algorithm.
It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or a callable.
If none is given, 'linear' will be used. If a callable is given it is
used to pre-compute the kernel matrix from data matrices; that matrix
should be an array of shape ``(n_samples, n_samples)``.
:param (str or float) gamma: {'scale', 'auto'} or float, default=0.001. Kernel coefficient for 'rbf', 'poly' and 'sigmoid'
:return:
(SVC) clf: The SVC classifier object
(list) test_y: true values of y, used for model performance testing purposes
(list) y_preds: predicted values of y, used for model performance testing purposes
'''
if test_size>0:
train_x, test_x, train_y, test_y = train_test_split(x,y, test_size=test_size, shuffle=shuffle)
else:
train_x = x
train_y = y
test_x = []
test_y = []
testsize = len(test_y)
#Define classifier
clf = svm.SVC(
kernel = kernel,
C = C,
gamma = gamma
)
clf.fit(train_x,train_y)
#Test data
y_preds = []
if test_size>0:
for i in range(testsize):
predicted = clf.predict(test_x[i].reshape(1,-1))[0]
y_preds.append(predicted)
return clf, test_y, y_preds
def SVM_Kfolds(x, y, k, kernel='linear', C=1.0, gamma=0.001, multiclass=False, with_counts=True, with_lists=True, with_confusion_matrix=True):
'''
Trains a Support Vector Classifier using the shuffled and split data for each cycle of a K-folds cross validation process.
Then it calculates the performance of the SVC for each cycle and outputs the average performance results.
*arrays: sequence of indexables with same length / shape[0]
Allowed inputs are lists, numpy arrays, scipy-sparse matrices or pandas dataframes.
:param (array or indexable) x: input data
:param (array or indexable) y: target data
:param (int) k: Number of cycles for the k-folds cross validation. Test size is len(y)//k, and the data is shuffled each cycle.
Parameters for SVC:
Originally, the method has more parameters available, but for simplicity I only use the following:
:param (float) C: Regularization parameter. The strength of the regularization is inversely proportional to C.
Must be strictly positive. The penalty is a squared l2 penalty.
:param (str) kernel: Specifies the kernel type to be used in the algorithm.
It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or a callable.
If none is given, 'linear' will be used. If a callable is given it is
used to pre-compute the kernel matrix from data matrices; that matrix
should be an array of shape ``(n_samples, n_samples)``.
:param (str or float) gamma: {'scale', 'auto'} or float, default=0.001. Kernel coefficient for 'rbf', 'poly' and 'sigmoid'
Parameters for the F-score method:
:param (bool) multiclass: if true, uses the F_score_multiclass_Kfolds() method. If false, uses F_score_Kfolds() for output.
:param (bool) with_counts: if true, returns a list of the counts dictionaries as part of the resulting output for each cycle in the k-folds operation.
:param (bool) with_lists: if true, returns the list of values used to calculate the average and standard deviation of each result.
:param (bool) with_confusion_matrix: if true, returns the confusion matrix used in the multi-class analysis.
:return:
if multiclass:
results dictionary with shape:
{
0: {
"precision":{
"average":_,
"std": _,
"list": [...],
},
"recall": {
"average":_,
"std": _,
"list": [...],
},
"accuracy": {
"average":_,
"std": _,
"list": [...],
},
"F1": {
"average":_,
"std": _,
"list": [...],
},
"counts": [
{
"CP":_,
"TP":_,
"TN":_,
"IP":_,
"FP":_,
"FN":_
}, {...} ...
]
"confusion_matrix": {
"sum":_,
"average":_,
"std":_,
"list": [...]
}
},
1: {...},
2: {...},
...
class_index_n: {...}
}
if not multiclass:
results dictionary with shape:
{
"precision":{
"average":_,
"std": _,
"list": [...],
},
"recall": {
"average":_,
"std": _,
"list": [...],
},
"accuracy": {
"average":_,
"std": _,
"list": [...],
},
"F1": {
"average":_,
"std": _,
"list": [...],
},
"counts": [
{
"CP":_,
"TP":_,
"TN":_,
"IP":_,
"FP":_,
"FN":_
}, {...} ...
]
}
'''
test_size = len(y)//k
y_pred_list = []
true_ys_list = []
for t in range(k):
clf, test_y, y_preds = SVM_Train(x, y, test_size, shuffle=True, kernel=kernel, C=C, gamma=gamma)
y_pred_list.append(y_preds)
true_ys_list.append(test_y)
if multiclass:
results = F_score_multiclass_Kfolds(true_ys_list, y_pred_list, with_counts=with_counts, with_lists=with_lists, with_confusion_matrix=with_confusion_matrix)
else:
results = F_score_Kfolds(true_ys_list, y_pred_list, with_counts=with_counts, with_lists=with_lists)
return results
def SVM_weights_trained(clf,keyword_list, min_df=1, token_pattern='(?u)\\b\\w+\\b'):
'''
For knowing the weight vector in an SVM used in text classification with the Bag Of Words method.
Input a trained SVC classifier, the keyword list used to classify text and the settings used in the BOW process.
Words with stronger weight will be closer to the dividing hyperplane, and will have a stronger impact on the decision for either class.
High weighted keywords can be interpreted as vital for classification.
:param (SVC) clf: SVC classifier object.
:param (list of strings) keyword_list: list of keywords used in the Bag Of Words as features in the training process.
Parameters of the CountVectorizer:
:param (float [0.0, 1.0] or int) min_df: When building the vocabulary ignore terms that have a document frequency strictly lower than the given threshold. This value is also called cut-off in the literature. If float, the parameter represents a proportion of documents, integer absolute counts. This parameter is ignored if vocabulary is not None.
:param (string) token_pattern: Regular expression denoting what constitutes a “token”, only used if analyzer == 'word'. The default regexp select tokens of 2 or more alphanumeric characters (punctuation is completely ignored and always treated as a token separator).
:return:
influences: zipped list of feature names and weight values
'''
weights = clf.coef_.tolist()[0]
vectorizer = CountVectorizer(min_df=min_df, token_pattern=token_pattern)
IM = vectorizer.fit_transform(keyword_list)
feature_names = vectorizer.get_feature_names()
influences = list(zip(feature_names, weights))
return influences
#################################
### Gradient Boosting Machine ###
#################################
def GBM_Train(x, y, test_size, shuffle=True, n_estimators=100, subsample=0.8, max_depth=3):
'''
Trains a Gradient Boosting Machine using the data and test_size given to split it into training data and testing data.
Returns the classifier, and the predictions and true values for performance testing.
Parameters for train_test_split:
Originally, the method has more parameters available, but for simplicity I only use the following:
*arrays: sequence of indexables with same length / shape[0]
Allowed inputs are lists, numpy arrays, scipy-sparse matrices or pandas dataframes.
:param (array or indexable) x: input data
:param (array or indexable) y: target data
:param (float or int) test_size: If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split.
If int, represents the absolute number of test samples.
If None, the value is set to the complement of the train size.
If train_size is also None, it will be set to 0.25.
:param (bool) shuffle: Whether or not to shuffle the data before splitting. If shuffle=False then stratify must be None.
Parameters for GradientBoostingClassifier:
Originally, the method has more parameters available, but for simplicity I only use the following:
:param (int) n_estimators: The number of boosting stages to perform. Gradient boosting is fairly robust to over-fitting so a large number usually results in better performance.
:param (float) subsample: The fraction of samples to be used for fitting the individual base learners.
If smaller than 1.0 this results in Stochastic Gradient Boosting.
subsample interacts with the parameter n_estimators.
Choosing subsample < 1.0 leads to a reduction of variance and an increase in bias.
:param (int) max_depth: maximum depth of the individual regression estimators.
The maximum depth limits the number of nodes in the tree.
Tune this parameter for best performance; the best value depends on the interaction of the input variables.
:return:
(GBC) clf: The GradientBoostingClassifier object
(list) test_y: true values of y, used for model performance testing purposes
(list) y_preds: predicted values of y, used for model performance testing purposes
'''
if test_size>0:
train_x, test_x, train_y, test_y = train_test_split(x,y, test_size=test_size, shuffle=shuffle)
else:
train_x = x
train_y = y
test_x = []
test_y = []
testsize = len(test_y)
#Define classifier
clf = GradientBoostingClassifier(n_estimators=n_estimators, subsample=subsample, max_depth=max_depth)
clf.fit(train_x,train_y)
#Test data
y_preds = []
if test_size>0:
for i in range(testsize):
predicted = clf.predict(test_x[i].reshape(1,-1))[0]
y_preds.append(predicted)
return clf, test_y, y_preds
def GBM_Kfolds(x, y, k, n_estimators=100, subsample=0.8, max_depth=3, multiclass=False, with_counts= True, with_lists= True, with_confusion_matrix=True):
'''
Trains a Gradient Boosting Classifier using the shuffled and split data for each cycle of a K-folds cross validation process.
Then it calculates the performance of the GBC for each cycle and outputs the average performance results.
*arrays: sequence of indexables with same length / shape[0]
Allowed inputs are lists, numpy arrays, scipy-sparse matrices or pandas dataframes.
:param (array or indexable) x: input data
:param (array or indexable) y: target data
:param (int) k: Number of cycles for the k-folds cross validation. Test size is len(y)//k, and the data is shuffled each cycle.
Parameters for GradientBoostingClassifier:
Originally, the method has more parameters available, but for simplicity I only use the following:
:param (int) n_estimators: The number of boosting stages to perform. Gradient boosting is fairly robust to over-fitting so a large number usually results in better performance.
:param (float) subsample: The fraction of samples to be used for fitting the individual base learners.
If smaller than 1.0 this results in Stochastic Gradient Boosting.
subsample interacts with the parameter n_estimators.
Choosing subsample < 1.0 leads to a reduction of variance and an increase in bias.
:param (int) max_depth: maximum depth of the individual regression estimators.
The maximum depth limits the number of nodes in the tree.
Tune this parameter for best performance; the best value depends on the interaction of the input variables.
Parameters for the F-score method:
:param (bool) multiclass: if true, uses the F_score_multiclass_Kfolds() method. If false, uses F_score_Kfolds() for output.
:param (bool) with_counts: if true, returns a list of the counts dictionaries as part of the resulting output for each cycle in the k-folds operation.
:param (bool) with_lists: if true, returns the list of values used to calculate the average and standard deviation of each result.
:param (bool) with_confusion_matrix: if true, returns the confusion matrix used in the multi-class analysis.
:return:
if multiclass:
results dictionary with shape:
{
0: {
"precision":{
"average":_,
"std": _,
"list": [...],
},
"recall": {
"average":_,
"std": _,
"list": [...],
},
"accuracy": {
"average":_,
"std": _,
"list": [...],
},
"F1": {
"average":_,
"std": _,
"list": [...],
},
"counts": [
{
"CP":_,
"TP":_,
"TN":_,
"IP":_,
"FP":_,
"FN":_
}, {...} ...
]
"confusion_matrix": {
"sum":_,
"average":_,
"std":_,
"list": [...]
}
},
1: {...},
2: {...},
...
class_index_n: {...}
}
if not multiclass:
results dictionary with shape:
{
"precision":{
"average":_,
"std": _,
"list": [...],
},
"recall": {
"average":_,
"std": _,
"list": [...],
},
"accuracy": {
"average":_,
"std": _,
"list": [...],
},
"F1": {
"average":_,
"std": _,
"list": [...],
},
"counts": [
{
"CP":_,
"TP":_,
"TN":_,
"IP":_,
"FP":_,
"FN":_
}, {...} ...
]
}
'''
test_size = len(y)//k
y_pred_list = []
true_ys_list = []
for t in range(k):
clf, test_y, y_preds = GBM_Train(x, y, test_size, shuffle=True, n_estimators=n_estimators, subsample=subsample, max_depth=max_depth)
y_pred_list.append(y_preds)
true_ys_list.append(test_y)
if multiclass:
results = F_score_multiclass_Kfolds(true_ys_list, y_pred_list, with_counts=with_counts, with_lists=with_lists, with_confusion_matrix=with_confusion_matrix)
else:
results = F_score_Kfolds(true_ys_list, y_pred_list, with_counts=with_counts, with_lists=with_lists)
return results
########################
### XGBoost Learning ###
########################
# http://xgboost.readthedocs.io/en/latest/parameter.html
def XGBoost_Train(x, y, test_size, shuffle=True, probability_cutoff=0.5, max_depth=3, learning_rate=0.1, eta=0.1, n_estimators=100, verbosity=1, objective='binary:logistic', min_child_weight=1, num_round=2):
'''
Trains an XGBoost using the data and test_size given to split it into training data and testing data.
Returns the classifier, and the predictions and true values for performance testing.
Parameters for train_test_split:
Originally, the method has more parameters available, but for simplicity I only use the following:
*arrays: sequence of indexables with same length / shape[0]
Allowed inputs are lists, numpy arrays, scipy-sparse matrices or pandas dataframes.
:param (array or indexable) x: input data
:param (array or indexable) y: target data
:param (float or int) test_size: If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split.
If int, represents the absolute number of test samples.
If None, the value is set to the complement of the train size.
If train_size is also None, it will be set to 0.25.
:param (bool) shuffle: Whether or not to shuffle the data before splitting. If shuffle=False then stratify must be None.
Parameters for parse_predictions_binary_Probability_Cutoff:
:param (float) probability_cutoff: Probability cutoff point for binary class decisions.
XGBoost returns probabilities of belonging to either class. In the case of binary predictions, it just returns one probability.
To be able to run performance tests, the cutoff decides it is class 1 when above it, or class 0 when below it.
Parameters for XGBoost:
Originally, the method has more parameters available, but for simplicity I only use the following:
:param (int) max_depth: Maximum depth of a tree. Increasing this value will make the model more complex and more likely to overfit. 0 is only accepted in lossguided growing policy when tree_method is set as hist and it indicates no limit on depth. Beware that XGBoost aggressively consumes memory when training a deep tree.
:param (float) learning_rate (alias eta): Step size shrinkage used in update to prevents overfitting. After each boosting step, we can directly get the weights of new features, and eta shrinks the feature weights to make the boosting process more conservative.
:param (int) n_estimators: Number of gradient boosted trees. Equivalent to number of boosting rounds.
:param (int) verbosity: Verbosity of printing messages. Valid values are 0 (silent), 1 (warning), 2 (info), 3 (debug). Sometimes XGBoost tries to change configurations based on heuristics, which is displayed as warning message. If there’s unexpected behaviour, please try to increase value of verbosity.
:param (str) objective: There's more options in XGBoost, but since I only know binary or multiclass uses, my method only accepts these:
binary:logistic: logistic regression for binary classification, output probability
binary:logitraw: logistic regression for binary classification, output score before logistic transformation
binary:hinge: hinge loss for binary classification. This makes predictions of 0 or 1, rather than producing probabilities.
multi:softmax: set XGBoost to do multiclass classification using the softmax objective, you also need to set num_class(number of classes)
multi:softprob: same as softmax, but output a vector of ndata * nclass, which can be further reshaped to ndata * nclass matrix. The result contains predicted probability of each data point belonging to each class.
:param (int) min_child_weight: Minimum sum of instance weight (hessian) needed in a child. If the tree partition step results in a leaf node with the sum of instance weight less than min_child_weight, then the building process will give up further partitioning. In linear regression task, this simply corresponds to minimum number of instances needed to be in each node. The larger min_child_weight is, the more conservative the algorithm will be.
:param (int) num_round: The number of rounds for boosting
:return:
(XGBoost) clf: The XGBoost object
(list) test_y: true values of y, used for model performance testing purposes
(list) y_preds: predicted values of y, used for model performance testing purposes
'''
if test_size>0:
train_x, test_x, train_y, test_y = train_test_split(x,y, test_size=test_size, shuffle=shuffle)
else:
train_x = x
train_y = y
test_x = []
test_y = []
#Define classifier
# specify parameters via map
param = {'max_depth':max_depth, 'learning_rate':learning_rate, 'eta':eta, 'verbosity':verbosity, 'objective':objective, 'n_estimators':n_estimators}
dtrain = xgboost.DMatrix(train_x, label=train_y)
clf = xgboost.train(param, dtrain, num_round)
#Test data
if test_size>0:
dtest = xgboost.DMatrix(test_x)
predicted_probs = clf.predict(dtest)
if param["objective"].startswith("binary"):
y_preds = parse_predictions_binary_Probability_Cutoff(predicted_probs, probability_cutoff=probability_cutoff)
elif param["objective"].startswith("multi"):
y_preds = predicted_probs.argmax(axis=1)
else:
y_preds = []
else:
y_preds = []
return clf, test_y, y_preds
def XGBoost_Kfolds(x, y, k, probability_cutoff=0.5, max_depth=3, learning_rate=0.1, n_estimators=100, eta=1, silent=1, objective='binary:logistic', min_child_weight=1, num_round=2, with_counts=True, with_lists=True, with_confusion_matrix=True):
'''
Trains an XGBoost using the shuffled and split data for each cycle of a K-folds cross validation process.
Then it calculates the performance of the GBC for each cycle and outputs the average performance results.
*arrays: sequence of indexables with same length / shape[0]
Allowed inputs are lists, numpy arrays, scipy-sparse matrices or pandas dataframes.
:param (array or indexable) x: input data
:param (array or indexable) y: target data
:param (int) k: Number of cycles for the k-folds cross validation. Test size is len(y)//k, and the data is shuffled each cycle.
Parameters for parse_predictions_binary_Probability_Cutoff:
:param (float) probability_cutoff: Probability cutoff point for binary class decisions.
XGBoost returns probabilities of belonging to either class. In the case of binary predictions, it just returns one probability.
To be able to run performance tests, the cutoff decides it is class 1 when above it, or class 0 when below it.
Parameters for XGBoost:
Originally, the method has more parameters available, but for simplicity I only use the following:
:param (int) max_depth: Maximum depth of a tree. Increasing this value will make the model more complex and more likely to overfit. 0 is only accepted in lossguided growing policy when tree_method is set as hist and it indicates no limit on depth. Beware that XGBoost aggressively consumes memory when training a deep tree.
:param (float) learning_rate (alias eta): Step size shrinkage used in update to prevents overfitting. After each boosting step, we can directly get the weights of new features, and eta shrinks the feature weights to make the boosting process more conservative.
:param (int) n_estimators: Number of gradient boosted trees. Equivalent to number of boosting rounds.
:param (int) verbosity: Verbosity of printing messages. Valid values are 0 (silent), 1 (warning), 2 (info), 3 (debug). Sometimes XGBoost tries to change configurations based on heuristics, which is displayed as warning message. If there’s unexpected behaviour, please try to increase value of verbosity.
:param (str) objective: There's more options in XGBoost, but since I only know binary or multiclass uses, my method only accepts these:
binary:logistic: logistic regression for binary classification, output probability
binary:logitraw: logistic regression for binary classification, output score before logistic transformation
binary:hinge: hinge loss for binary classification. This makes predictions of 0 or 1, rather than producing probabilities.
multi:softmax: set XGBoost to do multiclass classification using the softmax objective, you also need to set num_class(number of classes)
multi:softprob: same as softmax, but output a vector of ndata * nclass, which can be further reshaped to ndata * nclass matrix. The result contains predicted probability of each data point belonging to each class.
:param (int) min_child_weight: Minimum sum of instance weight (hessian) needed in a child. If the tree partition step results in a leaf node with the sum of instance weight less than min_child_weight, then the building process will give up further partitioning. In linear regression task, this simply corresponds to minimum number of instances needed to be in each node. The larger min_child_weight is, the more conservative the algorithm will be.
:param (int) num_round: The number of rounds for boosting
Parameters for the F-score method:
:param (bool) multiclass: if true, uses the F_score_multiclass_Kfolds() method. If false, uses F_score_Kfolds() for output.
:param (bool) with_counts: if true, returns a list of the counts dictionaries as part of the resulting output for each cycle in the k-folds operation.
:param (bool) with_lists: if true, returns the list of values used to calculate the average and standard deviation of each result.
:param (bool) with_confusion_matrix: if true, returns the confusion matrix used in the multi-class analysis.
:return:
if objective starts with multi (multiclass):
results dictionary with shape:
{
0: {
"precision":{
"average":_,
"std": _,
"list": [...],
},
"recall": {
"average":_,
"std": _,
"list": [...],
},
"accuracy": {
"average":_,
"std": _,
"list": [...],
},
"F1": {
"average":_,
"std": _,
"list": [...],
},
"counts": [
{
"CP":_,
"TP":_,
"TN":_,
"IP":_,
"FP":_,
"FN":_
}, {...} ...
]
"confusion_matrix": {
"sum":_,
"average":_,
"std":_,
"list": [...]
}
},
1: {...},
2: {...},
...
class_index_n: {...}
}
if objective starts with binary:
results dictionary with shape:
{
"precision":{
"average":_,
"std": _,
"list": [...],
},
"recall": {
"average":_,
"std": _,
"list": [...],
},
"accuracy": {
"average":_,
"std": _,
"list": [...],
},
"F1": {
"average":_,
"std": _,
"list": [...],
},
"counts": [
{
"CP":_,
"TP":_,
"TN":_,
"IP":_,
"FP":_,
"FN":_
}, {...} ...
]
}
'''
test_size = len(y)//k
y_pred_list = []
true_ys_list = []
for t in range(k):
clf, test_y, y_preds = XGBoost_Train(x, y, test_size, shuffle=True, probability_cutoff=probability_cutoff, max_depth=max_depth, learning_rate=learning_rate, n_estimators=n_estimators, eta=eta, silent=silent, objective=objective, min_child_weight=min_child_weight, num_round=num_round)
y_pred_list.append(y_preds)
true_ys_list.append(test_y)
if objective.startswith("multi"):
results = F_score_multiclass_Kfolds(true_ys_list, y_pred_list, with_counts=with_counts, with_lists=with_lists, with_confusion_matrix=with_confusion_matrix)
elif objective.startswith("binary"):
results = F_score_Kfolds(true_ys_list, y_pred_list, with_counts=with_counts, with_lists=with_lists)
else:
results = []
return results
#########################
### LightGBM Learning ###
#########################
def LightGBM_train(x, y, test_size = 0.1, shuffle=True, binary=True, multiclass=False, n_class=2, params = None):
'''
Trains a LightGBM using the data and test_size given to split it into training data and testing data.
Returns the classifier, and the predictions and true values for performance testing.
The method has some default parameters, but they can be overwritten by the dictionary params.
Parameters for train_test_split:
Originally, the method has more parameters available, but for simplicity I only use the following:
*arrays: sequence of indexables with same length / shape[0]
Allowed inputs are lists, numpy arrays, scipy-sparse matrices or pandas dataframes.
:param (array or indexable) x: input data
:param (array or indexable) y: target data
:param (float or int) test_size: If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split.
If int, represents the absolute number of test samples.
If None, the value is set to the complement of the train size.
If train_size is also None, it will be set to 0.25.
:param (bool) shuffle: Whether or not to shuffle the data before splitting. If shuffle=False then stratify must be None.
Parameter for binary or multiclass decision:
:param (bool) binary: Vestigial parameter. if false, it sets parameters for LightGBM to use several classes.
It is the opposite of the newer param multiclass, but some old projects are using this older param.
:param (bool) multiclass: if true, it sets parameters for LightGBM to use several classes.
:param (int) n_class: if multiclass, will pass to LightGBM the number of classes to use.
Parameters for LightGBM:
Originally, the method has more parameters available, but for simplicity I only use the following:
:param (dict) params: Parameters for LightGBM. Consult https://lightgbm.readthedocs.io/en/latest/Parameters.html
:return:
(LightGBM) clf: The LightGBM object
(list) test_y: true values of y, used for model performance testing purposes
(list) y_preds: predicted values of y, used for model performance testing purposes
'''
if binary and multiclass:
binary=False
if not binary and not multiclass:
multiclass=True
x = numpy.array(x)
y = numpy.array(y)
if test_size>0:
train_x, test_x, train_y, test_y = train_test_split(x,y, test_size=test_size, shuffle=shuffle)
else:
train_x = numpy.array(x)
train_y = numpy.array(y)
test_x = numpy.array([])
test_y = numpy.array([])
train_data = lightgbm.Dataset(train_x, label=train_y)
validation_data = train_data.create_valid(test_x, label=test_y)
#Define classifier
default_params = {
"objective": "multiclass",
"metric": "multi_logloss",
"num_class": 2,
"learning_rate": 0.05,
"min_data": 10,
"num_leaves": 31,
"verbose": -1,
"num_threads": 1,
"max_bin": 255
}
if multiclass:
default_params["objective"]="multiclass"
default_params["num_class"]= n_class
default_params["metric"]="multi_logloss"
params = default_params.update(params)
if test_size>0:
clf = lightgbm.train(params, train_data, valid_sets=validation_data)
else:
clf = lightgbm.train(params, train_data)
# Test data
if test_size>0:
predicted_probs = clf.predict(test_x, num_iteration=clf.best_iteration)
# LightGBM's prediction output is always multi-class shaped even in binary, so:
y_preds = predicted_probs.argmax(axis=1)
else:
y_preds=[]
return clf, test_y, y_preds
def LightGBM_Kfolds(x, y, k, binary=True, multiclass=False, n_class=2, params = None, with_counts=True, with_lists=True, with_confusion_matrix=True):
'''
Trains an LightGBM using the shuffled and split data for each cycle of a K-folds cross validation process.
The method has some default parameters, but they can be overwritten by the dictionary params.
Then it calculates the performance of the GBC for each cycle and outputs the average performance results.
*arrays: sequence of indexables with same length / shape[0]
Allowed inputs are lists, numpy arrays, scipy-sparse matrices or pandas dataframes.
:param (array or indexable) x: input data
:param (array or indexable) y: target data
:param (int) k: Number of cycles for the k-folds cross validation. Test size is len(y)//k, and the data is shuffled each cycle.
Parameter for binary or multiclass decision:
:param (bool) binary: Vestigial parameter. if false, it sets parameters for LightGBM to use several classes.
It is the opposite of the newer param multiclass, but some old projects are using this older param.
:param (bool) multiclass: if true, it sets parameters for LightGBM to use several classes.
:param (int) n_class: if multiclass, will pass to LightGBM the number of classes to use.
Parameters for LightGBM:
Originally, the method has more parameters available, but for simplicity I only use the following:
:param (dict) params: Parameters for LightGBM. Consult https://lightgbm.readthedocs.io/en/latest/Parameters.html
Parameters for the F-score method:
:param (bool) multiclass: if true, uses the F_score_multiclass_Kfolds() method. If false, uses F_score_Kfolds() for output.
:param (bool) with_counts: if true, returns a list of the counts dictionaries as part of the resulting output for each cycle in the k-folds operation.
:param (bool) with_lists: if true, returns the list of values used to calculate the average and standard deviation of each result.
:param (bool) with_confusion_matrix: if true, returns the confusion matrix used in the multi-class analysis.
:return:
if objective starts with multi (multiclass):
results dictionary with shape:
{
0: {
"precision":{
"average":_,
"std": _,
"list": [...],
},
"recall": {
"average":_,
"std": _,
"list": [...],
},
"accuracy": {
"average":_,
"std": _,
"list": [...],
},
"F1": {
"average":_,
"std": _,
"list": [...],
},
"counts": [
{
"CP":_,
"TP":_,
"TN":_,
"IP":_,
"FP":_,
"FN":_
}, {...} ...
]
"confusion_matrix": {
"sum":_,
"average":_,
"std":_,
"list": [...]
}
},
1: {...},
2: {...},
...
class_index_n: {...}
}
if objective starts with binary:
results dictionary with shape:
{
"precision":{
"average":_,
"std": _,
"list": [...],
},
"recall": {
"average":_,
"std": _,
"list": [...],
},
"accuracy": {
"average":_,
"std": _,
"list": [...],
},
"F1": {
"average":_,
"std": _,
"list": [...],
},
"counts": [
{
"CP":_,
"TP":_,
"TN":_,
"IP":_,
"FP":_,
"FN":_
}, {...} ...
]
}
'''
if binary and multiclass:
binary=False
if not binary and not multiclass:
multiclass=True
test_size = len(y)//k
y_pred_list = []
true_ys_list = []
for t in range(k):
clf, test_y, y_preds = LightGBM_train(x, y, test_size, shuffle=True, binary=binary, multiclass=multiclass, n_class=n_class, params=params)
y_pred_list.append(y_preds)
true_ys_list.append(test_y)
if multiclass:
results = F_score_multiclass_Kfolds(true_ys_list, y_pred_list, with_counts=with_counts, with_lists=with_lists, with_confusion_matrix=with_confusion_matrix)
else:
results = F_score_Kfolds(true_ys_list, y_pred_list, with_counts=with_counts, with_lists=with_lists)
return results
def LightGBM_importance(clf, feature_names):
'''
For knowing the importance vector in a LightGBM with their feature names.
:param (LightGBM object) clf: The LightGBM object
:param (list of strings) feature_names: List of features used in the LightGBM training
:return:
importance_list: zipped list of feature names and importance values
'''
importance = clf.feature_importance()
importance_list = list(zip(feature_names, importance))
return importance_list
###########################
### Logistic Regression ###
###########################
def LogisticRegression(x,y, test_size, shuffle=True):
'''
Performs a logistic regression using the data and test_size given to split it into training data and testing data.
Returns the classifier, and the predictions and true values for performance testing.
Parameters for train_test_split:
Originally, the method has more parameters available, but for simplicity I only use the following:
*arrays: sequence of indexables with same length / shape[0]
Allowed inputs are lists, numpy arrays, scipy-sparse matrices or pandas dataframes.
:param (array or indexable) x: input data
:param (array or indexable) y: target data
:param (float or int) test_size: If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split.
If int, represents the absolute number of test samples.
If None, the value is set to the complement of the train size.
If train_size is also None, it will be set to 0.25.
:param (bool) shuffle: Whether or not to shuffle the data before splitting. If shuffle=False then stratify must be None.
:return:
(LogisticRegression) clf: The LogisticRegression classifier object
(list) test_y: true values of y, used for model performance testing purposes
(list) y_preds: predicted values of y, used for model performance testing purposes
'''
if test_size>0:
train_x, test_x, train_y, test_y = train_test_split(x,y, test_size=test_size, shuffle=shuffle)
else:
train_x = x
train_y = y
test_x = []
test_y = []
testsize = len(test_y)
#Define classifier
clf = LogisticRegression()
clf.fit(train_x,train_y)
#Test data
y_preds = []
if test_size>0:
for i in range(1, testsize+1):
predicted = clf.predict(test_x[i].reshape(1,-1))[0]
y_preds.append(predicted)
return clf, test_y, y_preds
def LogisticRegression_Kfolds(x,y,k, multiclass=False, with_counts=True, with_lists=True, with_confusion_matrix=True):
'''
Performs a logistic regression using the shuffled and split data for each cycle of a K-folds cross validation process.
Then it calculates the performance of the logistic regression for each cycle and outputs the average performance results.
*arrays: sequence of indexables with same length / shape[0]
Allowed inputs are lists, numpy arrays, scipy-sparse matrices or pandas dataframes.
:param (array or indexable) x: input data
:param (array or indexable) y: target data
:param (int) k: Number of cycles for the k-folds cross validation. Test size is len(y)//k, and the data is shuffled each cycle.
Parameters for the F-score method:
:param (bool) multiclass: if true, uses the F_score_multiclass_Kfolds() method. If false, uses F_score_Kfolds() for output.
:param (bool) with_counts: if true, returns a list of the counts dictionaries as part of the resulting output for each cycle in the k-folds operation.
:param (bool) with_lists: if true, returns the list of values used to calculate the average and standard deviation of each result.
:param (bool) with_confusion_matrix: if true, returns the confusion matrix used in the multi-class analysis.
:return:
if multiclass:
results dictionary with shape:
{
0: {
"precision":{
"average":_,
"std": _,
"list": [...],
},
"recall": {
"average":_,
"std": _,
"list": [...],
},
"accuracy": {
"average":_,
"std": _,
"list": [...],
},
"F1": {
"average":_,
"std": _,
"list": [...],
},
"counts": [
{
"CP":_,
"TP":_,
"TN":_,
"IP":_,
"FP":_,
"FN":_
}, {...} ...
]
"confusion_matrix": {
"sum":_,
"average":_,
"std":_,
"list": [...]
}
},
1: {...},
2: {...},
...
class_index_n: {...}
}
if not multiclass:
results dictionary with shape:
{
"precision":{
"average":_,
"std": _,
"list": [...],
},
"recall": {
"average":_,
"std": _,
"list": [...],
},
"accuracy": {
"average":_,
"std": _,
"list": [...],
},
"F1": {
"average":_,
"std": _,