-
Notifications
You must be signed in to change notification settings - Fork 7
/
kgrid_r0.py
1326 lines (998 loc) · 39.7 KB
/
kgrid_r0.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
"""
grid search codes for machine learning
Chemistry toolbox such as RDKit is not used.
"""
from sklearn import model_selection, linear_model, svm, metrics
import numpy as np
import pandas as pd
from operator import itemgetter
import jutil
from jsklearn import binary_model
def gs_np(X, Y, alphas_log=(-3, 3, 7), method = "Lasso", n_splits=5, disp = False):
"""
Return
------
df, pd.DataFrame
All results are included in df
df_avg, pd.DataFrame
Average results are included in df_avg
df_best, pd.DataFrame
The best of the average results is df_best
Usage
-----
df, df_avg, df_best = gs_np( X, Y)
"""
df_l = list()
df_avg_l = list()
for (alpha_idx, alpha) in enumerate( np.logspace(*alphas_log)):
model = getattr(linear_model, method)(alpha=alpha)
kf5_c = model_selection.KFold( n_splits=n_splits, shuffle=True)
kf5 = kf5_c.split( X)
r2_l = []
for train, test in kf5:
model.fit( X[train,:], Y[train,:])
r2 = model.score( X[test,:], Y[test,:])
r2_l.append( r2)
# make a dataframe
df_i = pd.DataFrame()
df_i["r2"] = r2_l
df_i["unit"] = range( len( r2_l))
df_i["method"] = method
df_i["n_splits"] = n_splits
df_i["alpha"] = alpha
df_i["alpha_idx"] = alpha_idx
df_l.append( df_i)
df_avg_i = pd.DataFrame()
df_avg_i["E[r2]"] = [np.mean( r2_l)]
df_avg_i["std(r2)"] = [np.std( r2_l)]
df_avg_i["method"] = method
df_avg_i["n_splits"] = n_splits
df_avg_i["alpha"] = alpha
df_avg_i["alpha_idx"] = alpha_idx
df_avg_l.append( df_avg_i)
if disp:
print( "alpha=", alpha)
print( r2_l)
print('Average, std=', np.mean(r2_l), np.std(r2_l))
print('-------------')
df = pd.concat( df_l, ignore_index=True)
df_avg = pd.concat( df_avg_l, ignore_index=True)
# dataframe for the best
idx_best = np.argmax( df_avg["E[r2]"].values)
df_best = df_avg.loc[[idx_best], :].copy()
return df, df_avg, df_best
def gs_numpy( method, X, Y, alphas_log = (-1, 1, 9), n_splits=5, n_jobs = -1, disp = True):
"""
Grid search method with numpy array of X and Y
Previously, np.mat are used for compatible with Matlab notation.
"""
if disp:
print( X.shape, Y.shape)
clf = getattr( linear_model, method)()
parmas = {'alpha': np.logspace( *alphas_log)}
kf5_c = model_selection.KFold( n_splits = n_splits, shuffle=True)
#kf5 = kf5_c.split( X)
gs = model_selection.GridSearchCV( clf, parmas, scoring = 'r2', cv = kf5_c, n_jobs = n_jobs)
gs.fit( X, Y)
return gs
def gs_Lasso( xM, yV, alphas_log = (-1, 1, 9), n_splits=5, n_jobs = -1):
print(xM.shape, yV.shape)
clf = linear_model.Lasso()
#parmas = {'alpha': np.logspace(1, -1, 9)}
parmas = {'alpha': np.logspace( *alphas_log)}
kf5_c = model_selection.KFold( n_splits = n_splits, shuffle=True)
#kf5 = kf5_c.split( xM)
gs = model_selection.GridSearchCV( clf, parmas, scoring = 'r2', cv = kf5_c, n_jobs = n_jobs)
gs.fit( xM, yV)
return gs
def gs_Lasso_norm( xM, yV, alphas_log = (-1, 1, 9)):
print(xM.shape, yV.shape)
clf = linear_model.Lasso( normalize = True)
#parmas = {'alpha': np.logspace(1, -1, 9)}
parmas = {'alpha': np.logspace( *alphas_log)}
kf5_c = model_selection.KFold( n_splits = 5, shuffle=True)
#kf5 = kf5_c.split( xM)
gs = model_selection.GridSearchCV( clf, parmas, scoring = 'r2', cv = kf5_c, n_jobs = -1)
gs.fit( xM, yV)
return gs
def gs_Lasso_kf( xM, yV, alphas_log_l):
kf5_ext_c = model_selection.KFold( n_splits = 5, shuffle=True)
kf5_ext = kf5_ext_c.split( xM)
score_l = []
for ix, (tr, te) in enumerate( kf5_ext):
print('{}th fold external validation stage ============================'.format( ix + 1))
xM_in = xM[ tr, :]
yV_in = yV[ tr, 0]
print('First Lasso Stage')
gs1 = gs_Lasso( xM_in, yV_in, alphas_log_l[0])
print('Best score:', gs1.best_score_)
print('Best param:', gs1.best_params_)
print(gs1.grid_scores_)
nz_idx = gs1.best_estimator_.sparse_coef_.indices
xM_in_nz = xM_in[ :, nz_idx]
print('Second Lasso Stage')
gs2 = gs_Lasso( xM_in_nz, yV_in, alphas_log_l[1])
print('Best score:', gs2.best_score_)
print('Best param:', gs2.best_params_)
print(gs2.grid_scores_)
print('External Validation Stage')
xM_out = xM[ te, :]
yV_out = yV[ te, 0]
xM_out_nz = xM_out[:, nz_idx]
score = gs2.score( xM_out_nz, yV_out)
print(score)
score_l.append( score)
print('')
print('all scores:', score_l)
print('average scores:', np.mean( score_l))
return score_l
def gs_Lasso_kf_ext( xM, yV, alphas_log_l):
kf5_ext_c = model_selection.KFold( n_splits = 5, shuffle=True)
kf5_ext = kf5_ext_c.split( xM)
score_l = []
for ix, (tr, te) in enumerate( kf5_ext):
print('{}th fold external validation stage ============================'.format( ix + 1))
xM_in = xM[ tr, :]
yV_in = yV[ tr, 0]
print('First Lasso Stage')
gs1 = gs_Lasso( xM_in, yV_in, alphas_log_l[0])
print('Best score:', gs1.best_score_)
print('Best param:', gs1.best_params_)
print(gs1.grid_scores_)
nz_idx = gs1.best_estimator_.sparse_coef_.indices
xM_in_nz = xM_in[ :, nz_idx]
print('Second Lasso Stage')
gs2 = gs_Lasso( xM_in_nz, yV_in, alphas_log_l[1])
print('Best score:', gs2.best_score_)
print('Best param:', gs2.best_params_)
print(gs2.grid_scores_)
print('External Validation Stage')
# Obtain prediction model by whole data including internal validation data
alpha = gs2.best_params_['alpha']
clf = linear_model.Lasso( alpha = alpha)
clf.fit( xM_in_nz, yV_in)
xM_out = xM[ te, :]
yV_out = yV[ te, 0]
xM_out_nz = xM_out[:, nz_idx]
score = clf.score( xM_out_nz, yV_out)
print(score)
score_l.append( score)
print('')
print('all scores:', score_l)
print('average scores:', np.mean( score_l))
return score_l
def gs_Ridge_Asupervising_2fp( xM1, xM2, yV, s_l, alpha_l):
"""
This 2fp case uses two fingerprints at the same in order to
combines their preprocessing versions separately.
"""
r2_l2 = list()
for alpha in alpha_l:
print(alpha)
r2_l = cv_Ridge_Asupervising_2fp( xM1, xM2, yV, s_l, alpha)
r2_l2.append( r2_l)
return r2_l2
def _cv_LinearRegression_r0( xM, yV):
print(xM.shape, yV.shape)
clf = linear_model.Ridge()
kf5_c = model_selection.KFold( n_splits = 5, shuffle=True)
kf5 = kf5_c.split( xM)
cv_scores = model_selection.cross_val_score( clf, xM, yV, scoring = 'r2', cv = kf5, n_jobs = -1)
return cv_scores
def _cv_LinearRegression_r1( xM, yV):
print(xM.shape, yV.shape)
clf = linear_model.LinearRegression()
kf5_c = model_selection.KFold( n_splits = 5, shuffle=True)
kf5 = kf5_c.split( xM)
cv_scores = model_selection.cross_val_score( clf, xM, yV, scoring = 'r2', cv = kf5, n_jobs = -1)
print('R^2 mean, std -->', np.mean( cv_scores), np.std( cv_scores))
return cv_scores
def _cv_LinearRegression_r2( xM, yV, scoring = 'r2'):
print(xM.shape, yV.shape)
clf = linear_model.LinearRegression()
kf5_c = model_selection.KFold( n_splits = 5, shuffle=True)
kf5 = kf5_c.split( xM)
cv_scores = model_selection.cross_val_score( clf, xM, yV, scoring = scoring, cv = kf5, n_jobs = -1)
print('{}: mean, std -->'.format( scoring), np.mean( cv_scores), np.std( cv_scores))
return cv_scores
def cv_LinearRegression( xM, yV, n_splits = 5, scoring = 'median_absolute_error', disp = False):
"""
metrics.explained_variance_score(y_true, y_pred) Explained variance regression score function
metrics.mean_absolute_error(y_true, y_pred) Mean absolute error regression loss
metrics.mean_squared_error(y_true, y_pred[, ...]) Mean squared error regression loss
metrics.median_absolute_error(y_true, y_pred) Median absolute error regression loss
metrics.r2_score(y_true, y_pred[, ...]) R^2 (coefficient of determination) regression score function.
"""
if disp:
print(xM.shape, yV.shape)
clf = linear_model.LinearRegression()
kf5_c = model_selection.KFold( n_splits=n_splits, shuffle=True)
kf5 = kf5_c.split( xM)
cv_score_l = list()
for train, test in kf5:
# clf.fit( xM[train,:], yV[train,:])
# yV is vector but not a metrix here. Hence, it should be treated as a vector
clf.fit( xM[train,:], yV[train])
yVp_test = clf.predict( xM[test,:])
if scoring == 'median_absolute_error':
cv_score_l.append( metrics.median_absolute_error(yV[test], yVp_test))
else:
raise ValueError( "{} scoring is not supported.".format( scoring))
if disp: # Now only this flag is on, the output will be displayed.
print('{}: mean, std -->'.format( scoring), np.mean( cv_score_l), np.std( cv_score_l))
return cv_score_l
def cv_LinearRegression_ci( xM, yV, n_splits = 5, scoring = 'median_absolute_error', disp = False):
"""
metrics.explained_variance_score(y_true, y_pred) Explained variance regression score function
metrics.mean_absolute_error(y_true, y_pred) Mean absolute error regression loss
metrics.mean_squared_error(y_true, y_pred[, ...]) Mean squared error regression loss
metrics.median_absolute_error(y_true, y_pred) Median absolute error regression loss
metrics.r2_score(y_true, y_pred[, ...]) R^2 (coefficient of determination) regression score function.
"""
if disp:
print(xM.shape, yV.shape)
clf = linear_model.LinearRegression()
kf5_c = model_selection.KFold( n_splits=n_splits, shuffle=True)
kf5 = kf5_c.split( xM)
cv_score_l = list()
ci_l = list()
for train, test in kf5:
# clf.fit( xM[train,:], yV[train,:])
# yV is vector but not a metrix here. Hence, it should be treated as a vector
clf.fit( xM[train,:], yV[train])
yVp_test = clf.predict( xM[test,:])
# Additionally, coef_ and intercept_ are stored.
ci_l.append( (clf.coef_, clf.intercept_))
if scoring == 'median_absolute_error':
cv_score_l.append( metrics.median_absolute_error(yV[test], yVp_test))
else:
raise ValueError( "{} scoring is not supported.".format( scoring))
if disp: # Now only this flag is on, the output will be displayed.
print('{}: mean, std -->'.format( scoring), np.mean( cv_score_l), np.std( cv_score_l))
return cv_score_l, ci_l
def cv_LinearRegression_ci_pred( xM, yV, n_splits = 5, scoring = 'median_absolute_error', disp = False):
"""
metrics.explained_variance_score(y_true, y_pred) Explained variance regression score function
metrics.mean_absolute_error(y_true, y_pred) Mean absolute error regression loss
metrics.mean_squared_error(y_true, y_pred[, ...]) Mean squared error regression loss
metrics.median_absolute_error(y_true, y_pred) Median absolute error regression loss
metrics.r2_score(y_true, y_pred[, ...]) R^2 (coefficient of determination) regression score function.
"""
if disp:
print(xM.shape, yV.shape)
clf = linear_model.LinearRegression()
kf5_c = model_selection.KFold( n_splits=n_splits, shuffle=True)
kf5 = kf5_c.split( xM)
cv_score_l = list()
ci_l = list()
yVp = yV.copy()
for train, test in kf5:
# clf.fit( xM[train,:], yV[train,:])
# yV is vector but not a metrix here. Hence, it should be treated as a vector
clf.fit( xM[train,:], yV[train])
yVp_test = clf.predict( xM[test,:])
yVp[test] = yVp_test
# Additionally, coef_ and intercept_ are stored.
coef = np.array(clf.coef_).tolist()
intercept = np.array(clf.intercept_).tolist()
ci_l.append( (clf.coef_, clf.intercept_))
if scoring == 'median_absolute_error':
cv_score_l.append( metrics.median_absolute_error(yV[test], yVp_test))
else:
raise ValueError( "{} scoring is not supported.".format( scoring))
if disp: # Now only this flag is on, the output will be displayed.
print('{}: mean, std -->'.format( scoring), np.mean( cv_score_l), np.std( cv_score_l))
return cv_score_l, ci_l, yVp.A1.tolist()
def cv_LinearRegression_ci_pred_full_Ridge( xM, yV, alpha, n_splits = 5, shuffle=True, disp = False):
"""
Note - scoring is not used. I may used later. Not it is remained for compatibility purpose.
metrics.explained_variance_score(y_true, y_pred) Explained variance regression score function
metrics.mean_absolute_error(y_true, y_pred) Mean absolute error regression loss
metrics.mean_squared_error(y_true, y_pred[, ...]) Mean squared error regression loss
metrics.median_absolute_error(y_true, y_pred) Median absolute error regression loss
metrics.r2_score(y_true, y_pred[, ...]) R^2 (coefficient of determination) regression score function.
"""
if disp:
print(xM.shape, yV.shape)
# print( 'alpha of Ridge is', alpha)
clf = linear_model.Ridge( alpha)
kf5_c = model_selection.KFold( n_splits=n_splits, shuffle=shuffle)
kf5 = kf5_c.split( xM)
cv_score_l = list()
ci_l = list()
yVp = yV.copy()
for train, test in kf5:
# clf.fit( xM[train,:], yV[train,:])
# yV is vector but not a metrix here. Hence, it should be treated as a vector
clf.fit( xM[train,:], yV[train])
yVp_test = clf.predict( xM[test,:])
yVp[test] = yVp_test
# Additionally, coef_ and intercept_ are stored.
ci_l.append( (clf.coef_, clf.intercept_))
y_a = np.array( yV[test])[:,0]
yp_a = np.array( yVp_test)[:,0]
cv_score_l.extend( np.abs(y_a - yp_a).tolist())
return cv_score_l, ci_l, yVp.A1.tolist()
def cv_LinearRegression_ci_pred_full( xM, yV, n_splits = 5, shuffle=True, disp = False):
"""
Note - scoring is not used. I may used later. Not it is remained for compatibility purpose.
metrics.explained_variance_score(y_true, y_pred) Explained variance regression score function
metrics.mean_absolute_error(y_true, y_pred) Mean absolute error regression loss
metrics.mean_squared_error(y_true, y_pred[, ...]) Mean squared error regression loss
metrics.median_absolute_error(y_true, y_pred) Median absolute error regression loss
metrics.r2_score(y_true, y_pred[, ...]) R^2 (coefficient of determination) regression score function.
"""
if disp:
print(xM.shape, yV.shape)
clf = linear_model.LinearRegression()
kf5_c = model_selection.KFold( n_splits=n_splits, shuffle=shuffle)
kf5 = kf5_c.split( xM)
cv_score_l = list()
ci_l = list()
yVp = yV.copy()
for train, test in kf5:
# clf.fit( xM[train,:], yV[train,:])
# yV is vector but not a metrix here. Hence, it should be treated as a vector
clf.fit( xM[train,:], yV[train])
yVp_test = clf.predict( xM[test,:])
yVp[test] = yVp_test
# Additionally, coef_ and intercept_ are stored.
ci_l.append( (clf.coef_, clf.intercept_))
y_a = np.array( yV[test])[:,0]
yp_a = np.array( yVp_test)[:,0]
cv_score_l.extend( np.abs(y_a - yp_a).tolist())
return cv_score_l, ci_l, yVp.A1.tolist()
def cv_LinearRegression_It( xM, yV, n_splits = 5, scoring = 'median_absolute_error', N_it = 10, disp = False, ldisp = False):
"""
N_it times iteration is performed for cross_validation in order to make further average effect.
The flag of 'disp' is truned off so each iteration will not shown.
"""
cv_score_le = list()
for ni in range( N_it):
cv_score_l = cv_LinearRegression( xM, yV, n_splits = n_splits, scoring = scoring, disp = disp)
cv_score_le.extend( cv_score_l)
o_d = {'mean': np.mean( cv_score_le),
'std': np.std( cv_score_le),
'list': cv_score_le}
if disp or ldisp:
print('{0}: mean(+/-std) --> {1}(+/-{2})'.format( scoring, o_d['mean'], o_d['std']))
return o_d
def cv_LinearRegression_ci_It( xM, yV, n_splits = 5, scoring = 'median_absolute_error', N_it = 10, disp = False, ldisp = False):
"""
N_it times iteration is performed for cross_validation in order to make further average effect.
The flag of 'disp' is truned off so each iteration will not shown.
"""
cv_score_le = list()
ci_le = list()
for ni in range( N_it):
cv_score_l, ci_l = cv_LinearRegression_ci( xM, yV, n_splits = n_splits, scoring = scoring, disp = disp)
cv_score_le.extend( cv_score_l)
ci_le.extend( ci_l)
o_d = {'mean': np.mean( cv_score_le),
'std': np.std( cv_score_le),
'list': cv_score_le,
'ci': ci_le}
if disp or ldisp:
print('{0}: mean(+/-std) --> {1}(+/-{2})'.format( scoring, o_d['mean'], o_d['std']))
return o_d
def cv_LinearRegression_ci_pred_It( xM, yV, n_splits = 5, scoring = 'median_absolute_error', N_it = 10, disp = False, ldisp = False):
"""
N_it times iteration is performed for cross_validation in order to make further average effect.
The flag of 'disp' is truned off so each iteration will not shown.
"""
cv_score_le = list()
ci_le = list()
yVp_ltype_l = list() # yVp_ltype is list type of yVp not matrix type
for ni in range( N_it):
cv_score_l, ci_l, yVp_ltype = cv_LinearRegression_ci_pred( xM, yV, n_splits = n_splits, scoring = scoring, disp = disp)
cv_score_le.extend( cv_score_l)
ci_le.extend( ci_l)
yVp_ltype_l.append( yVp_ltype)
o_d = {'mean': np.mean( cv_score_le),
'std': np.std( cv_score_le),
'list': cv_score_le,
'ci': ci_le,
'yVp': yVp_ltype_l}
if disp or ldisp:
print('{0}: mean(+/-std) --> {1}(+/-{2})'.format( scoring, o_d['mean'], o_d['std']))
return o_d
def cv_LOO( xM, yV, disp = False, ldisp = False):
"""
This is a specialized function for LOO cross_validation.
"""
n_splits = xM.shape[0] # for LOO CV
return cv_LinearRegression_ci_pred_full_It( xM, yV, n_splits = n_splits, N_it = 1,
shuffle = False, disp = disp, ldisp = ldisp)
def cv_LOO_mode( mode, xM, yV, disp = False, ldisp = False):
"""
This is a specialized function for LOO cross_validation.
"""
if mode == "Linear":
# Linear regression
return cv_LOO( xM = xM, yV = yV, disp = disp, ldisp = ldisp)
elif mode == "Bias":
return cv_LinearRegression_Bias( xM, yV)
elif mode == "None":
return cv_LinearRegression_None( xM, yV)
raise ValueError("Mode is not support: mode =", mode)
def cv_LOO_Ridge( xM, yV, alpha, disp = False, ldisp = False):
"""
This is a specialized function for LOO cross_validation.
"""
n_splits = xM.shape[0] # for LOO CV
return cv_LinearRegression_ci_pred_full_It_Ridge( xM, yV, alpha, n_splits = n_splits, N_it = 1,
shuffle = False, disp = disp, ldisp = ldisp)
def cv_LinearRegression_ci_pred_full_It_Ridge( xM, yV, alpha, n_splits = 5, N_it = 10,
shuffle = True, disp = False, ldisp = False):
"""
N_it times iteration is performed for cross_validation in order to make further average effect.
The flag of 'disp' is truned off so each iteration will not shown.
"""
cv_score_le = list()
ci_le = list()
yVp_ltype_l = list() # yVp_ltype is list type of yVp not matrix type
for ni in range( N_it):
cv_score_l, ci_l, yVp_ltype = cv_LinearRegression_ci_pred_full_Ridge( xM, yV, alpha,
n_splits = n_splits, shuffle = shuffle, disp = disp)
cv_score_le.extend( cv_score_l)
ci_le.extend( ci_l)
yVp_ltype_l.append( yVp_ltype)
# List is not used if N_it is one
if N_it == 1:
yVp_ltype_l = yVp_ltype_l[0]
o_d = {'median_abs_err': np.median( cv_score_le),
'mean_abs_err': np.mean( cv_score_le),
'std_abs_err': np.std( cv_score_le),
'list': cv_score_le,
'ci': ci_le,
'yVp': yVp_ltype_l}
return o_d
def cv_LinearRegression_ci_pred_full_It( xM, yV, n_splits = 5, N_it = 10,
shuffle = True, disp = False, ldisp = False):
"""
N_it times iteration is performed for cross_validation in order to make further average effect.
The flag of 'disp' is truned off so each iteration will not shown.
"""
cv_score_le = list()
ci_le = list()
yVp_ltype_l = list() # yVp_ltype is list type of yVp not matrix type
for ni in range( N_it):
cv_score_l, ci_l, yVp_ltype = cv_LinearRegression_ci_pred_full( xM, yV,
n_splits = n_splits, shuffle = shuffle, disp = disp)
cv_score_le.extend( cv_score_l)
ci_le.extend( ci_l)
yVp_ltype_l.append( yVp_ltype)
# List is not used if N_it is one
if N_it == 1:
yVp_ltype_l = yVp_ltype_l[0]
o_d = {'median_abs_err': np.median( cv_score_le),
'mean_abs_err': np.mean( cv_score_le),
'std_abs_err': np.std( cv_score_le),
'list': cv_score_le,
'ci': ci_le,
'yVp': yVp_ltype_l}
return o_d
def cv_LinearRegression_None( xM, yV):
"""
N_it times iteration is performed for cross_validation in order to make further average effect.
The flag of 'disp' is truned off so each iteration will not shown.
"""
#print( "cv_LinearRegression_None", xM.shape, yV.shape)
X, y = np.array( xM)[:,0], np.array( yV)[:,0]
# only 1-dim is allowed for both X and y
assert (X.ndim == 1) or (X.shape[2] == 1) and (yV.ndim == 1) or (yV.shape[2] == 1)
yP = X
cv_score_le = np.abs( np.array( y - yP)).tolist()
o_d = {'median_abs_err': np.median( cv_score_le),
'mean_abs_err': np.mean( cv_score_le),
'std_abs_err': np.std( cv_score_le), # this can be std(err)
'list': cv_score_le,
'ci': "t.b.d",
'yVp': X.tolist()}
return o_d
def cv_LinearRegression_Bias( xM, yV):
"""
N_it times iteration is performed for cross_validation in order to make further average effect.
The flag of 'disp' is truned off so each iteration will not shown.
"""
#print( "cv_LinearRegression_None", xM.shape, yV.shape)
X, y = np.array( xM)[:,0], np.array( yV)[:,0]
# only 1-dim is allowed for both X and y
assert (X.ndim == 1) or (X.shape[2] == 1) and (yV.ndim == 1) or (yV.shape[2] == 1)
loo_c = model_selection.LeaveOneOut()
loo = loo_c.split( X)
yP = y.copy()
for train, test in loo:
bias = np.mean(y[train] - X[train])
yP[test] = X[test] + bias
cv_score_le = np.abs( np.array( y - yP)).tolist()
o_d = {'median_abs_err': np.median( cv_score_le),
'mean_abs_err': np.mean( cv_score_le),
'std_abs_err': np.std( cv_score_le), # this can be std(err)
'list': cv_score_le,
'ci': "t.b.d",
'yVp': X.tolist()}
return o_d
def mdae_no_regression( xM, yV, disp = False, ldisp = False):
"""
Median absloute error (Mdae) is calculated without any (linear) regression.
"""
xM_a = np.array( xM)
yV_a = np.array( yV)
ae_l = [ np.abs(x - y) for x, y in zip(xM_a[:,0], yV_a[:, 0])]
return np.median( ae_l)
def gs_Ridge_Asupervising_2fp_molw( xM1, xM2, yV, s_l, alpha_l):
"""
This 2fp case uses two fingerprints at the same in order to
combines their preprocessing versions separately.
"""
r2_l2 = list()
for alpha in alpha_l:
print(alpha)
r2_l = cv_Ridge_Asupervising_2fp_molw( xM1, xM2, yV, s_l, alpha)
r2_l2.append( r2_l)
return r2_l2
def gs_Ridge_Asupervising_molw( xM, yV, s_l, alpha_l):
r2_l2 = list()
for alpha in alpha_l:
print(alpha)
r2_l = cv_Ridge_Asupervising_molw( xM, yV, s_l, alpha)
r2_l2.append( r2_l)
return r2_l2
def gs_Ridge_Asupervising( xM, yV, s_l, alpha_l):
r2_l2 = list()
for alpha in alpha_l:
print(alpha)
r2_l = cv_Ridge_Asupervising( xM, yV, s_l, alpha)
r2_l2.append( r2_l)
return r2_l2
def gs_RidgeByLasso_kf_ext( xM, yV, alphas_log_l):
kf5_ext_c = model_selection.KFold( n_splits = 5, shuffle=True)
kf5_ext = kf5_ext_c.split( xM)
score_l = []
for ix, (tr, te) in enumerate( kf5_ext):
print('{}th fold external validation stage ============================'.format( ix + 1))
xM_in = xM[ tr, :]
yV_in = yV[ tr, 0]
print('First Ridge Stage')
gs1 = gs_Lasso( xM_in, yV_in, alphas_log_l[0])
print('Best score:', gs1.best_score_)
print('Best param:', gs1.best_params_)
print(gs1.grid_scores_)
nz_idx = gs1.best_estimator_.sparse_coef_.indices
xM_in_nz = xM_in[ :, nz_idx]
print('Second Lasso Stage')
gs2 = gs_Ridge( xM_in_nz, yV_in, alphas_log_l[1])
print('Best score:', gs2.best_score_)
print('Best param:', gs2.best_params_)
print(gs2.grid_scores_)
print('External Validation Stage')
# Obtain prediction model by whole data including internal validation data
alpha = gs2.best_params_['alpha']
clf = linear_model.Ridge( alpha = alpha)
clf.fit( xM_in_nz, yV_in)
xM_out = xM[ te, :]
yV_out = yV[ te, 0]
xM_out_nz = xM_out[:, nz_idx]
score = clf.score( xM_out_nz, yV_out)
print(score)
score_l.append( score)
print('')
print('all scores:', score_l)
print('average scores:', np.mean( score_l))
return score_l
def gs_SVR( xM, yV, svr_params, n_splits = 5, n_jobs = -1):
print(xM.shape, yV.shape)
clf = svm.SVR()
#parmas = {'alpha': np.logspace(1, -1, 9)}
kf5_c = model_selection.KFold( n_splits=n_splits, shuffle=True)
#kf5 = kf5_c.split( xM)
gs = model_selection.GridSearchCV( clf, svr_params, scoring = 'r2', cv = kf5_c, n_jobs = n_jobs)
gs.fit( xM, yV.A1)
return gs
def cv_SVR( xM, yV, svr_params, n_splits = 5, n_jobs = -1, grid_std = None, graph = True, shuffle = True):
"""
method can be 'Ridge', 'Lasso'
cross validation is performed so as to generate prediction output for all input molecules
"""
print(xM.shape, yV.shape)
clf = svm.SVR( **svr_params)
kf_n_c = model_selection.KFold( n_splits=n_splits, shuffle=shuffle)
kf_n = kf5_ext_c.split( xM)
yV_pred = model_selection.cross_val_predict( clf, xM, yV, cv = kf_n, n_jobs = n_jobs)
if graph:
print('The prediction output using cross-validation is given by:')
jutil.cv_show( yV, yV_pred, grid_std = grid_std)
return yV_pred
def gs_SVC( X, y, params, n_splits = 5):
return gs_classfier( svm.SVC(), X, y, params, n_splits=n_splits)
def gs_classfier( classifier, xM, yVc, params, n_splits=5, n_jobs=-1):
"""
gs = gs_classfier( classifier, xM, yVc, params, n_splits=5, n_jobs=-1)
Inputs
======
classifier = svm.SVC(), for example
param = {"C": np.logspace(-2,2,5)}
"""
#print(xM.shape, yVc.shape)
kf5_c = model_selection.KFold( n_splits=n_splits, shuffle=True)
gs = model_selection.GridSearchCV( classifier, params, cv=kf5_c, n_jobs=n_jobs)
gs.fit( xM, yVc)
return gs
def gs_LinearSVC( xM, yVc, params, n_splits=5, n_jobs=-1):
return gs_classfier( svm.LinearSVC(), xM, yVc, params, n_splits=n_splits, n_jobs=n_jobs)
def gs_SVRByLasso_kf_ext( xM, yV, alphas_log, svr_params):
kf5_ext_c = model_selection.KFold( n_splits = 5, shuffle=True)
kf5_ext = kf5_ext_c.split( xM)
score_l = []
for ix, (tr, te) in enumerate( kf5_ext):
print('{}th fold external validation stage ============================'.format( ix + 1))
xM_in = xM[ tr, :]
yV_in = yV[ tr, 0]
print('First Ridge Stage')
gs1 = gs_Lasso( xM_in, yV_in, alphas_log)
print('Best score:', gs1.best_score_)
print('Best param:', gs1.best_params_)
print(gs1.grid_scores_)
nz_idx = gs1.best_estimator_.sparse_coef_.indices
xM_in_nz = xM_in[ :, nz_idx]
print('Second Lasso Stage')
gs2 = gs_SVR( xM_in_nz, yV_in, svr_params)
print('Best score:', gs2.best_score_)
print('Best param:', gs2.best_params_)
print(gs2.grid_scores_)
print('External Validation Stage')
# Obtain prediction model by whole data including internal validation data
C = gs2.best_params_['C']
gamma = gs2.best_params_['gamma']
epsilon = gs2.best_params_['epsilon']
clf = svm.SVR( C = C, gamma = gamma, epsilon = epsilon)
clf.fit( xM_in_nz, yV_in.A1)
xM_out = xM[ te, :]
yV_out = yV[ te, 0]
xM_out_nz = xM_out[:, nz_idx]
score = clf.score( xM_out_nz, yV_out.A1)
print(score)
score_l.append( score)
print('')
print('all scores:', score_l)
print('average scores:', np.mean( score_l))
return score_l
def gs_SVRByLasso( xM, yV, alphas_log, svr_params):
kf5_ext_c = model_selection.KFold( n_splits = 5, shuffle=True)
kf5_ext = kf5_ext_c.split( xM)
score1_l = []
score_l = []
for ix, (tr, te) in enumerate( kf5_ext):
print('{}th fold external validation stage ============================'.format( ix + 1))
xM_in = xM[ tr, :]
yV_in = yV[ tr, 0]
print('First Ridge Stage')
gs1 = gs_Lasso( xM_in, yV_in, alphas_log)
print('Best score:', gs1.best_score_)
print('Best param:', gs1.best_params_)
print(gs1.grid_scores_)
score1_l.append( gs1.best_score_)
nz_idx = gs1.best_estimator_.sparse_coef_.indices
xM_in_nz = xM_in[ :, nz_idx]
print('Second Lasso Stage')
gs2 = gs_SVR( xM_in_nz, yV_in, svr_params)
print('Best score:', gs2.best_score_)
print('Best param:', gs2.best_params_)
print(gs2.grid_scores_)
print('External Validation Stage')
# Obtain prediction model by whole data including internal validation data
C = gs2.best_params_['C']
gamma = gs2.best_params_['gamma']
epsilon = gs2.best_params_['epsilon']
clf = svm.SVR( C = C, gamma = gamma, epsilon = epsilon)
clf.fit( xM_in_nz, yV_in.A1)
xM_out = xM[ te, :]
yV_out = yV[ te, 0]
xM_out_nz = xM_out[:, nz_idx]
score = clf.score( xM_out_nz, yV_out.A1)
print(score)
score_l.append( score)
print('')
print('all scores:', score_l)
print('average scores:', np.mean( score_l))
print('First stage scores', score1_l)
print('Average first stage scores', np.mean( score1_l))
return score_l, score1_l
def gs_ElasticNet( xM, yV, en_params):
print(xM.shape, yV.shape)
clf = linear_model.ElasticNet()
kf5_c = model_selection.KFold( n_splits = 5, shuffle=True)
kf5 = kf5_c.split( xM)
gs = model_selection.GridSearchCV( clf, en_params, scoring = 'r2', cv = kf5_c, n_jobs = -1)
gs.fit( xM, yV)
return gs
def gs_SVRByElasticNet( xM, yV, en_params, svr_params):
kf5_ext_c = model_selection.KFold( n_splits = 5, shuffle=True)
kf5_ext = kf5_ext_c.split( xM)
score1_l = []
score_l = []
for ix, (tr, te) in enumerate( kf5_ext):
print('{}th fold external validation stage ============================'.format( ix + 1))
xM_in = xM[ tr, :]
yV_in = yV[ tr, 0]
print('First Ridge Stage')
gs1 = gs_ElasticNet( xM_in, yV_in, en_params)
print('Best score:', gs1.best_score_)
print('Best param:', gs1.best_params_)
print(gs1.grid_scores_)
score1_l.append( gs1.best_score_)
nz_idx = gs1.best_estimator_.sparse_coef_.indices
xM_in_nz = xM_in[ :, nz_idx]
print('Second Lasso Stage')
gs2 = gs_SVR( xM_in_nz, yV_in, svr_params)
print('Best score:', gs2.best_score_)
print('Best param:', gs2.best_params_)
print(gs2.grid_scores_)
print('External Validation Stage')
# Obtain prediction model by whole data including internal validation data
C = gs2.best_params_['C']
gamma = gs2.best_params_['gamma']
epsilon = gs2.best_params_['epsilon']
clf = svm.SVR( C = C, gamma = gamma, epsilon = epsilon)
clf.fit( xM_in_nz, yV_in.A1)
xM_out = xM[ te, :]
yV_out = yV[ te, 0]
xM_out_nz = xM_out[:, nz_idx]
score = clf.score( xM_out_nz, yV_out.A1)
print(score)
score_l.append( score)
print('')
print('all scores:', score_l)
print('average scores:', np.mean( score_l))
print('First stage scores', score1_l)
print('Average first stage scores', np.mean( score1_l))
return score_l, score1_l
def gs_GPByLasso( xM, yV, alphas_log):
kf5_ext_c = model_selection.KFold( n_splits = 5, shuffle=True)
kf5_ext = kf5_ext_c.split( xM)
score1_l = []
score_l = []
for ix, (tr, te) in enumerate( kf5_ext):
print('{}th fold external validation stage ============================'.format( ix + 1))
xM_in = xM[ tr, :]
yV_in = yV[ tr, 0]
print('First Ridge Stage')
gs1 = gs_Lasso( xM_in, yV_in, alphas_log)