-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathutils_models.py
2013 lines (1803 loc) · 84.7 KB
/
utils_models.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
# system
import os, re
from numbers import Number
# data
import numpy as np
import pandas as pd
import sklearn
from sklearn import cluster, preprocessing
from sklearn.manifold import Isomap, MDS, TSNE
from sklearn.metrics import confusion_matrix, mean_absolute_error, mean_squared_error
from sklearn.metrics import silhouette_samples, silhouette_score
from sklearn.metrics import pairwise_distances
from sklearn.decomposition import PCA, FastICA, KernelPCA
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.cluster import SpectralClustering
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.svm import SVR, SVC
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, explained_variance_score, r2_score
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis as QDA
from sklearn.model_selection import KFold
import copy, itertools
from sklearn.model_selection._search import ParameterGrid
from sklearn.metrics._scorer import check_scoring
import logging
try:
from umap.umap_ import UMAP
except:
logging.warning('UMAP not installed, some functions might be unsupported')
try:
from xgboost import XGBClassifier, XGBRegressor
except:
print("Warning! XGBoost cannot be loaded!")
# plotting
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from mpl_toolkits.mplot3d import Axes3D
import seaborn as sns
try:
import plotly.express as px
except:
print("Warning: Plotly cannot be loaded!")
RAND_STATE = 230
# PRINCIPLE: CODE: 0 INDEX, PLOTTING: 1 INDEX
""" ##########################################
################ Preprocessing ###############
########################################## """
def load_session(root, opt='all'):
file_map = {'MAS': "WilbrechtLab_4ChoiceRevDataALL_MASTERFILE_081513.csv",
'MAS2': 'WilbrechtLab_4ChoiceRevDataALL_MASTERFILE_051820.csv',
'4CR': "4CR_Merge_052920.csv",
'FIP': "FIP Digging Summary Master File.csv",
'FIP_RL': "FIP_RL_061120.csv"}
if isinstance(opt, str):
if opt == 'all':
opts = file_map.keys()
else:
opts = []
assert opt in file_map, 'dataset not found'
return pd.read_csv(os.path.join(root, file_map[opt]))
else:
opts = opt
pdfs = [pd.read_csv(os.path.join(root, file_map[o])) for o in opts]
return pd.concat(pdfs, axis=0, join='outer', ignore_index=True)
def label_feature(pdf, criteria='num', verbose=False):
# OBSOLETE
results = []
for c in pdf.columns:
try:
cdata = pdf[c]
if criteria == 'num':
l = int(np.issubdtype(cdata.dtype, np.number) or np.all(cdata.dropna().str.isnumeric()))
elif criteria == 'full':
l = int(not np.any(cdata.isnull()))
else:
raise NotImplementedError('Unknown criteria: ', criteria)
except:
l = -1
results.append(l)
if verbose:
print(c, l)
return np.array(results)
def dataset_split_feature_classes(pdf):
classes = {'other': []}
for c in pdf.columns:
if '.' in c:
cnames = c.split('.')
classe = ".".join(cnames[:-1])
if classe in classes:
classes[classe].append(c)
else:
classes[classe] = [c]
else:
classes['other'].append(c)
return {cl: pdf[classes[cl]] for cl in classes}
def dataset_feature_cleaning(pdf, spec_map):
# TODO: implement merger
# TODO: maybe at some point drop rows instead of slicing them to rid the warnings?
# TODO: move function outside to form a new function with a new table
# Search for specific selectors
for s in spec_map:
# TODO: add function to allow multiplexing handling
if spec_map[s] == 'selD':
# Select rows with nonnull values
pdf = pdf.loc[~pdf[s].isnull()]
elif spec_map[s] == 'selF':
pdf[s].values[pdf[s].isnull()]= -1
# pdf[s] = pdf[s].astype(np.int)
elif isinstance(spec_map[s], dict):
# Select
assert 'sel' in spec_map[s], print('Bad Usage of Dictionary Coding, no drop nor sel')
sel_list = spec_map[s]['sel']
pdf = pdf.loc[pdf[s].isin(sel_list)]
return pdf
def vanilla_vectorizer(pdf):
keywords = pdf.columns[label_feature(pdf) == 1][:-2]
X0 = pdf[keywords].astype(np.float64)
X_nonan = X0.dropna()
return X_nonan
def MAS_data_vectorizer(pdf, inputRange, NAN_policy='drop'):
"""
:param pdf:
:param inputRange: list (denoting the column indices) or int (first inputRange columns are inputs)
:param NAN_policy:
:return:
"""
spec_map = {
'exp1_label_FI_AL_M': 'selF',
'exp2_Angel': 'selF',
'Treat': 'cat',
'Age At Treat': 'cat',
'Genotype': 'cat',
'Experimenter': 'cat'
}
# test.weight
testweight = pdf['test.weight']
for i in range(testweight.shape[0]):
target = testweight.iloc[i]
if ' at ' in str(target):
dp = float(target.split(" ")[0])
pdf['test.weight'].values[i] = dp
if not isinstance(inputRange, list):
inputRange = np.arange(inputRange)
D = pdf.shape[-1]
for irg, rg in enumerate(inputRange):
if rg < 0:
inputRange[irg] = D+rg
outputRange = np.setdiff1d(np.arange(D), inputRange)
pdf = dataset_feature_cleaning(pdf, spec_map)
inPDF, outPDF = pdf.iloc[:, inputRange], pdf.iloc[:, outputRange]
tPDF, tLabels, tFRows = default_vectorizer(inPDF, NAN_policy, spec_map, True)
xPDF, xLabels, xFRows = default_vectorizer(outPDF, NAN_policy, spec_map, True)
mRows = tFRows & xFRows
return (tPDF.loc[mRows], tLabels.loc[mRows]), (xPDF.loc[mRows], xLabels.loc[mRows])
def FOURCR_data_vectorizer(pdf, inputRange, NAN_policy='drop'):
"""
:param pdf:
:param inputRange: list (denoting the column indices) or int (first inputRange columns are inputs)
:param NAN_policy:
:return:
"""
spec_map = {
'exp1_label_FI_AL_M': 'selF',
'exp2_Angel': 'selF',
'Treat': 'cat',
'Genotype': 'cat',
'Experimenter': 'cat',
'ID': 'cat' # Figure out better way to encode this
}
# test.weight
testweight = pdf['test.weight']
for i in range(testweight.shape[0]):
target = testweight.iloc[i]
if ' at ' in str(target):
dp = float(target.split(" ")[0])
pdf['test.weight'].values[i] = dp
if not isinstance(inputRange, list):
inputRange = np.arange(inputRange)
D = pdf.shape[-1]
for irg, rg in enumerate(inputRange):
if rg < 0:
inputRange[irg] = D+rg
outputRange = np.setdiff1d(np.arange(D), inputRange)
pdf = dataset_feature_cleaning(pdf, spec_map)
inPDF, outPDF = pdf.iloc[:, inputRange], pdf.iloc[:, outputRange]
tPDF, tLabels, tFRows = default_vectorizer(inPDF, 'ignore', spec_map, True)
xPDF, xLabels, xFRows = default_vectorizer(outPDF, NAN_policy, spec_map, True)
mRows = tFRows & xFRows
return (tPDF.loc[mRows], tLabels.loc[mRows]), (xPDF.loc[mRows], xLabels.loc[mRows])
def FIP_data_vectorizer(pdf, inputRange, NAN_policy='drop'):
"""
:param pdf:
:param inputRange: list (denoting the column indices) or int (first inputRange columns are inputs)
:param NAN_policy:
:return:
"""
spec_map = {
'Experimental Cohort': 'cat',
'FIP Duration': 'cat',
'Behavior Duration': 'cat',
'exp_treat_sex': 'cat'
}
if not isinstance(inputRange, list):
inputRange = np.arange(inputRange)
outputRange = np.setdiff1d(np.arange(pdf.shape[-1]), inputRange)
inPDF, outPDF = pdf.iloc[:, inputRange], pdf.iloc[:, outputRange]
tPDF, tLabels, tFRows = default_vectorizer(inPDF, 'ignore', spec_map, True)
xPDF, xLabels, xFRows = default_vectorizer(outPDF, NAN_policy, spec_map, True)
mRows = tFRows & xFRows
return (tPDF.loc[mRows], tLabels.loc[mRows]), (xPDF.loc[mRows], xLabels.loc[mRows])
def default_vectorizer(pdf, NAN_policy='drop', spec_map=None, finalROW=False):
""" Taking in pdf with raw data, returns tuple(PDF_feature, encoding PDF)
Every modification to rows must be recorded if the features are to be used in a (Input, Output) model
and finalRow must be `True`.
# TODO: when setting data values, use pdf.values[slice, slice] = value
:param pdf:
:param spec_map:
cat: for categorical label
selF for setting blank label values as -1; selD for deleting blank label values
:return:
"""
# NAN_policy: fill additional value (minimum for instance)
if spec_map is None:
spec_map = {}
# Check drop
droplist = [c for c in pdf.columns if c in spec_map and spec_map[c] == 'drop']
pdf.drop(columns=droplist, inplace=True)
class_table = classify_features(pdf)
# class 2, special treatment out front
SPECIAL_MAP = class_table['class'] == 2
special_features = class_table['feature'][SPECIAL_MAP]
# ONLY special features that got converted to other types will be kept in the final data frame
for spe in special_features:
sdata = pdf[spe]
null_flags = sdata.isnull()
nonnull = sdata[~null_flags]
m = re.search("(\d+)/(\d+)/(\d+)", nonnull.iloc[0])
if m:
# TODO: if some relationship were to be found, we could split date code to three column year,
# month, date to probe seasonality
class_table['class'][class_table['feature'] == spe] = 1
for i in range(sdata.shape[0]):
if not null_flags[i]:
m = re.search("(\d+)/(\d+)/(\d+)", sdata.iloc[i])
g3 = m.group(3)
if len(g3) == 4:
g3 = g3[-2:]
datecode = int(f"{int(g3):02d}{int(m.group(1)):02d}{int(m.group(2)):02d}")
pdf[spe].values[i] = datecode
else:
pdf[spe].values[i] = np.nan
elif spe in spec_map:
class_table['class'][class_table['feature'] == spe] = 0
if spec_map[spe] == 'cat':
del spec_map[spe]
else:
for i, s in enumerate(nonnull):
try:
if str(s).startswith("#"):
try:
pdf[spe].replace({s: np.nan}, inplace=True)
pdf[spe] = pdf[spe].astype(np.float)
class_table['class'][class_table['feature'] == spe] = 1
except:
print(f'feature {spe} needs special handling')
break
except:
print(spe, i, 'nonnull')
raise RuntimeError()
# class 0, encode, use hot map
ALPHAS_MAP = class_table['class'] == 0
alpha_features = class_table['feature'][ALPHAS_MAP]
pdf_ENC = pdf.loc[:, alpha_features].copy(deep=True)
for alp in alpha_features:
if alp in spec_map:
# spec_map features demand special encoding
assert isinstance(spec_map[alp], dict), 'special map must be a dictionary'
pdf[alp].replace(spec_map[alp], inplace=True)
else:
null_alp = pdf[alp].isnull()
unique_vals = pdf[alp].dropna().unique()
if len(unique_vals) < 3:
# Default binary coding
pdf[alp]=pdf[alp].astype('category')
pdf_ENC[alp] = pdf[alp]
pdf.loc[:, alp] = pdf[alp].cat.codes.astype(np.float)
# TODO: clean the setter algorithms by converting everything to normal
pdf[alp].values[null_alp] = np.nan
else:
# ONE HOT ENCODING if more than 2 possible values
# NULL value be sure to mark back to null
pdf = pd.get_dummies(pdf, prefix_sep='__', columns=[alp], dtype=np.float)
pdf[[c for c in pdf.columns if c.startswith(alp+'__')]].values[null_alp] = np.nan
# if NAN greater than 50%, apply NAN_policy first
NUM_MAP = class_table['class'] == 1
num_features = class_table['feature'][NUM_MAP]
pdf.drop(columns=np.setdiff1d(class_table['feature'],
np.concatenate((alpha_features, num_features))), inplace=True)
pdf = pdf.astype(np.float)
# DISPOSE OF columns that have too many nans TODO: IMPLEMENT IGNORE POLICY OF NANS
if NAN_policy == 'drop':
THRES = 0.3
dropped_cols = class_table['null_ratio'] >= THRES
dropped_features = class_table['feature'][dropped_cols]
dropped_alpha_features = class_table['feature'][ALPHAS_MAP & dropped_cols]
pdf_ENC.drop(columns=dropped_alpha_features, inplace=True)
droppingFs = []
for feat in dropped_features:
if feat in pdf.columns:
droppingFs.append(feat)
else:
droppingFs = droppingFs + [c for c in pdf.columns if c.startswith(feat+'__')]
pdf.drop(columns=droppingFs, inplace=True)
nonullrows = ~pdf.isnull().any(axis=1)
elif NAN_policy == 'ignore':
pdf_ENC.values[pdf_ENC.isnull()] = np.nan
pdf.values[pdf.isnull()] = np.nan
nonullrows = np.full(pdf.shape[0], 1, dtype=bool)
else:
raise NotImplementedError(f'unknown policy {NAN_policy}')
if finalROW:
return pdf, pdf_ENC, nonullrows
else:
pdf = pdf.loc[nonullrows]
pdf_ENC = pdf_ENC.loc[nonullrows]
return pdf, pdf_ENC
def categorical_feature_num_to_label(pdf, pdfENC, column):
orig, val = column.split('__')
return pdfENC[orig]
def classify_features(pdf, out=None):
# cat: 0, num: 1, special: 2
# out: tuple(folder, saveopt)
class_table = {}
class_table['feature'] = []
class_table['class'] = []
class_table['null_ratio'] = []
for c in pdf.columns:
class_table['feature'].append(c)
cdata = pdf[c]
null_sels = cdata.isnull()
null_ratio = null_sels.sum() / len(cdata)
nonnulls = cdata[~null_sels]
if np.issubdtype(cdata.dtype, np.number) or np.all(nonnulls.str.isnumeric()):
class_table['class'].append(1)
elif np.all(nonnulls.str.isalpha()):
class_table['class'].append(0)
else:
class_table['class'].append(2)
class_table['null_ratio'].append(null_ratio)
for k in class_table:
class_table[k] = np.array(class_table[k])
if out is not None:
outfolder, saveopt = out
pd.DataFrame(class_table).to_csv(os.path.join(outfolder, f'{saveopt}_classTable.csv'), index=False)
return class_table
def get_data_label(tPDF, tLabels, label=None, STRIFY=True):
# TODO: add merge label function if needed
# Guarantee tLabels to be series
if label is None:
allLabels = tLabels.columns
return set(np.concatenate([allLabels, [c for c in tPDF.columns if '__' not in c]]))
else:
targetDF = None
if label in tLabels.columns:
targetDF = tLabels
elif label in tPDF.columns:
targetDF = tPDF
else:
raise RuntimeError(f'Unknown Label: {label}!')
LDLabels = targetDF[label]
if STRIFY:
LDLabels = LDLabels.astype('str')
return LDLabels
""" ########################################
################ Validation ################
######################################## """
def df_preprocess_cv_fit(data, y_col, model, preprocessor, cv, param_grid, metrics=None):
""" Function splits data into train test folds, preprocess data, and then tune the hyperparameter
data: pd.DataFrame with data to fit
y: column variable in data used for model fitting
model: sklearn style model
preprocessor: CV_df_Preprocessor instance
cv: sklearn style cv splitter class, e.g.
from sklearn.model_selection import StratifiedKFold, KFold
skf = StratifiedKFold(n_splits=3); skf.split(X, y)
param_grid: dictionary of {'model__*': ..., 'prep__*': ...} for gridsearch hyperparam tune
"""
y = data[y_col].values
all_res = []
pgrid = ParameterGrid(param_grid)
for i, (train_inds, test_inds) in enumerate(cv.split(data, y)):
for pdict in pgrid:
# use itertools to parse preprocessor arg
# use iter
model_p = {}
prep_p = {}
for k, v in pdict.items():
step, arg = k.split('__')
if step == 'model':
model_p[k] = v
else:
prep_p[k] = v
prep = preprocessor(**prep_p)
X, y = prep.fit_transform(data)
d_train_inds, d_test_inds = prep.index_train_test(train_inds, test_inds)
mdl = model(**model_p)
mdl.fit(X[d_train_inds], y[d_train_inds])
# metrics
m_res = {}
if metrics is None:
m_res['accuracy'] = mdl.score(X[d_test_inds], y[d_test_inds])
else:
for m in metrics:
scorer = check_scoring(mdl, m)
m_res[m] = scorer(mdl, X[d_test_inds], y[d_test_inds])
res_d = copy.deepcopy(model_p)
res_d.update(prep_p)
res_d.update(metrics)
res_d['iter'] = i
all_res.append(res_d)
result_df = pd.DataFrame(all_res)
return result_df
def auc_roc_2dist(d1, d2, method='QDA', k=5, return_dist=False):
X = np.concatenate((d1, d2)).reshape((-1, 1))
y = np.repeat([0, 1], len(d1))
if method == 'QDA':
clf = QDA()
elif method == 'LR':
clf = LogisticRegression(solver="liblinear", random_state=RAND_STATE)
if k == 1:
clf.fit(X, y)
return roc_auc_score(y, clf.predict_proba(X)[:, 1])
else:
kf = KFold(n_splits=k, shuffle=True, random_state=RAND_STATE)
roc_scores = []
for train_index, test_index in kf.split(X):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
test_probs = clf.fit(X_train, y_train).predict_proba(X_test)[:, 1]
# for NaNs we replace it with the opposite of test label!
nantp = np.isnan(test_probs)
if np.sum(nantp) > 0:
logging.warning("NaNs encountered in QDA prediction, interpret AUCROC with caution!")
test_probs[nantp] = 1-y_test[nantp]
roc_scores.append(roc_auc_score(y_test, test_probs))
if return_dist:
return roc_scores
else:
return np.mean(roc_scores)
def make_k_arange_segs(n, k):
# alternative method making split more even
inds = np.arange(n)
# block_f = n / k
# if block_f % 1 > 0.5:
# block = int(np.ceil(block_f))
# else:
# block = int(np.floor(block_f))
block = n // k
for i in range(k):
if i == k-1:
yield inds[i*block:]
else:
yield inds[i*block:(i+1)*block]
def ksplit_X_y(X, y, k):
for inds in make_k_arange_segs(len(X), k):
yield X[inds], y[inds]
def simple_metric(y, y_pred):
region = np.abs(y-np.mean(y)) <= np.std(y)
return 1 - (np.std((y[region]-y_pred[region])) / np.std(y[region])) ** 2
# return np.std((y[region]-y_pred[region]))
def fp_corrected_metric(y, y_pred, method):
region = np.abs(y-np.mean(y)) <= np.std(y)
metric_list = {'explained_variance': explained_variance_score,
'r2': r2_score}
return metric_list[method](y[region], y_pred[region])
""" ##########################################
################ Visualization ###############
########################################## """
def visualize_dimensionality_ratios(pca_full, dataset_name, JNOTEBOOK_MODE=False):
xs = np.arange(1, len(pca_full.singular_values_)+1)
ys = np.cumsum(pca_full.explained_variance_ratio_)
titre = dataset_name+' PCA dimension plot'
if JNOTEBOOK_MODE:
fig = px.line(pd.DataFrame({'components': xs, 'variance ratio': ys}),
x='components', y='variance ratio', title=titre)
fig.show()
else:
plt.plot(xs, ys, 'o-')
plt.xlabel('# Components')
plt.ylabel("cumulative % of variance")
plt.title(titre)
plt.show()
def dataset_dimensionality_probing(X_nonan_dm, dataset_name, visualize=True, verbose=True,
JNOTEBOOK_MODE=False):
# DIM Probing
pca_full = PCA().fit(X_nonan_dm) # N x D -> N x K * K x D
if visualize:
visualize_dimensionality_ratios(pca_full, dataset_name, JNOTEBOOK_MODE=JNOTEBOOK_MODE)
#automatic_dimension probing
# TODO: IMPLEMENT CROSS-VALIDATION BASED SELECTION
cumsum = np.cumsum(pca_full.explained_variance_ratio_)
ClusteringDim = np.where(cumsum >= 0.9)[0][0]+1 # Determine with the ratio plots MAS: 9
variance_ratio = np.sum(pca_full.explained_variance_ratio_[:ClusteringDim])
if verbose:
print(f"Capturing {100*variance_ratio:.4f}% variance with {ClusteringDim} components")
return pca_full, ClusteringDim
def visualize_loading_weights(pca, keywords, nth_comp, show=True):
xs = np.arange(keywords.shape[0])
loadings = pca.components_[nth_comp]
pos = loadings >= 0
plt.bar(xs[pos], loadings[pos], color='b', label='+weights')
plt.bar(xs[~pos], -loadings[~pos], color='r', label='-weights')
plt.xticks(xs, keywords, rotation=90)
plt.legend()
plt.subplots_adjust(bottom=0.3)
if show:
plt.show()
def save_loading_plots(decomp, keywords, model_name, plots):
outpath = os.path.join(plots, f'{model_name}_numerical_features')
if not os.path.exists(outpath):
os.makedirs(outpath)
for i in range(decomp.components_.shape[0]):
plt.figure(figsize=(15, 8))
visualize_loading_weights(decomp, keywords, i, show=False)
fname = os.path.join(outpath, f'{model_name}_numF_D{i+1}_loading')
plt.savefig(fname+'.png')
plt.savefig(fname+'.eps')
plt.close()
def visualize_feature_importance(values, names, thres=20, tag=''):
feat_imps, feat_imps_stds = values
sort_inds = np.argsort(feat_imps)[::-1]
if thres is not None and len(feat_imps) > thres:
feat_imps_slice = feat_imps[sort_inds[:thres]]
feat_imps_stds_slice = feat_imps_stds[sort_inds[:thres]]
names_slice = names[sort_inds[:thres]]
else:
feat_imps_slice, feat_imps_stds_slice = feat_imps[sort_inds], feat_imps_stds[sort_inds]
names_slice = names[sort_inds]
fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(20, 10))
axes[0].hist(feat_imps, weights=np.full_like(feat_imps, 1/len(feat_imps)))
axes[0].set_xlabel('feature importance')
axes[0].set_ylabel('percent')
xs = range(len(feat_imps_slice))
axes[1].bar(xs, feat_imps_slice, yerr=feat_imps_stds_slice, align="center")
axes[1].set(xticks=xs, xlim=[-1, len(xs)])
axes[1].set_xticklabels(names_slice, rotation=60)
fig.suptitle(tag)
#plt.show()
def visualize_2D(X_HD, labels, dims, tag, show=True, out=None, label_alias=None, axis_alias=None,
vis_ignore=None, JNOTEBOOK_MODE=False):
# TODO: implement saving for JNOTEBOOK_MODE
"""dims: 0 indexed"""
# change clustering
if vis_ignore is None:
vis_ignore = []
if not hasattr(dims, '__iter__'):
dims = [dims, dims + 1]
X_2D = X_HD[:, dims]
c0n = f'Comp {dims[0]+1}' if axis_alias is None else axis_alias[0]
c1n = f'Comp {dims[1]+1}' if axis_alias is None else axis_alias[1]
titre = f'{tag}_2D_{dims[0]}-{dims[1]}_vis'
if JNOTEBOOK_MODE:
# NO need to ignore in interactive mode
nlabels = len(labels.unique())
# TODO: blend in real labels of treatments
if labels.dtype == 'object':
cseq = sns.color_palette("coolwarm", nlabels).as_hex()
cmaps = {ic: cseq[i] for i, ic in enumerate(sorted(labels.unique()))}
if label_alias is not None:
newLabels = labels.copy(deep=True)
newCMAPs = {}
for l in labels.unique():
al = label_alias[l]
newLabels[labels == l] = al
newCMAPs[al] = cmaps[l]
labels = newLabels
cmaps = newCMAPs
else:
cmaps = None
fig = px.scatter(pd.DataFrame({c0n: X_2D[:, 0], c1n: X_2D[:, 1],
labels.name: labels.values}), x=c0n, y=c1n, color=labels.name,
color_discrete_map=cmaps, title=titre)
if show:
fig.show()
else:
uniqlabels = np.setdiff1d(np.unique(labels), vis_ignore)
nlabels = len(uniqlabels)
with plt.style.context('dark_background'):
fig = plt.figure(figsize=(15, 15))
ax = plt.gca()
sns.set_style(style='black')
if labels.dtype == 'object':
cseq = sns.color_palette('coolwarm', nlabels)
for i, l in enumerate(sorted(uniqlabels)):
ax.scatter(X_2D[labels == l, 0], X_2D[labels == l, 1], color=cseq[i], label=l)
ax.legend()
else:
cmap = sns.cubehelix_palette(as_cmap=True)
uniqsel = np.isin(labels, uniqlabels)
points = ax.scatter(X_2D[uniqsel, 0], X_2D[uniqsel, 1], c=labels[uniqsel], cmap=cmap)
fig.colorbar(points)
plt.title(f'{tag} 2D {dims} visualization')
plt.xlabel(c0n)
plt.ylabel(c1n)
if show:
plt.show()
if out is not None:
fname = os.path.join(out, titre)
plt.savefig(fname+'.png')
plt.savefig(fname+'.eps')
plt.close()
def save_LD_plots(X_LD, labels, tag, out, show=True):
# labels: pd.Series containing labels for different sample points
outpath = os.path.join(out, tag+"_2D", 'labelGroup_'+labels.name)
if not os.path.exists(outpath):
os.makedirs(outpath)
for i in range(X_LD.shape[1] - 1):
visualize_2D(X_LD, labels, i, tag, show=show, out=outpath)
def visualize_3D(X_HD, labels, dims, tag, show=True, out=None, label_alias=None,
vis_ignore=None, axis_alias=None, JNOTEBOOK_MODE=False):
# TODO: implement saving for JNOTEBOOK_MODE ADD DATASET NAME MAYBE?
"""dims: 0 indexed"""
if vis_ignore is None:
vis_ignore = []
# change clustering
if not hasattr(dims, '__iter__'):
dims = np.arange(dims, dims+3)
assert X_HD.shape[1] >= 3, 'not enough dimensions try 2d instead'
X_3D = X_HD[:, dims]
c0n = f'Comp {dims[0]+1}' if axis_alias is None else axis_alias[0]
c1n = f'Comp {dims[1]+1}' if axis_alias is None else axis_alias[1]
c2n = f'Comp {dims[2]+1}' if axis_alias is None else axis_alias[2]
titre = f'{tag}_3D_{dims[0]}-{dims[1]}-{dims[2]}_vis'
if JNOTEBOOK_MODE:
nlabels = len(labels.unique())
# TODO: blend in real labels of treatments
if labels.dtype == 'object':
cseq = sns.color_palette("coolwarm", nlabels).as_hex()
cmaps = {ic: cseq[i] for i, ic in enumerate(sorted(labels.unique()))}
if label_alias is not None:
newLabels = labels.copy(deep=True)
newCMAPs = {}
for l in labels.unique():
al = label_alias[l]
newLabels[labels == l] = al
newCMAPs[al] = cmaps[l]
labels = newLabels
cmaps = newCMAPs
else:
cmaps = None
fig = px.scatter_3d(pd.DataFrame({c0n: X_3D[:, 0], c1n: X_3D[:, 1], c2n: X_3D[:, 2],
labels.name: labels.values}), x=c0n, y=c1n, z=c2n,
color=labels.name, color_discrete_map=cmaps, title=titre)
if show:
fig.show()
else:
uniqlabels = np.setdiff1d(np.unique(labels), vis_ignore)
nlabels = len(uniqlabels)
with plt.style.context('dark_background'):
fig = plt.figure(figsize=(15, 15))
ax = fig.add_subplot(111, projection='3d')
sns.set_style(style='dark')
if labels.dtype == 'object':
cseq = sns.color_palette('coolwarm', nlabels).as_hex()
for i, l in enumerate(sorted(uniqlabels)):
ax.scatter(X_3D[labels == l, 0], X_3D[labels == l, 1], X_3D[labels == l, 2], s=100,
color=cseq[i], label=l)
ax.legend()
else:
cmap = sns.cubehelix_palette(as_cmap=True)
uniqsel = np.isin(labels, uniqlabels)
points = ax.scatter(X_3D[uniqsel, 0], X_3D[uniqsel, 1], X_3D[uniqsel, 2], s=100,
c=labels[uniqsel], cmap=cmap)
fig.colorbar(points)
plt.title(f'{tag} 3D {dims} visualization')
plt.xlabel(c0n)
plt.ylabel(c1n)
if show:
plt.show()
if out is not None:
fname = os.path.join(out, titre)
plt.savefig(fname+'.png')
plt.savefig(fname+'.eps')
plt.close()
def visualize_3d_multiple_surface_umap():
import plotly.graph_objects as go
for m in umap_accus:
if len(umap_accus[m].shape) == 1:
umap_accus[m] = umap_accus[m].reshape(umap_xs.shape)
fig = go.Figure(data=[go.Surface(x=umap_min_dists_seqs, y=umap_neighbor_seqs, z=umap_accus[m], showscale=False)
for m in umap_accus])
fig.update_layout({'title': 'UMAP', 'xaxis_title': 'min_dist', 'yaxis_title': 'neighbor'})
fig.show()
def visualize_3d_multiple_surface(data, title='3D surface'):
import plotly.graph_objects as go
fig = go.Figure(
data=[go.Surface(x=data['x']['data'], y=data['y']['data'], z=data['z']['data'], showscale=False)])
fig.update_layout({'title': title, 'xaxis_title': data['x']['name'],
'yaxis_title': data['y']['name'],
'zaxis_title': data['z']['name']})
fig.show()
def visualize_LD_multimodels(models, labels, dims, ND=3, show=True, out=None, label_alias=None,
vis_ignore=None, axis_alias=None, JNOTEBOOK_MODE=False):
for m in models:
model, X_LD = models[m]
vfunc = visualize_3D if min(X_LD.shape[1], ND) == 3 else visualize_2D
vfunc(X_LD, labels, dims, m, show=show, out=out, label_alias=label_alias,
vis_ignore=vis_ignore, axis_alias=axis_alias,
JNOTEBOOK_MODE=JNOTEBOOK_MODE)
def visualize_conn_matrix(mats, uniqLabels, affinity='euclidean', tag=None, cluster_param=3, label_alias=None,
confusion_mode=None, save=None):
"""
cite: https://www.kaggle.com/grfiv4/plot-a-confusion-matrix
:param mats:
:param uniqLabels:
:param affinity:
:param tag:
:param cluster_param:
:param confusion_mode: None if for other connectivity matrices, for confusion matrices: raw, normalize
by true, pred, or total
:return:
"""
# HANDLE dissimality more graceful
NM = len(list(mats.values())[0])
lxs = np.arange(len(uniqLabels))
# visualize confusing matrix, dissimilarity matrices and connectivity matrices
fig, axes = plt.subplots(nrows=NM, ncols=len(mats), sharex=True, sharey=True,
figsize=(len(mats) * 7, NM * 5))
for k, m in enumerate(mats):
for l, met in enumerate(mats[m]):
if NM * len(mats) == 1:
ax = axes
elif NM == 1:
ax = axes[k]
elif len(mats) == 1:
ax = axes[l]
else:
ax = axes[l][k]
# modify linkage
# TODO: modify method to accommodate 2D rows
mat2vis = mats[m][met]
if confusion_mode is not None:
if confusion_mode == 'true':
mat2vis = mat2vis / np.sum(mat2vis, keepdims=True, axis=1)
elif confusion_mode == 'pred':
mat2vis = mat2vis / np.sum(mat2vis, keepdims=True, axis=0)
elif confusion_mode == 'all':
mat2vis = mat2vis / np.sum(mat2vis)
hsort_mat, hsort_labels, hsort = conn_matrix_hierarchical_sort(mat2vis, uniqLabels,
affinity=affinity,
cluster_param=cluster_param)
if label_alias is not None:
hsort_labels = [label_alias[hl] for hl in hsort_labels]
clabels, ccounts = np.unique(hsort.labels_, return_counts=True)
cluster_edges = np.cumsum(ccounts) - 0.5
if affinity == 'precomputed':
hsort_mat = 1 / (hsort_mat + 1e-12)
if confusion_mode is not None:
# For confusion matrix, visualize accuracy
thresh = hsort_mat.max() / 1.5 if confusion_mode != 'raw' else hsort_mat.max() / 2
for i in range(hsort_mat.shape[0]):
for j in range(hsort_mat.shape[1]):
if confusion_mode != 'raw':
fm = "{:0.2f}"
else:
fm = "{:,}"
ax.text(j, i, fm.format(hsort_mat[i, j]),
horizontalalignment="center",
color="white" if hsort_mat[i, j] > thresh else "black")
fig.suptitle("Confusion Matrix For Classifiers")
elif affinity == 'precomputed':
thresh = hsort_mat.max() / 1.5 if confusion_mode != 'raw' else hsort_mat.max() / 2
for i in range(hsort_mat.shape[0]):
if confusion_mode != 'raw':
fm = "{:0.2f}"
else:
fm = "{:,}"
ax.text(i, i, fm.format(hsort_mat[i, i]),
horizontalalignment="center",
color="white" if hsort_mat[i, i] > thresh else "black")
fig.suptitle("Similarity Matrix Across classes")
else:
fig.suptitle("Raw Data Matrix Sorted With Dissimilarity")
pmp = ax.imshow(hsort_mat, cmap=plt.cm.get_cmap('Blues'))
ax.hlines(cluster_edges, -0.5, hsort_mat.shape[0] - 0.5, colors='k')
ax.vlines(cluster_edges, -0.5, hsort_mat.shape[0] - 0.5, colors='k')
ax.set_title(f"{m}_{met}" + f"_{tag}" if tag is not None else "")
ax.set_xticks(lxs)
ax.set_xticklabels(hsort_labels, rotation=45, horizontalalignment="right")
ax.set_ylabel('truth')
ax.set_yticks(lxs)
ax.set_yticklabels(hsort_labels)
ax.set_ylabel(f'{met}')
plt.colorbar(pmp, ax=ax)
if save is not None:
fig.savefig(os.path.join(save, f"{tag}_conn_matrix.eps"))
def visualize_F_measure_multi_clf(mats, uniqLabels, label_alias=None):
"""
cite: https://www.kaggle.com/grfiv4/plot-a-confusion-matrix
:param mats:
:param uniqLabels:
:param affinity:
:param tag:
:param cluster_param:
:param confusion_mode: None if for other connectivity matrices, for confusion matrices: raw, normalize
by true, pred, or total
:return:
"""
# HANDLE dissimality more graceful
NM = len(list(mats.values())[0])
# visualize confusing matrix, dissimilarity matrices and connectivity matrices
all_fmeas = []
if label_alias is not None:
label_show = [label_alias[hl] for hl in uniqLabels]
else:
label_show = uniqLabels
all_labels = np.tile(label_show, NM * len(mats))
all_dims = []
all_clfs = []
for m in mats:
all_dims.append((len(uniqLabels) * len(mats[m])) * [m])
for met in mats[m]:
all_clfs.append(len(uniqLabels) * [met])
f_meas = class_wise_F_measure(mats[m][met])
all_fmeas.append(f_meas)
F_pdf = pd.DataFrame({'DimReduction': np.concatenate(all_dims), 'Classifier': np.concatenate(all_clfs),
'Group': all_labels, 'F-measure': np.concatenate(all_fmeas)})
fig = px.bar(F_pdf, x="Group", y="F-measure", facet_row="Classifier", facet_col="DimReduction",
title=f"Class-wise F-measure For Classification (Chance: {1 / len(uniqLabels)})")
fig.show()
def feature_clustering_visualize(X, keywords, nclusters, show=True):
agglo = cluster.FeatureAgglomeration(n_clusters=nclusters)
agglo.fit(X)
ys = np.arange(keywords.shape[0])
labels = agglo.labels_
sorts = np.argsort(labels)
plt.barh(ys, labels[sorts])
plt.yticks(ys, keywords[sorts])
plt.subplots_adjust(left=0.3)
if show:
plt.show()
return agglo
#deprecated
def save_isomap_2D(iso, X_iso, plots, clustering=None):
if not os.path.exists(plots):
os.makedirs(plots)
for i in range(X_iso.shape[1]-1):
plt.figure(figsize=(15, 15))
if clustering is not None:
for l in np.unique(clustering.labels_):
plt.scatter(X_iso[clustering.labels_ == l, i], X_iso[clustering.labels_ == l, i+1], label=l)
plt.legend()
else:
plt.scatter(X_iso[:, i], X_iso[:, i+1])
plt.xlabel(f'Comp {i+1}')
plt.ylabel(f'Comp {i+2}')
fname = os.path.join(plots, f'iso_2D{i+1}-{i+2}_loading' + '_cluster' if clustering else '')
plt.savefig(fname+'.png')
plt.savefig(fname+'.eps')
plt.close()
def silhouette_plot(X, labels, cluster_arg=None, ax=None):
# Visualize Silhouette Plot
# Cite: https://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_silhouette_analysis.html
if ax is None:
ax = plt.gca()
n_clusters = len(np.unique(labels))
n_unique_labels = np.sort(np.unique(labels))
cpalette = sns.color_palette('Spectral', n_colors=n_clusters)
# The 1st subplot is the silhouette plot
# The silhouette coefficient can range from -1, 1 but in this example all
# lie within [-0.1, 1]
ax.set_xlim([-0.1, 1])
# The (n_clusters+1)*10 is for inserting blank space between silhouette
# plots of individual clusters, to demarcate them clearly.
ax.set_ylim([0, len(X) + (n_clusters + 1) * 10])
# The silhouette_score gives the average value for all the samples.
# This gives a perspective into the density and separation of the formed
# clusters
silhouette_avg = silhouette_score(X, labels)
if cluster_arg is None:
cluster_arg = f'n_clusters={n_clusters}'
print(f'For {cluster_arg}, "The average silhouette_score is : {silhouette_avg}')
# Compute the silhouette scores for each sample
sample_silhouette_values = silhouette_samples(X, labels)
y_lower = 10
for i in range(n_clusters):
# Aggregate the silhouette scores for samples belonging to
# cluster i, and sort them
ith_cluster_silhouette_values = sample_silhouette_values[labels == n_unique_labels[i]]
ith_cluster_silhouette_values.sort()
size_cluster_i = ith_cluster_silhouette_values.shape[0]
y_upper = y_lower + size_cluster_i