-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathML_Tools.py
More file actions
3545 lines (3287 loc) · 157 KB
/
ML_Tools.py
File metadata and controls
3545 lines (3287 loc) · 157 KB
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
import numpy as np
import pandas as pd
from math import *
import sys
import matplotlib.pyplot as plt
from _products.visualization_tools import *
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV, cross_val_score, train_test_split
from _products.utility_fnc import *
from sklearn import metrics
viz = Visualizer()
# =========================================================================
# =========================================================================
# TODO:Feature Selection and Preprocessing tools
# =========================================================================
# =========================================================================
def LCN_transform(df_base, target='Adoption', mtc=0, mxcc=1, corrs=('kendall', 'pearson'), inplace=False, verbose=False):
""" This will peform a LCN search and either return a reduced data frame
or reduce the given
:param df: data frame
:param target: the target('s) of the analysis
:param mtc: minimum target correlation
:param mxcc: maximum cross correlation between independent variables
:param corrs: types of correlation matrices to create
:param inplace: if true will modify original, otherwise returns a reduced version
:return:
"""
corr_dfk = df_base.corr(method=corrs[0])
corr_df = df_base.corr(method=corrs[1])
corr_df[target] = corr_dfk[target].values.flatten()
corr_df.loc[target, :] = corr_dfk.loc[target,:]
dfattribs = list(df_base.columns.values.tolist()).copy()
del dfattribs[dfattribs.index(target)]
print(dfattribs)
lcn_d = LCN(corr_df, target=target)
rl = HCTLCCL(lcn_d, [], target=target, options=dfattribs, target_corr_lim=mtc,
cross_corr_lim=mxcc)
if verbose:
print()
print('return features:')
print(rl)
print()
return df_base.loc[:, rl], df_base.loc[:, [target]]
# sorts a correlation and
def LCN(corr_M, threshold=100, target='Adoption'):
"""Takes a correlation matrix some threshold value and the name of the target column.
This method will use the given correlation matrix to create a dictionary for all features
in the matrix where the keys are the features and the values are a dictionary of all other
features as keys and vals are the key features correlations to those variables....
dict = {'feat1': {'feat2: correl_feat1_feat2}}
result is a dictionary keyed on the features, with values of a sorted dictionary keyed on other
features sorted on correlation
:param corr_M: correlation matrix
:param threshold: TODO: I don't remeber exactly what this does
:param target:
:return:
"""
# go through Data frame of correlations grabbing the list and sorting from lowest to
# grab the attribs
attribs = corr_M.columns.values.tolist()
lv1_d = {}
for ata in attribs:
lv1_d[ata] = dict()
for atb in attribs:
if ata != atb and atb != target:
if corr_M.loc[ata, atb] < threshold:
lv1_d[ata][atb] = abs(corr_M.loc[ata, atb])
if ata == target:
lv1_d[ata] = sort_dict(lv1_d[ata], reverse=True)
else:
lv1_d[ata] = sort_dict(lv1_d[ata], reverse=False)
return lv1_d
def HCTLCCL(corr_dic, start_vars, target, options, target_corr_lim = .09, cross_corr_lim=.55):
rl = list(start_vars)
for p_var in corr_dic[target]:
if corr_dic[target][p_var] > target_corr_lim and p_var not in rl and p_var in options:
rl = check_correlation(p_var, corr_dic, rl, '', cross_corr_lim)
if corr_dic[target][p_var] < target_corr_lim:
return rl
return rl
def check_correlation(check_var, corr_dic, cl, used, cross_corr_lim = .55):
# go through current list
for variable in cl:
# checking cross correlation between the possible
# variable to be added and the current one from
# the current list if it surpasses the threshold
# return the current list as is
if corr_dic[check_var][variable] > cross_corr_lim:
return cl
# if correlations with all current variables
# are within limits return the current list
# updated with the new value
return cl + [check_var]
def forward_selector_test(x, y, x2, y2):
pass
# =========================================================================
# =========================================================================
# TODO: Statistics and Preprocessing
# =========================================================================
# =========================================================================
class NORML():
"""a data normalizer. has two normalization methods
1) min max normalization:
* equation : (X-Min_val)/(Max_val - Min_val)
* rescales the data to [0,1] values
* centers pdf on the mean
2) z standardization (X-Min_val)/(Max_val - Min_val)
* equation : (X-Mean)/(Standard_Deviation)
* rescales the data to [-1,1] values
* centers pdf on 0 with std = 1
Select the type by setting the input argument
nrmlz_type to:
* : minmax for option 1
* : zstd for option 2
"""
def __init__(self, nrmlz_type='minmax'):
self.mu=None
self.std=None
self.cov=None
self.corr=None
self.cov_inv=None
self.cov_det=None
self.min = None
self.max = None
self.normlz_type=nrmlz_type
def set_type(self, n_type):
self.normlz_type = n_type
def fit(self, df=None, X=None):
if type(df) != type(np.array([0])):
df = pd.DataFrame(df)
self.process_df(df)
def process_df(self, df):
self.mu = df.values.mean(axis=0)
self.std = df.values.std(axis=0)
self.min = df.min()
self.max = df.max()
self.cov = df.cov()
self.cov_inv = np.linalg.inv(self.cov)
self.cov_det = np.linalg.det(self.cov)
def transform(self,df, headers=None):
if type(df) !=type(np.array([0])):
df = pd.DataFrame(df)
if self.normlz_type == 'zstd':
if headers is not None:
return pd.DataFrame((df - self.mu) / self.std, columns=headers)
return pd.DataFrame((df - self.mu) / self.std)
elif self.normlz_type == 'minmax':
if headers is not None:
return pd.DataFrame((df - self.min) / (self.max - self.min), columns=headers)
return pd.DataFrame((df - self.min) / (self.max - self.min))
def standardize_data(X, X2, scaler_ty='minmax'):
#scaler_ty = 'std'
if scaler_ty == 'minmax':
mm_scaler = MinMaxScaler()
mm_scaler.fit(X)
Xtrn = mm_scaler.transform(X)
Xtsn = mm_scaler.transform(X2)
elif scaler_ty == 'std':
std_scaler = StandardScaler()
std_scaler.fit(X)
Xtrn = std_scaler.transform(X)
Xtsn = std_scaler.transform(X2)
return Xtrn, Xtsn
def cross_val_splitter(X, y, tr=.5, ts=.5, vl=0, seed=None, verbose=False, target=None):
train_idx, val_idx, test_idx = split_data(X, y, p_train=tr, p_test=vl, p_val=ts, verbose=verbose,seed=seed)
def split_data(X, y, p_train=.70, p_test=.30, p_val=.0, priors = None, verbose=False, seed=False, lr=True):
"""Returns a randomized set of indices into an array for the purposes of splitting data"""
dXY = None
if type(X) != type(pd.DataFrame([0])):
nx = pd.DataFrame(X)
nx[X.shape[1]] = y.values.tolist()
dXY = nx.values
np.random.shuffle(dXY)
N = len(X)
train = int(np.around(N * p_train, 0))
if p_val == 0:
test = int(np.around(N * p_test, 0, ))
val = 0
else:
test = N - train
val = N - train - test
tr = dXY[0:train]
ts = dXY[train:train+test]
if p_val != 0:
vl = dXY[train+test:]
tr_X, tr_y = tr[:][0:len(dXY[0])], tr[:][len(dXY[0])]
ts_X, ts_y = ts[:][0:len(dXY[0])], ts[:][len(dXY[0])]
vl_X, vl_y = list(), list()
if p_val != 0:
vl_X, vl_y = tr[:][0:len(dXY[0])], tr[:][len(dXY[0])]
'''
if priors is not None:
print('need to set up the distribution of the weights')
if verbose:
print('train set size: ', train)
print('test set size: ', test)
print('val set size: ', val)
np.random.shuffle(X)
tr_idx = rc
for i in range(0, train):
trn_idx.append(r_c[i])
for i in range(train, train+test):
tst_idx.append(r_c[i])
for i in range(train+test, data_size):
val_idx.append(r_c[i])
if val == 0:
return trn_idx, tst_idx
else:
return trn_idx, tst_idx, val_idx
'''
if p_val != 0:
return (tr_X, tr_y), (ts_X, ts_y), (vl_X, vl_y)
return (tr_X, tr_y), (ts_X, ts_y), (vl_X, vl_y)
def gstandardize_data(X, X2, scaler_ty='minmax'):
if scaler_ty == 'minmax':
nrml = NORML()
nrml.fit(X)
Xr = nrml.transform(X)
xrts = nrml.transform(X2)
if scaler_ty == 'zstd':
nrml = NORML(scaler_ty=scaler_ty)
nrml.fit(X)
Xr = nrml.transform(X)
xrts = nrml.transform(X2)
return Xr, xrts
def normalize(X, mu, std, min, max, type='z', copy=False):
if type == 'z':
return z_normalize(X, mu, std)
elif type == 'mm':
return min_max_normalize(X, min, max)
def z_normalize(X, mu, std):
return pd.DataFrame((X - mu)/std, columns=X.columns)
def min_max_normalize(X, min, max):
return pd.DataFrame((X - min)/(max - min), columns=X.columns)
# =========================================================================
# =========================================================================
# TODO: Modeling tools
# =========================================================================
# =========================================================================
#Classification Model
class CMODEL():
"""a representation of a model for machine learning can in take in multiple data sets and perform
a column wise merge
"""
def __init__(self, file_list, exclude_list, target, df=None, usecols=None, usecol_list=None, verbose=False, lcn=False,
labeled=True, joins=('fips', 'fips', 'fips'), impute='drop', nas=(-999, ), drop_joins=False,st_vars=[],
mtc=.0, mxcc=1, dim_red=None, split_type='tt', tr_ts_vl = (.6, .4, 0), normal =None, complx=False):
self.normlz = normal
self.target = target # the current models classification objective
self.classes = list() # the class values for this model
self.model_mean = None # the attribute mean values
self.model_std = None # the attribute std values
self.model_cov = None
self.model_cov_det = None
self.model_cov_inv = None
self.class_splits = dict() # the data set split by class
self.class_counts = dict() # a count for each class in the data set
self.class_priors = dict() # the prior probaility of each class initialized by data set
self.class_means = dict() # the attribute means for each class
self.class_std = dict() # the attribute std for each class
self.class_cov = dict() # the covariance matrix for each class
self.class_cor = dict()
self.class_cov_inv = dict() # the covariance matrix inverse for each class
self.class_cov_det = dict() # the class covariance matrix determinant
self.attribs = None # the names of the attributes by column
self.excluded=None # the excluded variables, can be added back as onehot encoded versions
self.data_set=None # holds the desired data set
self.og_dataset= None # the merged set before any preprossing
self.data_corr = None
self.X = None # data or independent variables
self.y = None # the target values or dependent variable
self.Xtr_n=None
self.Xts_n=None
self.corr = None # the correlation matrix for the data
self.Xfld = None # an fld transformed version of the data
self.Xpca = None # a pca transformed version of the data
self.dim_red = DimensionReducer() # the models dimension reducer
self.Xts=None
self.yts=None
self.complx=complx
self.process_files(file_list, exclude_list, target, usecols, usecol_list, verbose, labeled, joins,
impute, nas, drop_joins=drop_joins, lcn=lcn, mtc=mtc, mxcc=mxcc, tr_ts_vl=tr_ts_vl,
df=df, st_vars=st_vars)
def process_files(self, file_list, exclude_list, target, usecols, usecol_list, verbose, labeled,
joins=('fips', 'fips', 'fips'), impute='drop', nas=(-999,), drop_joins=False,
lcn=False, mtc=.1, mxcc=.4, tr_ts_vl=(.6, .4, 0), df=None, to_encode=None, drops=None, st_vars=[]):
df_list = list([])
# go through and create and clean up data frames
# dropping those in the exclude list
doit=True
if drops is None:
tormv = list()
else:
tormv = drops
# If there was a data frame passed
if df is not None:
self.og_dataset = df
self.excluded = tormv
if to_encode is not None:
hold_over = df.low[:, to_encode]
else:
# loop to set up input do data merger
for df, ex in zip(file_list, exclude_list):
print('Data file:', df)
print('adding to be excluding', ex)
df_list.append(pd.read_excel(df))
tormv += ex
#if doit and len(ex) > 0:
self.excluded = tormv
self.og_dataset = data_merger(df_list, joins=joins, verbose=verbose, drop_joins=True, target=target)
#print(self.og_dataset)
merged = self.og_dataset.drop(columns=tormv, inplace=False)
self.data_corr = merged.sort_values(by=target, axis='index', ascending=False).corr(method='kendall')
if usecols is not None:
merged = merged.loc[:, usecols]
self.data_corr = merged.corr(method='kendall')
if lcn:
self.data_corr = merged.corr(method='kendall')
lcn_d = LCN(self.data_corr, target=target)
rl = HCTLCCL(lcn_d, st_vars, target=target, options=merged.columns.values.tolist(), target_corr_lim=mtc,
cross_corr_lim=mxcc)
merged = merged.loc[:, rl + [target]]
print('columns used:')
print(merged.columns)
if impute == 'drop':
for n in nas:
merged.replace(n, np.nan) # this value is used by the SVI data set to represent missing data
merged = merged.dropna()
self.data_set = merged
self.attribs = merged.columns.values.tolist()
print(self.attribs)
del self.attribs[self.attribs.index(self.target)]
self.X = pd.DataFrame(merged.loc[:, self.attribs], columns=self.attribs)
self.y = pd.DataFrame(merged.loc[:, self.target], columns=[self.target])
# TODO: NOW SPLIT THE DATA INTO DESIRED NUMBER OF FOLDS
targets0 = self.y[target]
ts = tr_ts_vl[1] + tr_ts_vl[2]
print('ts size', ts)
tr = 1 - ts
# Create training and testing sets for the data
X_train0, X_test0, y_train0, y_test0 = train_test_split(self.X, targets0, stratify=targets0, test_size=ts,
train_size=tr, )
self.train_counts = y_train0.value_counts(normalize=True)
self.test_counts = y_test0.value_counts(normalize=True)
self.X, self.y = pd.DataFrame(X_train0, columns=self.attribs), pd.DataFrame(y_train0, columns=[self.target])
self.Xts, self.yts = pd.DataFrame(X_test0, columns=self.attribs), pd.DataFrame(y_test0, columns=[self.target])
self.N = self.X.shape[0]
self.Nts = self.Xts.shape[0]
self.d = self.X.shape[1]
self.corr = self.X.corr()
if self.normlz is not None:
print('Normalize', self.normlz)
self.X, self.Xts = standardize_data(self.X, self.Xts, scaler_ty=self.normlz)
self.X = pd.DataFrame(self.X, columns=self.attribs)
self.Xts = pd.DataFrame(self.Xts, columns=self.attribs)
self.y.index = self.X.index
self.yts.index = self.Xts.index
print('y len', len(self.y.values))
print('X len', len(self.X.values))
self.grab_model_stats()
# TODO: need to a some time move LCN stuff here
# grab class specific stats
self.calculate_class_stats()
self.model_data = list((self.X, self.y)) # store data and labels together in lit
def grab_model_stats(self):
print(self.X.values)
print(self.X)
self.model_mean = self.X.values.mean(axis=0)
self.model_std = self.X.values.std(axis=0).mean()
self.model_cov = self.X.cov()
if self.complx:
self.model_cov_inv = np.linalg.inv(self.model_cov)
self.model_cov_det = np.linalg.det(self.model_cov)
def calculate_class_stats(self):
self.classes = list(set(self.y[self.target]))
print('classes', self.classes)
for c in self.classes:
self.splits_priors(c)
self.class_means_std(c)
if self.complx:
self.class_cov_inv_det(c)
self.class_cor[c] = self.class_splits[c].corr()
def splits_priors(self,c):
self.class_splits[c] = self.X.loc[self.y[self.target] == c, :]
self.class_counts[c] = self.class_splits[c].shape[0]
self.class_priors[c] = self.class_splits[c].shape[0] / self.N
def class_means_std(self,c):
self.class_means[c] = self.class_splits[c].values.mean(axis=0)
self.class_std[c] = self.class_splits[c].values.std(axis=0)
def class_cov_inv_det(self, c):
self.class_cov[c] = self.class_splits[c].cov()
if self.complx:
self.class_cov_inv[c] = np.linalg.inv(self.class_cov[c].values)
self.class_cov_det[c] = np.linalg.det(self.class_cov[c].values)
def show_data_report(self):
print('=======================================================================================')
print('Train data size:', self.X.shape[0])
print('y_train class distribution 0')
print(self.train_counts)
print('Test data size:', self.Xts.shape[0])
print('y_test class distribution 0')
print(self.test_counts)
print('=======================================================================================')
print('Features in Model:')
print(self.X.columns.values)
print('Predicting for {}'.format(self.target))
def Reduce_Dimension(self, dr_type='FLD', pov=None, pc=None):
if dr_type == 'FLD':
self.perform_FLD()
def perform_FLD(self):
self.dim_red.fld_fit(self)
self.Xfld = self.dim_red.FLD(self.X)
self.tsXfld = self.dim_red.FLD(self.X)
class RMODEL():
def __init__(self, X=None, Y=None, columns=None, impute=None, verbose=False, trtsspl=(.7, ),
n_type=None):
self.X = np.array(X)
self.Y = np.array(Y)
if columns is None:
self.dataframe = pd.DataFrame(self.X)
else:
self.dataframe = pd.DataFrame(self.X, columns=columns)
self.dataframe['target'] = Y
self.Xtr = None
self.ytr = None
self.Xts = None
self.yts = None
self.train_test_split = trtsspl
self.cross_val_split()
self.columns = columns
self.impute=impute
self.verbose=verbose
self.normalizer = NORML()
self.n_type=n_type
if n_type is not None:
self.normalize()
def cross_val_split(self):
if self.train_test_split[0] == 0:
self.Xtr = self.X
self.Xts = self.X
self.ytr = self.Y
self.yts = self.Y
return
else:
np.random.shuffle(np.array(self.X))
def normalize(self, n_type='minmax'):
self.normalizer.set_type(n_type=n_type)
self.normalizer.fit(self.Xts)
self.Xtr = self.normalizer.transform(self.X)
self.Xts = self.normalizer.transform(self.Xts)
# =========================================================================
# =========================================================================
# TODO: Dimension Reduction tools
# =========================================================================
# =========================================================================
class DimensionReducer():
def __init__(self):
self.type=None
self.class_splits=None
self.classes=None
self.class_means=None
self.data_means=None
self.data_std = None
self.class_cov=None
self.class_cov_inv=None
self.class_cov_det=None
self.class_priors=None
self.class_counts=None
self.eig_vec = None
self.eig_vals = None
self.pval = None
self.W = None
self.WT = None
self.WT2 = None
self.k=None
self.k_90 = None
self.s = None
self.vh = None
self.i_l = list()
self.dr_type = None
self.y2 = None
self.x2 = None
self.x1 = None
self.y1 = None
self.N = None
self.z, self.one = list(), list()
def FLDA(self, df, dftr, y, classes=(0,1), class_label='type'):
y = pd.DataFrame(y, columns=[class_label])
c1 = dftr.loc[y[class_label] == classes[0], :]
n1 = len(c1)
c2 = dftr.loc[y[class_label] == classes[1], :]
n2 = len(c2)
#print('There are {0} negative and {1} positive samples'.format(n1, n2))
Sw_inv = np.linalg.inv((n1-1)*c1.cov() + (n2-1)*c2.cov())
#print(Sw_inv.shape)
#print(c1.mean().shape)
#w = np.dot(Sw_inv, np.dot((c1.mean() - c2.mean()), (c1.mean()-c2.mean()).transpose()))
w = np.dot(Sw_inv, (c1.values.mean(axis=0) - c2.values.mean(axis=0)))
#print('w', w.shape)
#print('df', df.shape)
return np.dot(df,w)
def fld_fit(self, cmodel):
self.dr_type = 'fld'
self.attribs = cmodel.attribs
self.class_splits = cmodel.class_splits
self.class_counts = cmodel.class_counts
self.classes = cmodel.classes
self.class_means = cmodel.class_means
self.data_means = cmodel.model_mean
self.data_std = cmodel.model_std
self.class_cov = cmodel.class_cov
self.class_cov_inv = cmodel.class_cov_inv
self.class_cov_det = cmodel.class_cov_det
self.class_priors = cmodel.class_priors
self.N=None
self.kmm=None
self.Calculate_W_FLD()
def pca_fit(self, X):
self.eig_vals, self.eig_vec = np.linalg.eig(X.cov())
#print('eigvec', self.eig_vec)
self.N = len(X)
print('eigvals', self.eig_vals)
def svd_w_np(self, X):
u, s, vh = np.linalg.svd(X, full_matrices=False, compute_uv=True)
self.s = s
self.vh = vh
self.N = len(X)
self.d = X.shape[1]
return
def svd_pov(self, s, accuracy=.90, verbose=False, pov_plot=False, show_now=False):
sum_s = sum(s.tolist())
ss = s**2
sum_ss = sum(ss.tolist())
self.prop_list = list()
found = False
k = 0
x1, y1, x2, y2, = 0, 0, 0, 0
p_l, i_l = 0, 0
found = False
self.prop_list.append(0)
self.i_l.append(0)
for i in range(1, len(ss)+1):
perct = sum(ss[0:i]) / sum_ss
# perct = sum(s[0:i]) / sum_s
if np.around(perct, 2) >= accuracy and not found:
self.x1 = i
self.y1 = perct
found = True
self.prop_list.append(perct)
self.i_l.append(i)
self.single_vals = np.arange(1, self.N + 1)
if pov_plot:
plt.figure()
plt.plot(self.i_l, self.prop_list)
plt.scatter(self.x1, self.y1, c='r', marker='o', label='Point at {:.1f}% accuracy'.format(self.y1*100))
plt.title('Proportion of Variance vs. Number of Eigen Values\n{:d} required for {:.2f}'.format(self.x1, self.y1*100))
plt.legend()
plt.xlabel('Number of Eigen values')
plt.ylabel('Proportion of Variance')
if show_now:
plt.show()
return self.x1 + 1
def svd_fit(self,X, vh=None, k=None, get_pov=True, pov_thresh=.90, verbose=False, plot=False, usek=False,
gen_plot=True, y=None):
if vh is None:
self.svd_w_np(X)
u, s, vh = np.linalg.svd(X, full_matrices=False, compute_uv=True)
if get_pov:
print('getting pov')
self.kmm = self.svd_pov(s, accuracy=pov_thresh, verbose=verbose, pov_plot=plot, show_now=True)
if usek:
k = self.kmm
self.N = len(X)
self.data_means = X.mean(axis=0).values.flatten()
#print('data means', self.data_means)
print('vector shape', vh.shape)
#vt = np.transpose(self.vh)
vt = np.transpose(self.vh)
# grab the first k principle components
if k is not None:
self.W = vt[:, 0:k]
self.k = k
else:
self.W = vt[:, :]
self.k = len(X)
self.WT = np.transpose(self.W)
# grab the first two principle components
W2 = vt[:, 0:2]
W3 = vt[:, 0:3]
self.WT2 = np.transpose(W2)
self.WT3 = np.transpose(W3)
if gen_plot:
# get 0's and 1's
for row, adp in zip(self.WT2, y):
if adp == 0:
self.z.append(row)
else:
self.one.append(row)
def svd_transform(self, X, treD=False):
z_array = list()
z2_array = list()
z3_array = list()
for row in X.values:
#print('row',row)
#print('data means')
#print(self.data_means)
c_x = row - self.data_means
z_array.append(np.dot(self.WT, c_x))
z2_array.append(np.dot(self.WT2, c_x))
if treD:
z3_array.append(np.dot(self.WT3, c_x))
Z = np.array(z_array, dtype=np.float)
Z2 = np.array(z2_array, dtype=np.float)
if treD:
Z3 = np.array(z3_array, dtype=np.float)
return Z, Z2, Z3
return Z, Z2
def Calculate_W_FLD(self, ):
c1 = self.class_splits[0]
n1 = self.class_counts[0]
c2 = self.class_splits[1]
n2 = self.class_counts[1]
# TODO: evalute below to see if needed or not
if False and type(c1) != type(pd.DataFrame({0:0})):
c1 = pd.DataFrame(c1).values
c2 = pd.DataFrame(c2).values
Sw_inv = np.linalg.inv((n1 - 1) * c1.cov() + (n2 - 1) * c2.cov())
self.W_fld = np.dot(Sw_inv, (c1.values.mean(axis=0) - c2.values.mean(axis=0)))
def pca_transform(self, X, p=None):
if p is None:
return self.convert_basis(X, self.eig_vec)
else:
return self.convert_basis(X, self.eig_vec[0:p])
def FLD(self, X):
return pd.DataFrame(np.dot(X,self.W_fld))
def PCA(self, df, pov, eig_vec=None, m=None, verbose=False, ret_level=0,
pov_plot=False, show_now=False):
# if not given eigen values calculate them based on the
# desired proportion of variance (pov) covered
if eig_vec is None:
#print(df.cov())
eig_vals, eig_vec = np.linalg.eig(df.cov())
if m is None:
pov_l, m = self.calculate_p(eig_vals=eig_vals, pov=pov, verbose=verbose, show_now=show_now,
pov_plot=pov_plot)
print('The Number of eigenvectors to cover {:.2f} of the variance is {:d}'.format(100*pov, m))
else:
pov_l, cm = self.calculate_p(eig_vals=eig_vals, pov=pov, verbose=verbose, show_now=show_now,
pov_plot=pov_plot)
print('The number of eigenvectors is set to {:d}'.format(m))
#print(eig_vec)
eig_vec = eig_vec[0:m]
# now perform transform
y = self.convert_basis(df, pd.DataFrame(eig_vec))
if ret_level == 0:
return y
elif ret_level == 2:
return pov_l, m, eig_vec, pd.DataFrame(y)
elif ret_level == 1:
return eig_vec, y
def calculate_p(self, pov, eig_vals=None, verbose=False, pov_plot=False, show_now=False):
#print('calculating k')
# calculate total sum
if eig_vals is None:
eig_vals = self.eig_vals
s_m = sum(eig_vals)
if verbose:
print('The sum of the eigen values is {0}'.format(s_m))
print('The length of the eigen values vector is {0}'.format(len(eig_vals)))
print('here it is')
print(eig_vals)
# now go through to find your required k for the
# desired Proportion of Variance (pov)
pov_l, cpov, csum, k, found = [], 0, 0, 0, False
pov_found = 0
for v in range(len(eig_vals)):
csum += np.around(eig_vals[v], 2)
pov_l.append(np.around(csum/s_m, 2))
if verbose:
print('The sum at {:d} is {:.2f}, pov {:.2f}'.format(v, csum, pov_l[v]))
if pov_l[-1] >= pov and not found:
k = v+1
pov_found = pov_l[-1]
print(k, pov_found)
found = True
if pov_plot:
plt.figure()
plt.plot(list(range(1, len(eig_vals)+1)), pov_l)
plt.scatter(k, pov_found, c='r', marker='o', label='Point at {:.1f}% accuracy'.format(pov_found*100))
plt.title('Proportion of Variance vs. Number of Eigen Values')
plt.legend()
plt.xlabel('Number of Eigen values')
plt.ylabel('Proportion of Variance')
if show_now:
plt.show()
self.pov_l = pov_l
self.k = k
return pov_l, k
def convert_basis(self, df, new_basis):
return np.dot(df, new_basis.transpose())
def PCA_Eig(self, X, class_means):
return 1
def PCA_SVD(self, X):
return 1
# =========================================================================
# =========================================================================
# TODO: Learners
# =========================================================================
# =========================================================================
def epsilon(emax, emin, k, kmax):
return emax * ((emin/emax)**(min(k, kmax)/kmax))
class Learner(ABC):
"""Template class for a learning machine"""
def __init__(self,):
pass
def finish_init(self):
pass
def fit(self, cmodel):
pass
def predict(self, X):
pass
def score(self, X, Y):
pass
class bayes_classifiers(Learner):
def __init__(self, cmodel=None, df_list=None, case=1):
super().__init__()
self.fit(cmodel=cmodel)
self.case = case
if self.case == 1:
self.func = 'euclid'
elif self.case == 2:
self.func = 'mahala'
if self.case == 1:
self.func = 'euclid'
elif self.case == 3:
self.func = 'quadratic'
def fit(self, cmodel):
self.cmodel = cmodel
def bayes_classifier_model_finder(self, dfx, dfy, case=1, func='euclid', scale= .1, verbose=False,
priors=()):
#n, p = list(), list()
#f, b = .10, .90
#while f <= b:
# n.append(b)
# p.append(f)
# f += scale
# b -= scale
#back = n[0:]
#rback = n[0:]
#rback.reverse()
#ford = p[0:-1]
#rford = ford[0:]
#rford.reverse()
#pos = ford + rback
#neg = back + rford
if len(priors) == 0:
pos, neg = self.generate_priors(scale=scale)
else:
if scale is not None:
pos, neg = self.generate_priors(scale=scale, prior1=priors[0], prior2=priors[1])
else:
pos, neg = list([priors[0]]), list([priors[1]])
#print(pos)
#print(neg)
best_acc, best_scr, best_posnegs, scr = 0, None, None, 0
pr_l1, pr_l2, accuracy , sens, spec= list(), list(), list(), list(), list()
best_pr = [0, 0]
for ps, ng in zip(pos, neg):
pr = [ps, ng]
#print(pr[0] + pr[1])
acc, scr, posnegs = self.bayes_classifier_predict_and_score(dfx, dfy, case=case, priors=pr, func=func, verbose=verbose)
accuracy.append(acc)
pr_l1.append(pr[0])
pr_l2.append(pr[1])
sens.append(posnegs['sen'])
spec.append(posnegs['spe'])
if acc > best_acc:
best_acc = acc
best_scr = scr
best_posnegs = posnegs
best_pr[0] = pr[0]
best_pr[1] = pr[1]
result_dic = {'best_accuracy':best_acc,
'best_scores':best_scr,
'best_postnegs':best_posnegs,
'pr_l1':pr_l1,
'pr_l2':pr_l2,
'sens':sens,
'spec':spec,
'accuracy_list':accuracy,
'best_priors': best_pr}
#return best_acc, best_scr, best_posnegs, pr_l1, pr_l2, sens, spec, accuracy, best_pr
return result_dic
def bayes_classifier_model_finderB(self, dfx, dfy, case=1, func='euclid', scale= .1, verbose=False,
priors=()):
#n, p = list(), list()
#f, b = .10, .90
#while f <= b:
# n.append(b)
# p.append(f)
# f += scale
# b -= scale
#back = n[0:]
#rback = n[0:]
#rback.reverse()
#ford = p[0:-1]
#rford = ford[0:]
#rford.reverse()
#pos = ford + rback
#neg = back + rford
if len(priors) == 0:
pos, neg = self.generate_priors(scale=scale)
else:
if scale is not None:
pos, neg = self.generate_priors(scale=scale, prior1=priors[0], prior2=priors[1])
else:
pos, neg = list([priors[0]]), list([priors[1]])
print(pos)
print(neg)
best_acc, best_scr, best_posnegs, scr = 0, None, None, 0
pr_l1, pr_l2, accuracy , sens, spec= list(), list(), list(), list(), list()
best_pr = [0, 0]
for ps, ng in zip(pos, neg):
pr = [ps, ng]
#print(pr[0] + pr[1])
acc, scr, posnegs = self.bayes_classifier_predict_and_scoreB(dfx, dfy, case=case, priors=pr, func=func, verbose=verbose)
accuracy.append(acc)
pr_l1.append(pr[0])
pr_l2.append(pr[1])
sens.append(posnegs['sen'])
spec.append(posnegs['spe'])
if acc > best_acc:
best_acc = acc
best_scr = scr
best_posnegs = posnegs
best_pr[0] = pr[0]
best_pr[1] = pr[1]
result_dic = {'best_accuracy': best_acc,
'best_scores': best_scr,
'best_postnegs': best_posnegs,
'pr_l1': pr_l1,
'pr_l2': pr_l2,
'sens': sens,
'spec': spec,
'accuracy_list': accuracy,
'best_priors': best_pr}
# return best_acc, best_scr, best_posnegs, pr_l1, pr_l2, sens, spec, accuracy, best_pr
return result_dic
def bayes_classifier_predict(self, dfx, case=1, verbose=False, priors = [1,1], func='euclid'):
ypred = list()
case = self.case
func = self.func
# figure out the priors situation
if priors is None:
prior1 = self.cmodel.class_priors[0]
prior2 = self.cmodel.class_priors[1]
else:
prior1 = priors[0]
prior2 = priors[1]
#print('====================================> Priors: ', prior1, prior2)
# figure out what discriminant function to use
if case == 1:
func = 'euclid'
#cov = self.gauss_params['std'] ** 2
cov = self.cmodel.model_std ** 2
print('cov', cov)
elif case == 2:
func = 'mahala'
cov = self.cmodel.model_cov
elif case == 3:
func = 'quadratic'
cov = [self.cmodel.class_cov[0], self.cmodel.class_cov[1]]
#mu1 = self.gauss_params['mu_c1']
#mu1 = self.gauss_params['mu_c1']
#mu1 = self.Cmu_array[0]
#mu2 = self.Cmu_array[1]
mu1 = self.cmodel.class_means[0]
mu2 = self.cmodel.class_means[1]
#print(func)
# make some predictions
for xi in dfx.values:
if case != 3:
pc1 = self.discriminate_function(xi, mu1, cov, prior1, func=func)
pc2 = self.discriminate_function(xi, mu2, cov, prior2, func=func)
else:
#print(func)
pc1 = self.discriminate_function(xi, mu1, cov[0], prior1, func=func)
pc2 = self.discriminate_function(xi, mu2, cov[1], prior2, func=func)
if verbose:
print('pc1',pc1)
print('pc2',pc2)
if pc1 > pc2:
ypred.append(0)
else:
ypred.append(1)
return ypred
def bayes_classifier_predict_and_scoreB(self, dfx, dfy, case=1, priors=[1,1], func='euclid', verbose=False):
case = self.case
func = self.func
ypred = self.bayes_classifier_predict(dfx, case=case, priors=priors, func=func, verbose=verbose)
return self.bayes_classifier_score(dfy, ypred)
def bayes_classifier_predict_and_score(self, dfx, dfy, case=1, priors=[1,1], func='euclid', verbose=False):
case = self.case
func = self.func
ypred = self.bayes_classifier_predict(dfx, case=case, priors=priors, func=func, verbose=verbose)
return self.bayes_classifier_score(dfy, ypred)
def bayes_classifier_score(self, yactual, ypred, vals = [0,1]):
return bi_score(ypred, yactual, vals, classes=vals)
def generate_priors(self, scale, prior1=None, prior2=None):
if prior1 is not None and prior2 is not None:
# set up prior1 side
if prior1 < prior2:
l1 = list([1])
l2 = list([.0001])
while l1[-1] - scale >= prior1:
l1.append(l1[-1] - scale)
l2.append(1 - l1[-1])
if l1[-1] - prior1 < 0:
l1[-1] = prior1
l2[-1] = 1 - prior1