-
Notifications
You must be signed in to change notification settings - Fork 6
/
partial_dependence.py
4324 lines (3067 loc) · 155 KB
/
partial_dependence.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
partial_dependence is a library for plotting partial dependency patterns
of machine learning classfiers. Partial dependence measures the
prediction change when changing one or more input features. We will
focus only on 1D partial dependency plots. For each instance in the data
we can plot the prediction change as we change a single feature in a
defined sample range. Then we cluster similar plots, e.g., instances
reacting similarly value changes, to reduce clutter. The technique is a
black box approach to recognize sets of instances where the model makes
similar decisions.
"""
from __future__ import print_function
from __future__ import division
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#import time
from itertools import combinations
from sklearn.cluster import AgglomerativeClustering
import scipy.interpolate as si
import sys
from matplotlib.legend import Legend
import matplotlib as mpl
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.gridspec as gridspec
import math
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
def custom_formatwarning(msg, *args, **kwargs):
return str(msg) + '\n'
warnings.formatwarning = custom_formatwarning
try:
unicode = unicode
except NameError:
# python 3
str = str
unicode = str
bytes = bytes
basestring = (str, bytes)
else:
# python 2
str = str
unicode = unicode
bytes = str
basestring = basestring
__version__ = "0.0.5"
class PdpCurves(object):
def __init__(self, preds):
self._preds = preds
self._ixs = np.arange(self._preds.shape[0])
self._dm = None
self.r_param = None
def copy(self):
return self.__copy__()
def __copy__(self):
res = type(self)(self._preds)
res.__dict__.update(self.__dict__)
return res
def get_mean_distances(self, cluster_A, cluster_B):
dist_mtrx = self._dm
real_A = cluster_A[1]
real_B = cluster_B[1]
lab_A = cluster_A[0]
lab_B = cluster_B[0]
if lab_A == lab_B:
return 1.1
inst_A_list = real_A.get_ixs()
inst_B_list = real_B.get_ixs()
distance_list = []
for a in inst_A_list:
for b in inst_B_list:
distance_list.append(dist_mtrx[a,b])
return np.mean(distance_list)
def split(self,labels_cluster):
if labels_cluster is None:
return [ (None, self.copy()) ]
def get_slice(c, lbl):
c._preds = self._preds[labels_cluster == lbl, :]
if self._dm is not None:
c._dm = self._dm[labels_cluster == lbl, :][:, labels_cluster == lbl]
c._ixs = self._ixs[labels_cluster == lbl]
return c
def get_macro_dist(clusters_input):
pairs_of_clusters = []
for comb in combinations(list_of_clusters, 2):
pairs_of_clusters.append(comb)
num_cluster_here = len(list_of_clusters)
macro_dist_matrix = np.zeros((num_cluster_here,num_cluster_here))
for i in list_of_clusters:
for j in list_of_clusters:
macro_dist_matrix[i,j] = self.get_mean_distances(clusters_input[i],
clusters_input[j])
return macro_dist_matrix
list_of_clusters = np.unique(labels_cluster)
curves_list = []
for lbl in list_of_clusters:
the_slice = get_slice(self.copy(), lbl)
curves_list.append((lbl, the_slice))
return (curves_list,get_macro_dist(curves_list))
def get_ixs(self):
return self._ixs
def get_preds(self):
return self._preds
def get_dm(self, never_splom = False):
if self._dm is None:
self._dm = self._compute_dm()
return self._dm
def _compute_dm(self):
preds = self._preds
lenTest = len(preds)
def rmse(curve1, curve2):
return np.sqrt(((curve1 - curve2) ** 2).mean())
def lb_keogh(s1, s2, r):
LB_sum=0
for (ind, i) in enumerate(s1):
lower_bound=min(s2[(ind - r if ind - r >= 0 else 0):(ind + r)])
upper_bound=max(s2[(ind - r if ind - r >= 0 else 0):(ind + r)])
if i > upper_bound:
LB_sum = LB_sum + (i - upper_bound) ** 2
elif i < lower_bound:
LB_sum = LB_sum + (i - lower_bound) ** 2
return np.sqrt(LB_sum)
if self.r_param is None:
lb_keogh_bool = False
else:
lb_keogh_bool = True
list_of_test_indexes = list(range(lenTest))
pairs_of_curves = []
for comb in combinations(list_of_test_indexes, 2):
pairs_of_curves.append(comb)
distance_matrix = np.zeros((lenTest, lenTest))
for pair in pairs_of_curves:
i = pair[0]
j = pair[1]
if lb_keogh_bool:
distance = lb_keogh(preds[i], preds[j], self.r_param)
else:
distance = rmse(preds[i], preds[j])
distance_matrix[i, j] = distance
distance_matrix[j, i] = distance
distance_matrix[i, i] = 0.0
return distance_matrix
def get_keogh_radius(self):
return self.r_param
def set_keogh_radius(self, r_param):
self._dm = None
self.r_param = r_param
class Pdp2DCurves(object):
def __init__(self, raw, original_ps, ixs, feat_y, feat_x):
self._raw = raw
self._origs = original_ps
self._ixs = ixs
self.A = feat_y
self.B = feat_x
self._dm = None
self.sample_A = None
self.sample_B = None
self.heat_map = None
def get_sample_A(self):
return self.sample_A
def get_sample_B(self):
return self.sample_B
def get_A(self):
return self.A
def get_B(self):
return self.B
def compute_heatmap(self):
heatmap_datas = []
num_samples = self._raw.shape[1]
num_inst = len(self._ixs)
for i in range(num_inst):
single_pdp = self._raw[i]
orig_pred = self._origs[i]
heatmap_datas.append(single_pdp-orig_pred)
heatmap_data_final = []
for i in range(num_samples):
heatmap_data_final.append(list(np.zeros(num_samples)))
for heat in heatmap_datas:
heatmap_data_final+=heat
heatmap_data_final = heatmap_data_final / num_inst
return heatmap_data_final
def get_data(self):
if self.heat_map is None:
self.heat_map = self.compute_heatmap()
return self.heat_map
def get_preds(self):
return self._raw
def get_origs(self):
return self._origs
def get_ixs(self):
return self._ixs
def set_sample_data(self,A_sample,B_sample):
self.sample_A = A_sample
self.sample_B = B_sample
def get_sample_data(self):
return self.sample_A, self.sample_B
def copy(self):
return self.__copy__()
def __copy__(self):
res = type(self)(self._raw, self._origs, self._ixs, self.A, self.B)
res.__dict__.update(self.__dict__)
return res
def swap_features(self):
swapped_copy = self.copy()
swapped_copy.heat_map = self.get_data().transpose()
raws = []
for r in self._raw:
raws.append(r.transpose())
raws = np.array(raws)
swapped_copy._raw = raws
swapped_copy.A = self.B
swapped_copy.B = self.A
swapped_copy.sample_A = self.sample_B
swapped_copy.sample_B = self.sample_A
return swapped_copy
def get_dm(self, is_splom = False):
if self._dm is None:
self._dm = self._compute_dm(is_splom)
return self._dm
def set_dm(self,matrix):
self._dm = matrix
def _compute_dm(self, splom_flag = False):
preds = self._raw
lenTest = len(self._ixs)
def rmse(curve1, curve2, do_you_splom = False):
if do_you_splom:
return ((curve1 - curve2) ** 2).sum()
return np.sqrt(((curve1 - curve2) ** 2).mean())
list_of_test_indexes = list(range(lenTest))
pairs_of_curves = []
for comb in combinations(list_of_test_indexes, 2):
pairs_of_curves.append(comb)
distance_matrix = np.zeros((lenTest, lenTest))
for pair in pairs_of_curves:
i = pair[0]
j = pair[1]
distance = rmse(preds[i].reshape((-1,)), preds[j].reshape((-1,)),splom_flag)
distance_matrix[i, j] = distance
distance_matrix[j, i] = distance
distance_matrix[i, i] = 0.0
return distance_matrix
def get_mean_distances(self, cluster_A, cluster_B):
dist_mtrx = self._dm
real_A = cluster_A[1]
real_B = cluster_B[1]
lab_A = cluster_A[0]
lab_B = cluster_B[0]
if lab_A == lab_B:
return 1.1
inst_A_list = real_A._index_ixs
inst_B_list = real_B._index_ixs
distance_list = []
for a in inst_A_list:
for b in inst_B_list:
distance_list.append(dist_mtrx[a,b])
return np.mean(distance_list)
def split(self,labels_cluster):
if labels_cluster is None:
return [ (None, self.copy()) ]
def get_slice(c, lbl):
c._raw = self._raw[labels_cluster == lbl, :]
if self._dm is not None:
c._dm = self._dm[labels_cluster == lbl, :][:, labels_cluster == lbl]
c._ixs = self._ixs[labels_cluster == lbl]
c._origs = self._origs[labels_cluster == lbl]
c._index_ixs = np.array(range(len(self._ixs)))[labels_cluster == lbl]
c.heat_map = c.compute_heatmap()
return c
def get_macro_dist(clusters_input):
pairs_of_clusters = []
for comb in combinations(list_of_clusters, 2):
pairs_of_clusters.append(comb)
num_cluster_here = len(list_of_clusters)
macro_dist_matrix = np.zeros((num_cluster_here,num_cluster_here))
for i in list_of_clusters:
for j in list_of_clusters:
macro_dist_matrix[i,j] = self.get_mean_distances(clusters_input[i],
clusters_input[j])
return macro_dist_matrix
list_of_clusters = np.unique(labels_cluster)
curves_list = []
for lbl in list_of_clusters:
the_slice = get_slice(self.copy(), lbl)
curves_list.append((lbl, the_slice))
return (curves_list,get_macro_dist(curves_list))
class PartialDependence(object):
'''
Initialization Parameters
-------------------------
df_test: pandas.DataFrame
(REQUIRED) dataframe containing only the features values for each instance in the test-set.
model: Python object
(REQUIRED) Trained classifier as an object with the following properties:
The object must have a method predict_proba(X)
which takes a numpy.array of shape (n, num_feat)
as input and returns a numpy.array of shape (n, len(class_array)).
class_array: list of strings
(REQUIRED) all the classes name in the same order as the predictions returned by predict_proba(X).
class_focus: string
(REQUIRED) class name of the desired partial dependence
num_samples: integer value
(OPTIONAL)[default = 100] number of desired samples. Sampling a feature is done with:
numpy.linspace(min_value,max_value,num_samples)
where the bounds are related to min and max value for that feature in the test-set.
scale: float value
(OPTIONAL)[default = None] scale parameter vector for normalization.
shift: float value
(OPTIONAL)[default = None] shift parameter vector for normalization.
If you need to provide your data to the model in normalized form,
you have to define scale and shift such that:
transformed_data = (original_data + shift)*scale
where shift and scale are both numpy.array of shape (1,num_feat).
If the model uses directly the raw data in df_test without any transformation,
do not insert any scale and shift parameters.
'''
def __init__(self,
df_test,
model,
class_array,
class_focus,
num_samples=100,
scale=None,
shift=None):
self.df = df_test
self.mdl = model
self.cls_arr = class_array
self.cls_fcs = class_focus
self.n_smpl = int(np.floor(num_samples/2)*2)
self.scl = scale
self.shft = shift
self._compute_sampling()
def _compute_sampling(self):
df_test = self.df
model = self.mdl
class_array = self.cls_arr
class_focus = self.cls_fcs
num_samples = self.n_smpl
scale = self.scl
shift = self.shft
def check_denormalization(scale_check, shift_check):
if scale_check is None or shift_check is None:
de_norm = False
else:
de_norm = True
return de_norm
de_norm_bool = check_denormalization(scale, shift)
data_set_pred_index = class_array.index(class_focus)
lenTest = len(df_test)
num_feat = len(df_test.columns)
#ylabel = [df_test.columns[-1]]
xlabel = list(df_test.columns)
x_array = df_test[xlabel].values
#y_array = df_test[ylabel].values
#labs = [True if l[0] in [class_array[0]] else False for l in y_array]
if de_norm_bool:
x_array = (x_array + shift) * scale
pred = model.predict_proba(x_array)
original_preds = np.array([ x[data_set_pred_index] for x in pred ])
#thresh = get_roc_curve(original_preds,labs)["score"]
dictLabtoIndex = {}
for (ix, laballa) in enumerate(xlabel):
dictLabtoIndex[laballa] = ix
df_features = pd.DataFrame(columns=[ "max","min","mean","sd" ], index=xlabel)
means = []
stds = []
mins = []
maxs = []
for laballa in xlabel:
THErightIndex = dictLabtoIndex[laballa]
if de_norm_bool:
vectzi = (list(df_test[laballa]) + shift[0][THErightIndex]) * scale[0][THErightIndex]
else:
vectzi = list(df_test[laballa])
mean = np.mean(vectzi)
maxim = max(vectzi)
minion = min(vectzi)
standin = np.std(vectzi)
means.append(mean)
stds.append(standin)
mins.append(minion)
maxs.append(maxim)
df_features["max"] = maxs
df_features["min"] = mins
df_features["mean"] = means
df_features["sd"] = stds
num_feat = len(xlabel)
df_sample = pd.DataFrame(columns=xlabel)
eps = 0
for laballa in xlabel:
lower_bound = df_features["min"][laballa] - eps
higher_bound = df_features["max"][laballa] + eps
#bound = df_features["mean"][laballa] + 2*df_features["sd"][laballa]
df_sample[laballa] = np.linspace(lower_bound, higher_bound, num_samples)
changing_rows = np.copy(x_array)
# local sampling
def local_sampling (fix, chosen_row):
base_value = chosen_row[dictLabtoIndex[fix]]
samplesLeft = list(np.linspace(base_value-1, base_value, int(num_samples / 2) + 1))
samplesRight = list(np.linspace(base_value, base_value + 1, int(num_samples / 2) + 1))
samples = samplesLeft + samplesRight
divisor = int(num_samples / 2 + 1)
final_samples = samples[:divisor - 1] + [ base_value ] + samples[divisor + 1:]
return final_samples
list_of_df_local_sampling = []
for i in range(lenTest):
r = changing_rows[i]
df = pd.DataFrame()
for lab in xlabel:
df[lab] = local_sampling (lab,r)
list_of_df_local_sampling.append(df)
self.changing_rows = changing_rows
self.dictLabtoIndex = dictLabtoIndex
self.original_preds = original_preds
self.num_feat = num_feat
self.lenTest = lenTest
self.data_set_pred_index = data_set_pred_index
self.df_sample = df_sample
self.df_features = df_features
self.de_norm_bool = de_norm_bool
self.list_local_sampling = list_of_df_local_sampling
def pdp(self, fix, chosen_row=None,batch_size=0):
"""
By choosing a feature and changing it in the sample range,
for each row in the test-set we can create num_samples different versions of the original instance.
Then we are able to compute prediction values for each of the different vectors.
pdp() initialize and returns a python object from the class PdpCurves containing such predictions values.
Parameters
----------
fix : string
(REQUIRED) The name of feature as reported in one of the df_test columns.
chosen_row : numpy.array of shape (1,num_feat)
(OPTIONAL) [default = None] A custom row, defined by the user, used to test or compare the results.
For example you could insert a row with mean values in each feature.
batch_size: integer value
(OPTIONAL) [default = 0] The batch size is required when the size ( num_rows X num_samples X num_feat ) becomes too large.
In this case you might want to compute the predictions in chunks of size batch_size, to not run out of memory.
If batch_size = 0, then predictions are computed with a single call of model.predict_proba().
Otherwise the number of calls is automatically computed and it will depend on the user-defined batch_size parameter.
In order to not split up predictions relative to a same instance in different chunks,
batch_size must be greater or equale to num_samples.
Returns
-------
curves_returned: python object
(ALWAYS) An itialized object from the class PdpCurves.
It contains all the predictions obtained from the different versions of the test instances, stored in matrix_changed_rows.
chosen_row_preds: numpy.array of shape (1, num_samples)
(IF REQUESTED) If chosen_row_alterations was supplied by the user, we also return this array, otherwise just pred_matrix is returned.
It contains all the different predictions obtained from the different versions of custom chosen_row, stored in chosen_row_alterations.
"""
rows = self.changing_rows
dictLabtoIndex = self.dictLabtoIndex
num_feat = self.num_feat
df_sample = self.df_sample
num_samples = self.n_smpl
self.the_feature = fix
def pred_comp_all(self, matrix_changed_rows, chosen_row_alterations_input=None, batch_size_input=0):
model = self.mdl
#num_samples = self.n_smpl
def compute_pred(self, matrix_changed_rows, chosen_row_alterations_sub_funct=None):
#t = time.time()
#num_feat = self.num_feat
data_set_pred_index = self.data_set_pred_index
num_rows= len(matrix_changed_rows)
pred_matrix = np.zeros((num_rows, num_samples))
matrix_changed_rows = matrix_changed_rows.reshape((num_rows * num_samples, num_feat))
ps = model.predict_proba(matrix_changed_rows)
ps = [ x[data_set_pred_index] for x in ps ]
k = 0
for i in range(0, num_rows * num_samples):
if i % num_samples == 0:
pred_matrix[k] = ps[i:i + num_samples]
k += 1
curves_returned = PdpCurves(pred_matrix)
if chosen_row_alterations_sub_funct is not None:
chosen_row_preds = model.predict_proba(chosen_row_alterations_sub_funct)
chosen_row_preds = np.array([ x[data_set_pred_index] for x in chosen_row_preds ])
return curves_returned, chosen_row_preds
return curves_returned
def compute_pred_in_chunks(self, matrix_changed_rows, number_all_preds_in_batch, chosen_row_alterations_sub_funct=None):
#t = time.time()
num_feat = self.num_feat
data_set_pred_index = self.data_set_pred_index
num_rows= len(matrix_changed_rows)
pred_matrix = np.zeros((num_rows, num_samples))
#number_all_preds_in_batch = 1000
if number_all_preds_in_batch < num_samples:
print ("Error: batch size cannot be less than sample size.")
return np.nan
if number_all_preds_in_batch > num_samples*num_rows:
print ("Error: batch size cannot be greater than total size (num. of instances X num. of samples).")
return np.nan
num_of_instances_in_batch = int( np.floor( number_all_preds_in_batch / num_samples ) )
how_many_calls = int( np.ceil( num_rows / num_of_instances_in_batch ) )
residual = num_of_instances_in_batch * how_many_calls - num_rows
num_of_instances_in_last_batch = num_of_instances_in_batch - residual
#print ("num_of_instances_in_batch" , num_of_instances_in_batch)
#print ( "how_many_calls" , how_many_calls, type(how_many_calls) )
#print ( "residual" , residual)
#print ( "num_of_instances_in_last_batch" , num_of_instances_in_last_batch)
for i in range(0, how_many_calls):
#if float(i+1)%1000==0:
#print ("---- loading preds: ", np.round(i/float(num_rows),decimals=4)*100,"%")
#print ("------ elapsed: ",int(int(time.time()-t)/60), "m")
low_bound_index = i*num_of_instances_in_batch
high_bound_index = low_bound_index + num_of_instances_in_batch
if i == how_many_calls -1 and residual != 0:
high_bound_index = low_bound_index + num_of_instances_in_last_batch
matrix_batch = matrix_changed_rows[low_bound_index:high_bound_index]
pred_matrix_batch = compute_pred(self,matrix_batch).get_preds()
pred_matrix[low_bound_index:high_bound_index] = np.copy(pred_matrix_batch)
curves_returned = PdpCurves(pred_matrix)
if chosen_row_alterations_sub_funct is not None:
chosen_row_preds = model.predict_proba(chosen_row_alterations_sub_funct)
chosen_row_preds = np.array([x[data_set_pred_index] for x in chosen_row_preds])
return curves_returned, chosen_row_preds
return curves_returned
if batch_size_input != 0:
return compute_pred_in_chunks(self, matrix_changed_rows,
number_all_preds_in_batch = batch_size_input,
chosen_row_alterations_sub_funct = chosen_row_alterations_input)
return compute_pred(self, matrix_changed_rows,
chosen_row_alterations_sub_funct = chosen_row_alterations_input)
num_rows = len(rows)
new_matrix_f = np.zeros((num_rows, num_samples, num_feat))
sample_vals = df_sample[fix]
depth_index = 0
for r in rows:
index_height = 0
for v in sample_vals:
new_r = np.copy(r)
new_r[dictLabtoIndex[fix]] = v
new_matrix_f[depth_index][index_height] = new_r
index_height += 1
depth_index += 1
if chosen_row is not None:
chosen_row_alterations = []
for v in sample_vals:
arow = np.copy(chosen_row)
arow[dictLabtoIndex[fix]] = v
chosen_row_alterations.append(arow)
chosen_row_alterations = np.array(chosen_row_alterations)
return pred_comp_all(
self,
new_matrix_f,
chosen_row_alterations_input=chosen_row_alterations,
batch_size_input=batch_size)
return pred_comp_all(
self,
new_matrix_f,
batch_size_input=batch_size)
def get_optimal_keogh_radius(self):
"""
computes the optimal value for the parameter needed to compute the LB Keogh distance.
It is computed given the sample values, the standard deviation, max and min.
"""
the_feature = self.the_feature
num_samples = self.n_smpl
df_sample = self.df_sample
df_features = self.df_features
distance_between_2_samples = \
(df_sample[the_feature][num_samples-1] - df_sample[the_feature][0]) / num_samples
sugg_r = int(np.ceil(df_features["sd"][the_feature] / 10.0 / distance_between_2_samples))
#print("Suggested r parameter:",sugg_r)
#rWarpedUsed = int(input("warp parameter window:"))
rWarpedUsed = sugg_r
if rWarpedUsed == 0:
rWarpedUsed = 1
return rWarpedUsed
def compute_clusters(self, curves, n_clusters=5):
"""
Produces a clustering on the instances of the test set based on the similrity of the predictions values from preds.
The clustering is done with the agglomerative technique using a distance matrix.
The distance is measured either with root mean square error (RMSE) or with dynamic time warping distance (DTW),
depending on the user choice.
Parameters
----------
curves : python object
(REQUIRED) Returned by previous function pdp() or pdp_2D() or get_data_splom().
n_clusters : integer value
(OPTIONAL) [default = 5] The number of desired clusters.
Returns
-------
the_list_sorted : list of size n_clusters with tuples: ( label cluster (float), python object OR dictionary of python objects (SPLOM data) )
(ALWAYS) Each element is an object from the class PdpCurves() or Pdp2DCurves() representing a different cluster.
This list is sorted using the clustering distance matrix taking the biggest cluster first,
then the closest cluster by average distance next and so on.
"""
num_feat = self.num_feat
num_samples = self.n_smpl
from_splom = False
if type(curves) is dict:
from_splom = True
if not from_splom:
distance_matrix = curves.get_dm(from_splom)
else:
size_matrix = len(curves[(0,1)].get_ixs())
distance_matrix = np.zeros((size_matrix,size_matrix))
for ij in curves:
curves_from_grid = curves[ij]
distance_matrix += curves_from_grid.get_dm(from_splom)
num_squares_summed = (num_samples+1)**2*(num_feat**2-num_feat)/2
distance_matrix = np.sqrt(distance_matrix/num_squares_summed)
clust = AgglomerativeClustering(affinity = 'precomputed', n_clusters = n_clusters, linkage = 'average')
clust.fit(distance_matrix)
labels_array = clust.labels_
def split_and_sort (curves_obj):
goal = curves_obj.split(labels_array)
the_list = goal[0]
the_matrix_for_sorting = goal[1]
size = 0
for cl in the_list:
size_new = len(cl[1].get_ixs())
if size_new > size:
size = size_new
label_biggest = cl[0]
cluster_labels_still = list(range(len(the_list)))
corder = [ label_biggest ]
cluster_labels_still.remove(label_biggest)
while len(corder)<len(the_list):
mins = {}
for c in corder:
full_distances = list(the_matrix_for_sorting[c,:])
distances = list(the_matrix_for_sorting[c,cluster_labels_still])
the_min = np.min(distances)
the_index = full_distances.index(min(distances))
mins[the_index] = the_min
new_cord = min(mins, key=mins.get)
corder.append(new_cord)
cluster_labels_still.remove(new_cord)
if len(np.unique(corder)) != len(the_list):
print("Fatal Error.")
the_list_sorted = []
for c in corder:
the_list_sorted.append(the_list[c])
return the_list_sorted
if not from_splom:
return split_and_sort (curves)
else:
heats_list = []
labels_list = []
for i in range(n_clusters):
heats_list.append({})
labels_list.append(None)
for ij in curves:
curves[ij].set_dm(distance_matrix)
list_heatmaps = split_and_sort(curves[ij])
for i in range(n_clusters):
label_cluster = list_heatmaps[i][0]
heat_obj = list_heatmaps[i][1]
if labels_list[i] is None:
labels_list[i] = label_cluster
else:
if labels_list[i] != label_cluster:
print ("mismatching clusters",labels_list[i],"vs",label_cluster)
return
heats_list[i][ij] = heat_obj
return [ (labels_list[i], heats_list[i]) for i in range(n_clusters) ]
def _back_to_the_original(self, data_this, fix):
# private function to be able to plot the data values not in normalized form
dictLabtoIndex = self.dictLabtoIndex
de_norm = self.de_norm_bool
scale = self.scl
shift = self.shft
if de_norm:
integ = dictLabtoIndex[fix]
data_that = data_this / scale[0][integ] - shift[0][integ]
else:
data_that = data_this
return data_that
def plot(self,
curves_input,
color_plot = None,
thresh = 0.5,
local_curves = True,
chosen_row_preds_to_plot = None,
plot_full_curves = False,
plot_object = None,
cell_view = False,
path = None):
"""
The visualization will display broad curves with color linked to different clusters.
The orginal instances are displayed with coordinates (orginal feature value, original prediction) either as
local curves or dots depending on the local_curves argument value.
Parameters
----------
curves : python object
(REQUIRED) A python object from the class PdpCurves(). ( Returned by previous function pdp() )
Otherwise a list of such python objects in tuples. ( Returned by previous function compute_clusters() )
color_plot : string or list of strings
(OPTIONAL) [default = None] The color for each cluster of instances.
If there is no clustering or just a single cluster provide just a string with the desire color.
thresh: float value
(OPTIONAL) [default = 0.5] The threshold is displayed as a red dashed line parallel to the x-axis.
local_curves: boolean value
(OPTIONAL) [default = True] If True the original instances are displayed as edges, otherwise if False they are displayed as dots.
chosen_row_preds_to_plot: numpy.array of shape (1, num_samples)
(OPTIONAL) [default = None] Returned by previous function pdp().
Such values will be displayed as red curve in the plot.
plot_full_curves: boolean value
(OPTIONAL) [default = False]