-
Notifications
You must be signed in to change notification settings - Fork 7
/
jpandas.py
2414 lines (1840 loc) · 74.4 KB
/
jpandas.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
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem import Draw
from rdkit import DataStructs
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn import linear_model, externals
from IPython.display import display
# This is James Sungjin Kim's library
import jutil, jchem, jquinone, jgrid
import jfile
import j3x.jpyx
from maml.gp import gaussian_process as gp
def pd_find_SMILES( pdr, s, disp = False, smiles_id = 'SMILES'):
pdw = pdr[ pdr[ smiles_id] == s]
if disp:
display( pdw)
return pdw
def list_indices( l, target):
return [i for i,val in enumerate(l) if val == target]
def get_duplist( x_list, disp = True):
"""
Duplication indices are returned.
"""
duplist = []
for x in set( x_list):
if x_list.count( x) > 1:
duplist.append( list_indices( x_list, x))
if disp:
print(duplist)
for d in duplist:
print([x_list[x] for x in d])
return duplist
def check_mol2smiles( x_smiles_1):
"""
Find smiles codes which can not operate in rdkit now.
x_smiles_1 is refined by cannonical smiles generated by rdkit
"""
x_mol_list = [Chem.MolFromSmiles(x) for x in x_smiles_1]
fail_list = []
for ii in range( len(x_mol_list)):
try:
x_smiles_1[ii] = Chem.MolToSmiles( x_mol_list[ii])
#print ii, "Sucess"
except:
print(ii, "Faliue")
fail_list.append( ii)
x_smiles_1[ii] = ''
return fail_list
def get_mol2smiles( x_smiles_1):
"""
Find smiles codes which can not operate in rdkit now.
x_smiles_1 is refined by cannonical smiles generated by rdkit
"""
x_mol_list = [Chem.MolFromSmiles(x) for x in x_smiles_1]
fail_list = []
for ii in range( len(x_mol_list)):
try:
Chem.MolToSmiles( x_mol_list[ii])
#print ii, "Sucess"
except:
print(ii, "Faliue")
fail_list.append( ii)
x_smiles_1[ii] = ''
return fail_list
def pd_remove_no_mol2smiles( pdr, smiles_id = 'SMILES'):
"""
Find not working smiles codes
"""
s = pdr[ smiles_id].tolist()
fail_list = get_mol2smiles( s)
pdr = pd_remove_faillist_ID( pdr, fail_list)
return pdr
def pd_refine_smiles( pdr, smiles_id = 'SMILES'):
"""
smiles codes are refined by rdkit.
"""
s_l = pdr[ smiles_id]
m_l = list(map( Chem.MolFromSmiles, s_l))
new_s_l = list(map( Chem.MolToSmiles, m_l))
pdr[ smiles_id] = new_s_l
return pdr
def pd_clean_smiles( pdr, smiles_id = 'SMILES'):
if 'ID' not in list(pdr.keys()):
raise TypeError( 'pdr should have a key of ID.')
print('1. All columns each with a smile code not supported in rdkit are removing.')
pdr1 = pd_remove_no_mol2smiles( pdr, smiles_id = smiles_id)
print('2. Smiles are refined by rdkit')
pdr2 = pd_refine_smiles( pdr1, smiles_id = smiles_id)
print('3. Removing columns with duplicated smiles codes.')
print(' - you may check properties for the same smiles code molecules:')
print(' pd_get_dup_smiles_and_property()')
pdr3 = pd_remove_dup_smiles( pdr2, smiles_id = smiles_id)
return pdr3
def pd_remove_duplist_ID( pdr, dup_l):
pdr_ID_x = []
for d in dup_l:
pdr_ID_x.append([ pdr.ID.tolist()[x] for x in d])
print('pdr_ID_x ->', pdr_ID_x)
pdw = pdr
for d in pdr_ID_x:
for x in d[1:]:
pdw = pdw[ pdw.ID != x]
#print pdr.SMILES.shape, pdw.SMILES.shape
return pdw
def pd_remove_faillist_ID( pdr, fail_l):
"""
copy ID first and then operate for deleting
since pdw is chaning on the fly.
Index of list and index of pd item can not be the same.
"""
#pdr_ID_x = [ pdr.ID[x] for x in fail_l]
pdr_ID_x = [ pdr.ID.tolist()[x] for x in fail_l]
print("pdr_ID_x -> ", pdr_ID_x)
pdw = pdr
for x in pdr_ID_x:
# If indexing is working, this becomes copy
# since the length is not any longer the same
pdw = pdw[ pdw.ID != x]
#print [pdr.ID[ x] for x in fail_l]
#print pdr.SMILES.shape, pdw.SMILES.shape
return pdw
def pd_check_mol2smiles( pd_smiles):
smiles_l = pd_smiles.tolist()
fail_l = check_mol2smiles( smiles_l)
# since siles_l is changed, pd values are also changed.
pd_smiles = smiles_l
return fail_l
def pd_check_mol2smi( pdr, smiles_id = 'SMILES'):
smiles_l = pdr[smiles_id].tolist()
fail_l = check_mol2smiles( smiles_l)
return fail_l
def pd_remove_dup_smiles( pdr, smiles_id = 'SMILES'):
s_l = pdr[ smiles_id].tolist()
d_l = get_duplist( s_l)
print(d_l)
new_pdr = pd_remove_duplist_ID( pdr, d_l)
return new_pdr
def pd_get_fp_strings( pdr, radius = 4, nBits = 1024, smiles_id = 'SMILES'):
"""
Extract smiles codes and then convert them to fingerprint string list
"""
s_l = pdr[ smiles_id].tolist()
m_l = list(map( Chem.MolFromSmiles, s_l))
fp_s_l = [AllChem.GetMorganFingerprintAsBitVect(m, radius = radius, nBits = nBits).ToBitString() for m in m_l]
return fp_s_l
def xM( s_l, radius = 4, nBits = 1024):
m_l = list(map( Chem.MolFromSmiles, s_l))
fp_l = [AllChem.GetMorganFingerprintAsBitVect(m, radius = radius, nBits = nBits) for m in m_l]
return np.mat( fp_l)
def pd_get_xM( pdr, radius = 4, nBits = 1024, smiles_id = 'SMILES'):
"""
Extract smiles codes and then convert them to fingerprint matrix.
"""
s_l = pdr[ smiles_id].tolist()
m_l = list(map( Chem.MolFromSmiles, s_l))
fp_l = [AllChem.GetMorganFingerprintAsBitVect(m, radius = radius, nBits = nBits) for m in m_l]
xM = np.mat( fp_l)
return xM
def pd_get_xM_N( pdr, radius = 4, nBits = 1024, smiles_id = 'SMILES', N = None):
"""
Extract smiles codes and then convert them to fingerprint matrix.
Only the limited number of molecules are retrieved in order to reduce computational complexity.
"""
if N:
s_l = pdr[ smiles_id].tolist()[:N]
m_l = list(map( Chem.MolFromSmiles, s_l))
fp_l = [AllChem.GetMorganFingerprintAsBitVect(m, radius = radius, nBits = nBits) for m in m_l]
xM = np.mat( fp_l)
else:
return pd_get_xM( pdr, radius, nBits, smiles_id)
return xM
pd_get_fpM = pd_get_xM
def pd_get_xM_MACCSkeys( pdr, smiles_id = 'SMILES'):
"""
Extract smiles codes and then convert them to fingerprint matrix.
"""
s_l = pdr[ smiles_id].tolist()
return jchem.get_xM_MACCSkeys( s_l)
def pd_get_xM_molw( pdr, smiles_id = 'SMILES'):
s_l = pdr[ smiles_id].tolist()
return jchem.get_xM_molw( s_l)
def pd_get_xM_lasa( pdr, smiles_id = 'SMILES'):
s_l = pdr[ smiles_id].tolist()
return jchem.get_xM_lasa( s_l)
def pd_get_fpM_fromStr( pdr, fp_id = 'Fingerprint'):
"""
Extract fingerprint strings and then convert them to fingerprint matrix.
"""
s_l = pdr[ fp_id].tolist()
fp_i_l2 = [list(map(int, x)) for x in s_l]
xM = np.mat( fp_i_l2)
return xM
def pd_get_yV( pdr, y_id):
return np.mat( pdr[ y_id]).T
def pd_get_dup_smiles_and_property( pdr, smiles_id = 'SMILES', property_id = 'Solubility_log_mol_l'):
pdr1 = pd_refine_smiles( pdr, smiles_id = smiles_id)
lst = get_duplist( pdr1[ smiles_id].tolist(), disp = False)
print('SMILES --> Property-1(SMILES), Property-2(SMILES), ...')
for ll in lst:
print(pdr1[smiles_id][ ll[0]], '-->', end=' ')
for l0 in ll:
print(l0, ":", pdr1[ property_id][l0], end=' ')
delta = abs(pdr1[ property_id][ ll[0]] - pdr1[ property_id][l0])
if delta > 0.1 * abs(pdr1[property_id][ ll[0]]):
print("Large difference ({})".format( delta), end=' ')
elif delta > 0.01 * abs(pdr1[property_id][ ll[0]]):
print("Medium difference ({})".format( delta), end=' ')
print()
print('\n=========================================')
print('Medium difference list: > 0.01 times')
for ll in lst:
for l0 in ll:
delta = abs(pdr1[ property_id][ ll[0]] - pdr1[ property_id][l0])
if delta > 0.01 * abs(pdr1[property_id][ ll[0]]):
print(pdr1[smiles_id][ ll[0]], '-->', end=' ')
print(l0, ":", pdr1[ property_id][l0], end=' ')
print("Difference ({})".format( delta))
print('\n=========================================')
print('large difference list: > 0.1 times')
for ll in lst:
for l0 in ll:
delta = abs(pdr1[ property_id][ ll[0]] - pdr1[ property_id][l0])
if delta > 0.1 * abs(pdr1[property_id][ ll[0]]):
print(pdr1[smiles_id][ ll[0]], '-->', end=' ')
print(l0, ":", pdr1[ property_id][l0], end=' ')
print("Difference ({})".format( delta))
"""
Class modules are described below,
while function modules are described above.
"""
class _PD_mlr_r0():
def __init__(self, pdr, y_id = 'Solubility log(mol/L)', smiles_id = 'SMILES', preprocessing = False):
if preprocessing:
self.xM = jchem.calc_corr( pdr[ smiles_id].tolist())
else:
self.xM = pd_get_fpM( pdr, smiles_id = smiles_id)
self.yV = pd_get_yV( pdr, y_id = y_id)
def set_SVD(self):
U,d,VT = np.linalg.svd( self.xM)
self.xM = self.xM * VT.T
def _val_vseq_mode_rand_r0( self, mode = {'type': 'ridge', 'alpha': 0.5}, rate = 2, disp = True, graph = True):
"""
The regression performed directly from the pdr.
We define mode dictionary to enter various types of optimization method.
"""
ly = len( self.yV)
vseq = jutil.choose( ly, int(ly / rate));
if mode['type'] == 'ridge':
r_sqr, RMSE = jutil.mlr_val_vseq_ridge( self.xM, self.yV, vseq, alpha = mode['alpha'], disp = disp, graph = graph)
return r_sqr, RMSE
def val_vseq_mode_rand( self, mode = {'type': 'ridge', 'alpha': 0.5}, rate = 2, disp = True, graph = True):
"""
The regression performed directly from the pdr.
We define mode dictionary to enter various types of optimization method.
"""
ly = len( self.yV)
vseq = jutil.choose( ly, int(ly / rate));
r_sqr, RMSE = self.val_vseq_mode( self.xM, self.yV, vseq, mode = mode, disp = disp, graph = graph)
return r_sqr, RMSE
def _val_vseq_mode_r0( self, RM, yE, v_seq, mode = {'type': 'ridge', 'alpha': 0.5}, disp = True, graph = True):
"""
Validation is peformed using vseq indexed values.
"""
org_seq = list(range( len( yE)))
t_seq = [x for x in org_seq if x not in v_seq]
RMt, yEt = RM[ t_seq, :], yE[ t_seq, 0]
RMv, yEv = RM[ v_seq, :], yE[ v_seq, 0]
#Regression or prediction can be performed by the predefined type such as Ridge.
if mode['type'] == 'ridge':
print('Ridge: alpha =', mode['alpha'])
clf = linear_model.Ridge( alpha = mode['alpha'])
clf.fit( RMt, yEt)
if disp: print('Training result')
jutil.mlr_show( clf, RMt, yEt, disp = disp, graph = graph)
if disp: print('Validation result')
r_sqr, RMSE = jutil.mlr_show( clf, RMv, yEv, disp = disp, graph = graph)
#if r_sqr < 0:
# print 'v_seq:', v_seq, '--> r_sqr = ', r_sqr
return r_sqr, RMSE
def _val_vseq_mode_gpnorm( self, RM, yE, v_seq, mode = {'type': 'ridge', 'alpha': 0.5}, disp = True, graph = True):
"""
Validation is peformed using vseq indexed values.
"""
org_seq = list(range( len( yE)))
t_seq = [x for x in org_seq if x not in v_seq]
RMt, yEt = RM[ t_seq, :], yE[ t_seq, 0]
RMv, yEv = RM[ v_seq, :], yE[ v_seq, 0]
#Regression or prediction can be performed by the predefined type such as Ridge.
if mode['type'] == 'ridge':
print('Ridge: alpha =', mode['alpha'])
clf = linear_model.Ridge( alpha = mode['alpha'])
# Training mode
clf.fit( RMt, yEt)
yEt_predict = clf.predict( RMt)
# Validation mode
yEv_predict = clf.predict( RMv)
elif mode['type'] == 'maml_gp':
RMt_a, yEt_a = np.array( RMt), np.array( yEt) / mode['norm']
RMv_a, yEv_a = np.array( RMv), np.array( yEv) / mode['norm']
jgp_en = gp.GaussianProcess( RMt_a, yEt_a, RMv_a, yEv_a)
# Training mode
jgp_en.optimize_noise_and_amp()
yEt_predict = np.mat( jgp_en.predicted_targets)
print(yEt_predict.shape)
# Validation mode
jgp_en.run_gp()
yEv_predict = np.mat( jgp_en.predicted_targets)
print(yEv_predict.shape)
#if disp: print 'Training result'
#jutil.regress_show( yEt, yEt_predict, disp = disp, graph = graph)
if disp: print('Validation result')
r_sqr, RMSE = jutil.regress_show( yEv / mode['norm'], yEv_predict, disp = disp, graph = graph)
return r_sqr, RMSE
def _val_vseq_mode_r0( self, RM, yE, v_seq, mode = {'type': 'ridge', 'alpha': 0.5}, disp = True, graph = True):
"""
Validation is peformed using vseq indexed values.
"""
org_seq = list(range( len( yE)))
t_seq = [x for x in org_seq if x not in v_seq]
RMt, yEt = RM[ t_seq, :], yE[ t_seq, 0]
RMv, yEv = RM[ v_seq, :], yE[ v_seq, 0]
#Regression or prediction can be performed by the predefined type such as Ridge.
if mode['type'] == 'ridge':
print('Ridge: alpha =', mode['alpha'])
clf = linear_model.Ridge( alpha = mode['alpha'])
# Training mode
clf.fit( RMt, yEt)
yEt_predict = clf.predict( RMt)
# Validation mode
yEv_predict = clf.predict( RMv)
elif mode['type'] == 'maml_gp':
RMt_a, yEt_a = np.array( RMt), np.array( yEt)
RMv_a, yEv_a = np.array( RMv), np.array( yEv)
jgp_en = gp.GaussianProcess( RMt_a, yEt_a, RMv_a, yEv_a)
# Training mode
jgp_en.optimize_noise_and_amp()
yEt_predict = np.mat( jgp_en.predicted_targets)
print(yEt_predict.shape)
# Validation mode
jgp_en.run_gp()
yEv_predict = np.mat( jgp_en.predicted_targets)
print(yEv_predict.shape)
if mode['type'] != 'maml_gp':
if disp: print('Training result')
jutil.regress_show( yEt, yEt_predict, disp = disp, graph = graph)
if disp: print('Validation result')
r_sqr, RMSE = jutil.regress_show( yEv, yEv_predict, disp = disp, graph = graph)
return r_sqr, RMSE
def val_vseq_mode( self, RM, yE, v_seq, mode = {'tool': 'sklearn', 'type': 'ridge', 'alpha': 0.5}, disp = True, graph = True):
"""
Validation is peformed using vseq indexed values.
"""
if 'tool' not in list(mode.keys()):
if mode['type'] in ('maml_gp'):
mode['tool'] = 'AAG'
else:
mode['tool'] = 'sklearn'
org_seq = list(range( len( yE)))
t_seq = [x for x in org_seq if x not in v_seq]
RMt, yEt = RM[ t_seq, :], yE[ t_seq, 0]
RMv, yEv = RM[ v_seq, :], yE[ v_seq, 0]
if mode['tool'] == 'sklearn':
if mode['type'] == 'ridge':
print('Ridge: alpha =', mode['alpha'])
clf = linear_model.Ridge( alpha = mode['alpha'])
elif mode['type'] == 'Lasso':
print('Lasso: alpha =', mode['alpha'])
clf = linear_model.Lasso( alpha = mode['alpha'])
elif mode['type'] == 'ElasticNet':
print('ElasticNet: alpha = {0}, l1_ratio = {1}'.format( mode['alpha'], mode['l1_ratio']))
clf = linear_model.ElasticNet( alpha = mode['alpha'], l1_ratio = mode['l1_ratio'], normalize = True)
elif mode['type'] == 'LassoLars':
print('LassoLars: alpha =', mode['alpha'])
clf = linear_model.LassoLars( alpha = mode['alpha'])
else:
raise TypeError("The given mode is not supported yet or spells are different.")
# Training mode
clf.fit( RMt, yEt)
yEt_predict = clf.predict( RMt)
# Validation mode
yEv_predict = clf.predict( RMv)
if disp: print('Training result')
#print yEt_predict[:10] #For debugging
jutil.regress_show( yEt, yEt_predict, disp = disp, graph = graph)
elif mode['tool'] == 'AAG':
if mode['type'] == 'maml_gp':
RMt_a, yEt_a = np.array( RMt), np.array( yEt)
RMv_a, yEv_a = np.array( RMv), np.array( yEv)
jgp_en = gp.GaussianProcess( RMt_a, yEt_a, RMv_a, yEv_a)
# Training mode
jgp_en.optimize_noise_and_amp()
yEt_predict = np.mat( jgp_en.predicted_targets)
print(yEt_predict.shape)
# Validation mode
jgp_en.run_gp()
yEv_predict = np.mat( jgp_en.predicted_targets)
print(yEv_predict.shape)
else:
raise TypeError("{} is not support for mode-tool yet.".format( mode['tool']))
if disp: print('Validation result')
r_sqr, RMSE = jutil.regress_show( yEv, yEv_predict, disp = disp, graph = graph)
return r_sqr, RMSE
def _val_vseq_mode_r1( self, RM, yE, v_seq, mode = {'tool': 'sklearn', 'type': 'ridge', 'alpha': 0.5}, disp = True, graph = True):
"""
Validation is peformed using vseq indexed values.
"""
if 'tool' not in list(mode.keys()):
if mode['type'] in ('maml_gp'):
mode['tool'] = 'AAG'
else:
mode['tool'] = 'sklearn'
org_seq = list(range( len( yE)))
t_seq = [x for x in org_seq if x not in v_seq]
RMt, yEt = RM[ t_seq, :], yE[ t_seq, 0]
RMv, yEv = RM[ v_seq, :], yE[ v_seq, 0]
if mode['tool'] == 'sklearn':
if mode['type'] == 'ridge':
print('Ridge: alpha =', mode['alpha'])
clf = linear_model.Ridge( alpha = mode['alpha'])
elif mode['type'] == 'Lasso':
print('Lasso: alpha =', mode['alpha'])
clf = linear_model.Lasso( alpha = mode['alpha'])
elif mode['type'] == 'ElasticNet':
print('ElasticNet: alpha = {0}, l1_ratio = {1}'.format( mode['alpha'], mode['l1_ratio']))
clf = linear_model.ElasticNet( alpha = mode['alpha'], l1_ratio = mode['l1_ratio'])
elif mode['type'] == 'LassoLars':
print('LassoLars: alpha =', mode['alpha'])
clf = linear_model.LassoLars( alpha = mode['alpha'])
else:
raise TypeError("The given mode is not supported yet or spells are different.")
# Training mode
clf.fit( RMt, yEt)
yEt_predict = clf.predict( RMt)
# Validation mode
yEv_predict = clf.predict( RMv)
if disp: print('Training result')
#print yEt_predict[:10] #For debugging
jutil.regress_show( yEt, yEt_predict, disp = disp, graph = graph)
elif mode['tool'] == 'AAG':
if mode['type'] == 'maml_gp':
RMt_a, yEt_a = np.array( RMt), np.array( yEt)
RMv_a, yEv_a = np.array( RMv), np.array( yEv)
jgp_en = gp.GaussianProcess( RMt_a, yEt_a, RMv_a, yEv_a)
# Training mode
jgp_en.optimize_noise_and_amp()
yEt_predict = np.mat( jgp_en.predicted_targets)
print(yEt_predict.shape)
# Validation mode
jgp_en.run_gp()
yEv_predict = np.mat( jgp_en.predicted_targets)
print(yEv_predict.shape)
else:
raise TypeError("{} is not support for mode-tool yet.".format( mode['tool']))
if disp: print('Validation result')
r_sqr, RMSE = jutil.regress_show( yEv, yEv_predict, disp = disp, graph = graph)
return r_sqr, RMSE
def val_vseq_ridge_rand_profile( self, alpha = .5, rate = 2, iterN = 10, disp = False, graph = False, hist = True):
jutil.mlr_val_vseq_ridge_rand_profile( self.xM, self.yV, alpha = alpha, rate = rate, iterN = iterN,
disp = disp, graph = graph, hist = hist)
def val_vseq_mode_rand_profile( self, mode, rate = 2, iterN = 10, disp = True, graph = False, hist = True):
RM = self.xM
yE = self.yV
r2_rms_list = []
for ii in range( iterN):
vseq = jutil.choose( len( yE), int(len( yE) / rate));
r_sqr, RMSE = self.val_vseq_mode( RM, yE, vseq, mode = mode, disp = disp, graph = graph)
r2_rms_list.append( (r_sqr, RMSE))
r2_list, rms_list = list(zip( *r2_rms_list))
#Showing r2 as histogram
pd_r2 = pd.DataFrame( {'r_sqr': r2_list})
pd_r2.plot( kind = 'hist', alpha = 0.5)
#Showing rms as histogram
pd_rms = pd.DataFrame( {'rms': rms_list})
pd_rms.plot( kind = 'hist', alpha = 0.5)
print("average r2 and sd:", list(map( np.mean, [r2_list, rms_list])))
return r2_list, rms_list
class _PD_mlr_r1(): # 2015-6-3
def __init__(self, pdr, y_id = 'Solubility log(mol/L)', smiles_id = 'SMILES',
preprocessing = False, forwardpreprocessing = True):
"""
y normalization is not important for prediction.
X normalization seems to be useful but not confirmed yet.
"""
if preprocessing:
self.A = jchem.calc_corr( pdr[ smiles_id].tolist())
self.xM = self.A
else:
self.xM_org = pd_get_fpM( pdr, smiles_id = smiles_id)
self.xM = self.xM_org
self.preprocessing = preprocessing
self.forwardpreprocessing = forwardpreprocessing
self.yV = pd_get_yV( pdr, y_id = y_id)
#self.mean_yV = np.mean( yV)
#self.yV = yV - self.mean_yV
def set_SVD(self):
U,d,VT = np.linalg.svd( self.xM)
self.xM = self.xM * VT.T
def reset_SVD(self):
self.xM = self.xM_org
def val_vseq_mode_seq( self, mode = {'type': 'ridge', 'alpha': 0.5}, st_val = 0, rate = 2, disp = True, graph = True):
"""
The regression performed directly from the pdr.
We define mode dictionary to enter various types of optimization method.
"""
ly = len( self.yV)
vseq = list(range( st_val, ly, rate))
r_sqr, RMSE = self.val_vseq_mode( self.xM, self.yV, vseq, mode = mode, disp = disp, graph = graph)
return r_sqr, RMSE
def _val_vseq_mode_rand_r0( self, mode = {'type': 'ridge', 'alpha': 0.5}, rate = 2, disp = True, graph = True):
"""
The regression performed directly from the pdr.
We define mode dictionary to enter various types of optimization method.
"""
ly = len( self.yV)
vseq = jutil.choose( ly, int(ly / rate));
if mode['type'] == 'ridge':
r_sqr, RMSE = jutil.mlr_val_vseq_ridge( self.xM, self.yV, vseq, alpha = mode['alpha'], disp = disp, graph = graph)
return r_sqr, RMSE
def val_vseq_mode_rand( self, mode = {'type': 'ridge', 'alpha': 0.5}, rate = 2, disp = True, graph = True):
"""
The regression performed directly from the pdr.
We define mode dictionary to enter various types of optimization method.
"""
ly = len( self.yV)
vseq = jutil.choose( ly, int(ly / rate));
r_sqr, RMSE = self.val_vseq_mode( self.xM, self.yV, vseq, mode = mode, disp = disp, graph = graph)
return r_sqr, RMSE
def _val_vseq_mode_r0( self, RM, yE, v_seq, mode = {'type': 'ridge', 'alpha': 0.5}, disp = True, graph = True):
"""
Validation is peformed using vseq indexed values.
"""
org_seq = list(range( len( yE)))
t_seq = [x for x in org_seq if x not in v_seq]
RMt, yEt = RM[ t_seq, :], yE[ t_seq, 0]
RMv, yEv = RM[ v_seq, :], yE[ v_seq, 0]
#Regression or prediction can be performed by the predefined type such as Ridge.
if mode['type'] == 'ridge':
print('Ridge: alpha =', mode['alpha'])
clf = linear_model.Ridge( alpha = mode['alpha'])
clf.fit( RMt, yEt)
if disp: print('Training result')
jutil.mlr_show( clf, RMt, yEt, disp = disp, graph = graph)
if disp: print('Validation result')
r_sqr, RMSE = jutil.mlr_show( clf, RMv, yEv, disp = disp, graph = graph)
#if r_sqr < 0:
# print 'v_seq:', v_seq, '--> r_sqr = ', r_sqr
return r_sqr, RMSE
def _val_vseq_mode_gpnorm( self, RM, yE, v_seq, mode = {'type': 'ridge', 'alpha': 0.5}, disp = True, graph = True):
"""
Validation is peformed using vseq indexed values.
"""
org_seq = list(range( len( yE)))
t_seq = [x for x in org_seq if x not in v_seq]
RMt, yEt = RM[ t_seq, :], yE[ t_seq, 0]
RMv, yEv = RM[ v_seq, :], yE[ v_seq, 0]
#Regression or prediction can be performed by the predefined type such as Ridge.
if mode['type'] == 'ridge':
print('Ridge: alpha =', mode['alpha'])
clf = linear_model.Ridge( alpha = mode['alpha'])
# Training mode
clf.fit( RMt, yEt)
yEt_predict = clf.predict( RMt)
# Validation mode
yEv_predict = clf.predict( RMv)
elif mode['type'] == 'maml_gp':
RMt_a, yEt_a = np.array( RMt), np.array( yEt) / mode['norm']
RMv_a, yEv_a = np.array( RMv), np.array( yEv) / mode['norm']
jgp_en = gp.GaussianProcess( RMt_a, yEt_a, RMv_a, yEv_a)
# Training mode
jgp_en.optimize_noise_and_amp()
yEt_predict = np.mat( jgp_en.predicted_targets)
print(yEt_predict.shape)
# Validation mode
jgp_en.run_gp()
yEv_predict = np.mat( jgp_en.predicted_targets)
print(yEv_predict.shape)
#if disp: print 'Training result'
#jutil.regress_show( yEt, yEt_predict, disp = disp, graph = graph)
if disp: print('Validation result')
r_sqr, RMSE = jutil.regress_show( yEv / mode['norm'], yEv_predict, disp = disp, graph = graph)
return r_sqr, RMSE
def _val_vseq_mode_r0( self, RM, yE, v_seq, mode = {'type': 'ridge', 'alpha': 0.5}, disp = True, graph = True):
"""
Validation is peformed using vseq indexed values.
"""
org_seq = list(range( len( yE)))
t_seq = [x for x in org_seq if x not in v_seq]
RMt, yEt = RM[ t_seq, :], yE[ t_seq, 0]
RMv, yEv = RM[ v_seq, :], yE[ v_seq, 0]
#Regression or prediction can be performed by the predefined type such as Ridge.
if mode['type'] == 'ridge':
print('Ridge: alpha =', mode['alpha'])
clf = linear_model.Ridge( alpha = mode['alpha'])
# Training mode
clf.fit( RMt, yEt)
yEt_predict = clf.predict( RMt)
# Validation mode
yEv_predict = clf.predict( RMv)
elif mode['type'] == 'maml_gp':
RMt_a, yEt_a = np.array( RMt), np.array( yEt)
RMv_a, yEv_a = np.array( RMv), np.array( yEv)
jgp_en = gp.GaussianProcess( RMt_a, yEt_a, RMv_a, yEv_a)
# Training mode
jgp_en.optimize_noise_and_amp()
yEt_predict = np.mat( jgp_en.predicted_targets)
print(yEt_predict.shape)
# Validation mode
jgp_en.run_gp()
yEv_predict = np.mat( jgp_en.predicted_targets)
print(yEv_predict.shape)
if mode['type'] != 'maml_gp':
if disp: print('Training result')
jutil.regress_show( yEt, yEt_predict, disp = disp, graph = graph)
if disp: print('Validation result')
r_sqr, RMSE = jutil.regress_show( yEv, yEv_predict, disp = disp, graph = graph)
return r_sqr, RMSE
def val_vseq_mode( self, RM, yE, v_seq, mode = {'tool': 'sklearn', 'type': 'ridge', 'alpha': 0.5}, disp = True, graph = True):
"""
Validation is peformed using vseq indexed values.
"""
if 'tool' not in list(mode.keys()):
if mode['type'] in ('maml_gp'):
mode['tool'] = 'AAG'
else:
mode['tool'] = 'sklearn'
org_seq = list(range( len( yE)))
t_seq = [x for x in org_seq if x not in v_seq]
if self.preprocessing and not self.forwardpreprocessing:
RMt, yEt = RM[ t_seq, :-len(v_seq)], yE[ t_seq, 0]
RMv, yEv = RM[ v_seq, :-len(v_seq)], yE[ v_seq, 0]
else:
#This is general case
RMt, yEt = RM[ t_seq, :], yE[ t_seq, 0]
RMv, yEv = RM[ v_seq, :], yE[ v_seq, 0]
if mode['tool'] == 'sklearn':
if mode['type'].lower() == 'ridge':
print('Ridge: alpha =', mode['alpha'])
clf = linear_model.Ridge( alpha = mode['alpha'])
elif mode['type'].lower() == 'Lasso'.lower():
print('Lasso: alpha =', mode['alpha'])
clf = linear_model.Lasso( alpha = mode['alpha'])
elif mode['type'].lower() == 'ElasticNet'.lower():
print('ElasticNet: alpha = {0}, l1_ratio = {1}'.format( mode['alpha'], mode['l1_ratio']))
clf = linear_model.ElasticNet( alpha = mode['alpha'], l1_ratio = mode['l1_ratio'], normalize = True)
elif mode['type'].lower() == 'LassoLars'.lower():
print('LassoLars: alpha =', mode['alpha'])
clf = linear_model.LassoLars( alpha = mode['alpha'])
else:
raise TypeError("The given mode is not supported yet or spells are different.")
# Training mode
clf.fit( RMt, yEt)
yEt_predict = clf.predict( RMt)
# Validation mode
yEv_predict = clf.predict( RMv)
if disp: print('Training result')
#print yEt_predict[:10] #For debugging
jutil.regress_show( yEt, yEt_predict, disp = disp, graph = graph)
elif mode['tool'] == 'AAG':
if mode['type'] == 'maml_gp':
RMt_a, yEt_a = np.array( RMt), np.array( yEt)
RMv_a, yEv_a = np.array( RMv), np.array( yEv)
jgp_en = gp.GaussianProcess( RMt_a, yEt_a, RMv_a, yEv_a)
# Training mode
jgp_en.optimize_noise_and_amp()
yEt_predict = np.mat( jgp_en.predicted_targets)
print(yEt_predict.shape)
# Validation mode
jgp_en.run_gp()
yEv_predict = np.mat( jgp_en.predicted_targets)
print(yEv_predict.shape)
else:
raise TypeError("{} is not support for mode-tool yet.".format( mode['tool']))
if disp: print('Validation result')
r_sqr, RMSE = jutil.regress_show( yEv, yEv_predict, disp = disp, graph = graph)
return r_sqr, RMSE
def _val_vseq_mode_r1( self, RM, yE, v_seq, mode = {'tool': 'sklearn', 'type': 'ridge', 'alpha': 0.5}, disp = True, graph = True):
"""
Validation is peformed using vseq indexed values.
"""
if 'tool' not in list(mode.keys()):
if mode['type'] in ('maml_gp'):
mode['tool'] = 'AAG'
else:
mode['tool'] = 'sklearn'
org_seq = list(range( len( yE)))
t_seq = [x for x in org_seq if x not in v_seq]
RMt, yEt = RM[ t_seq, :], yE[ t_seq, 0]
RMv, yEv = RM[ v_seq, :], yE[ v_seq, 0]
if mode['tool'] == 'sklearn':
if mode['type'] == 'ridge':
print('Ridge: alpha =', mode['alpha'])
clf = linear_model.Ridge( alpha = mode['alpha'])
elif mode['type'] == 'Lasso':
print('Lasso: alpha =', mode['alpha'])
clf = linear_model.Lasso( alpha = mode['alpha'])
elif mode['type'] == 'ElasticNet':
print('ElasticNet: alpha = {0}, l1_ratio = {1}'.format( mode['alpha'], mode['l1_ratio']))
clf = linear_model.ElasticNet( alpha = mode['alpha'], l1_ratio = mode['l1_ratio'])
elif mode['type'] == 'LassoLars':
print('LassoLars: alpha =', mode['alpha'])
clf = linear_model.LassoLars( alpha = mode['alpha'])
else:
raise TypeError("The given mode is not supported yet or spells are different.")
# Training mode
clf.fit( RMt, yEt)
yEt_predict = clf.predict( RMt)
# Validation mode
yEv_predict = clf.predict( RMv)
if disp: print('Training result')
#print yEt_predict[:10] #For debugging
jutil.regress_show( yEt, yEt_predict, disp = disp, graph = graph)
elif mode['tool'] == 'AAG':
if mode['type'] == 'maml_gp':
RMt_a, yEt_a = np.array( RMt), np.array( yEt)
RMv_a, yEv_a = np.array( RMv), np.array( yEv)
jgp_en = gp.GaussianProcess( RMt_a, yEt_a, RMv_a, yEv_a)
# Training mode
jgp_en.optimize_noise_and_amp()
yEt_predict = np.mat( jgp_en.predicted_targets)
print(yEt_predict.shape)
# Validation mode
jgp_en.run_gp()
yEv_predict = np.mat( jgp_en.predicted_targets)
print(yEv_predict.shape)
else:
raise TypeError("{} is not support for mode-tool yet.".format( mode['tool']))
if disp: print('Validation result')
r_sqr, RMSE = jutil.regress_show( yEv, yEv_predict, disp = disp, graph = graph)
return r_sqr, RMSE
def val_vseq_ridge_rand_profile( self, alpha = .5, rate = 2, iterN = 10, disp = False, graph = False, hist = True):
jutil.mlr_val_vseq_ridge_rand_profile( self.xM, self.yV, alpha = alpha, rate = rate, iterN = iterN,
disp = disp, graph = graph, hist = hist)
def val_vseq_mode_rand_profile( self, mode, rate = 2, iterN = 10, disp = True, graph = False, hist = True):
RM = self.xM
yE = self.yV
r2_rms_list = []
for ii in range( iterN):
vseq = jutil.choose( len( yE), int(len( yE) / rate));
r_sqr, RMSE = self.val_vseq_mode( RM, yE, vseq, mode = mode, disp = disp, graph = graph)
r2_rms_list.append( (r_sqr, RMSE))
r2_list, rms_list = list(zip( *r2_rms_list))
#Showing r2 as histogram
pd_r2 = pd.DataFrame( {'r_sqr': r2_list})
pd_r2.plot( kind = 'hist', alpha = 0.5)
#Showing rms as histogram
pd_rms = pd.DataFrame( {'rms': rms_list})
pd_rms.plot( kind = 'hist', alpha = 0.5)
print("average r2 and sd:", list(map( np.mean, [r2_list, rms_list])))
return r2_list, rms_list
def predict( self, new_smiles, mode = {'tool': 'sklearn', 'type': 'ridge', 'alpha': 0.5}):