-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
_proximity_forest.py
1814 lines (1548 loc) · 57.3 KB
/
_proximity_forest.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
"""Proximity Forest time series classifier.
A decision tree forest which uses distance measures to partition data. B. Lucas and A.
Shifaz, C. Pelletier, L. O'Neill, N. Zaidi, B. Goethals, F. Petitjean and G. Webb
Proximity Forest: an effective and scalable distance-based classifier for time series,
Data Mining and Knowledge Discovery, 33(3): 607-635, 2019
"""
__author__ = ["goastler", "moradabaz"]
__all__ = ["ProximityForest", "ProximityStump", "ProximityTree"]
import math
import numpy as np
import pandas as pd
from joblib import Parallel, delayed
from scipy import stats
from sklearn.preprocessing import normalize
from sklearn.utils import check_random_state
from sktime.classification.base import BaseClassifier
from sktime.datatypes import convert
from sktime.distances import (
dtw_distance,
erp_distance,
lcss_distance,
msm_distance,
wdtw_distance,
)
from sktime.transformations.base import _PanelToPanelTransformer
from sktime.transformations.panel.summarize import DerivativeSlopeTransformer
# todo unit tests / sort out current unit tests
# todo logging package rather than print to screen
# todo get params avoid func pointer - use name
# todo set params use func name or func pointer
# todo constructor accept str name func / pointer
# todo duck-type functions
class _CachedTransformer(_PanelToPanelTransformer):
"""Transformer container.
Transforms data and adds the transformed version to a cache. If the
transformation is called again on already seen data the data is
fetched from the cache rather than performing the expensive transformation.
Parameters
----------
transformer: the transformer to transform uncached data
Attributes
----------
cache : location to store transforms seen before for fast look up
"""
def __init__(self, transformer):
self.cache = {}
self.transformer = transformer
super().__init__()
def clear(self):
"""Clear the cache."""
self.cache = {}
def transform(self, X, y=None):
"""Fit transformer, creating a cache for transformation.
Parameters
----------
X : pandas DataFrame of shape [n_instances, n_features]
Input data
y : pandas Series, shape (n_instances), optional
Targets for supervised learning.
Returns
-------
cached_instances.
"""
# for each instance, get transformed instance from cache or
# transform and add to cache
cached_instances = {}
uncached_indices = []
for index in X.index.values:
try:
cached_instances[index] = self.cache[index]
except Exception:
uncached_indices.append(index)
if len(uncached_indices) > 0:
uncached_instances = X.loc[uncached_indices, :]
transformed_uncached_instances = self.transformer.fit_transform(
uncached_instances
)
transformed_uncached_instances.index = uncached_instances.index
transformed_uncached_instances = transformed_uncached_instances.to_dict(
"index"
)
self.cache.update(transformed_uncached_instances)
cached_instances.update(transformed_uncached_instances)
cached_instances = pd.DataFrame.from_dict(cached_instances, orient="index")
return cached_instances
def __str__(self):
"""Return the transformer string."""
return self.transformer.__str__()
def _derivative_distance(distance_measure, transformer):
"""Take derivative before conducting distance measure.
Parameters
----------
distance_measure: the distance measure to use
transformer: the transformer to use
Return
------
a distance measure function with built in transformation
"""
def distance(instance_a, instance_b, **params):
df = pd.DataFrame([instance_a, instance_b])
df = transformer.transform(X=df)
instance_a = df.iloc[0, :]
instance_b = df.iloc[1, :]
return distance_measure(instance_a, instance_b, **params)
return distance
def distance_predefined_params(distance_measure, **params):
"""Conduct distance measurement with a predefined set of parameters.
Parameters
----------
distance_measure: callable
A callable distance measure function to use.
params: dict
The parameters to use in the distance measure
Returns
-------
ret: callable
A distance measure with no parameters
"""
def distance(instance_a, instance_b):
return distance_measure(instance_a, instance_b, **params)
return distance
def numba_wrapper(distance_measure):
"""Wrap a numba distance measure with numpy conversion.
Converts to 1 column per dimension format. Really would be better if the whole thing
worked directly with numpy arrays.
Parameters
----------
distance_measure: callable
A distance measure to wrap
Returns
-------
ret: callable
a distance measure which automatically formats data for numba distance
measures
"""
def distance(instance_a, instance_b, **params):
instance_a = convert(instance_a, "nested_univ", "numpyflat")
instance_b = convert(instance_b, "nested_univ", "numpyflat")
return distance_measure(instance_a, instance_b, **params)
return distance
def pure(y):
"""Test whether a set of class labels are pure (i.e. all the same).
Parameters
----------
y : 1d array like
array of class labels
Returns
-------
result : boolean
whether the set of class labels is pure
"""
# get unique class labels
unique_class_labels = np.unique(np.array(y))
# if more than 1 unique then not pure
return len(unique_class_labels) <= 1
def gini_gain(y, y_subs):
"""Get gini score of a split, i.e. the gain from parent to children.
Parameters
----------
y : 1d array like
array of class labels at parent
y_subs : list of 1d array like
list of array of class labels, one array per child
Returns
-------
score : float
gini score of the split from parent class labels to children. Note a
higher score means better gain,
i.e. a better split
"""
y = np.array(y)
# find number of instances overall
parent_n_instances = y.shape[0]
# if parent has no instances then is pure
if parent_n_instances == 0:
for child in y_subs:
if len(child) > 0:
raise ValueError("children populated but parent empty")
return 0.5
# find gini for parent node
score = gini(y)
# sum the children's gini scores
for index in range(len(y_subs)):
child_class_labels = y_subs[index]
# ignore empty children
if len(child_class_labels) > 0:
# find gini score for this child
child_score = gini(child_class_labels)
# weight score by proportion of instances at child compared to
# parent
child_size = len(child_class_labels)
child_score *= child_size / parent_n_instances
# add to cumulative sum
score -= child_score
return score
def gini(y):
"""Get gini score at a specific node.
Parameters
----------
y : 1d numpy array
array of class labels
Returns
-------
score : float
gini score for the set of class labels (i.e. how pure they are). A
larger score means more impurity. Zero means
pure.
"""
y = np.array(y)
# get number instances at node
n_instances = y.shape[0]
if n_instances > 0:
# count each class
_, class_counts = np.unique(y, return_counts=True)
# subtract class entropy from current score for each class
class_counts = np.divide(class_counts, n_instances)
class_counts = np.power(class_counts, 2)
sum = np.sum(class_counts)
return 1 - sum
else:
# y is empty, therefore considered pure
raise ValueError(" y empty")
def dtw_distance_measure_getter(X):
"""Generate the dtw distance measure.
Parameters
----------
X: dataset to derive parameter ranges from
Returns
-------
ret: distance measure and parameter range dictionary
"""
return {
"distance_measure": [numba_wrapper(dtw_distance)],
"window": stats.uniform(0, 0.25),
}
def msm_distance_measure_getter(X):
"""Generate the msm distance measure.
Parameters
----------
X: dataset to derive parameter ranges from
Returns
-------
ret: distance measure and parameter range dictionary
"""
n_dimensions = 1 # todo use other dimensions
return {
"distance_measure": [numba_wrapper(msm_distance)],
"dim_to_use": stats.randint(low=0, high=n_dimensions),
"c": [
0.01,
0.01375,
0.0175,
0.02125,
0.025,
0.02875,
0.0325,
0.03625,
0.04,
0.04375,
0.0475,
0.05125,
0.055,
0.05875,
0.0625,
0.06625,
0.07,
0.07375,
0.0775,
0.08125,
0.085,
0.08875,
0.0925,
0.09625,
0.1,
0.136,
0.172,
0.208,
0.244,
0.28,
0.316,
0.352,
0.388,
0.424,
0.46,
0.496,
0.532,
0.568,
0.604,
0.64,
0.676,
0.712,
0.748,
0.784,
0.82,
0.856,
0.892,
0.928,
0.964,
1,
1.36,
1.72,
2.08,
2.44,
2.8,
3.16,
3.52,
3.88,
4.24,
4.6,
4.96,
5.32,
5.68,
6.04,
6.4,
6.76,
7.12,
7.48,
7.84,
8.2,
8.56,
8.92,
9.28,
9.64,
10,
13.6,
17.2,
20.8,
24.4,
28,
31.6,
35.2,
38.8,
42.4,
46,
49.6,
53.2,
56.8,
60.4,
64,
67.6,
71.2,
74.8,
78.4,
82,
85.6,
89.2,
92.8,
96.4,
100,
],
}
def erp_distance_measure_getter(X):
"""Generate the erp distance measure.
Parameters
----------
X: dataset to derive parameter ranges from
ret: distance measure and parameter range dictionary
"""
stdp = _stdp(X)
instance_length = _max_instance_length(X) # todo should this use the max instance
# length for unequal length dataset instances?
max_raw_warping_window = np.floor((instance_length + 1) / 4)
n_dimensions = 1 # todo use other dimensions
return {
"distance_measure": [numba_wrapper(erp_distance)],
"dim_to_use": stats.randint(low=0, high=n_dimensions),
"g": stats.uniform(0.2 * stdp, 0.8 * stdp - 0.2 * stdp),
"band_size": stats.randint(low=0, high=max_raw_warping_window + 1)
# scipy stats randint is exclusive on the max value, hence + 1
}
def lcss_distance_measure_getter(X):
"""Generate the lcss distance measure.
Parameters
----------
X: dataset to derive parameter ranges from
Returns
-------
ret: distance measure and parameter range dictionary
"""
stdp = _stdp(X)
instance_length = _max_instance_length(X) # todo should this use the max instance
# length for unequal length dataset instances?
max_raw_warping_window = np.floor((instance_length + 1) / 4)
n_dimensions = 1 # todo use other dimensions
return {
"distance_measure": [numba_wrapper(lcss_distance)],
"dim_to_use": stats.randint(low=0, high=n_dimensions),
"epsilon": stats.uniform(0.2 * stdp, stdp - 0.2 * stdp),
# scipy stats randint is exclusive on the max value, hence + 1
"delta": stats.randint(low=0, high=max_raw_warping_window + 1),
}
# def twe_distance_measure_getter(X):
# """Generate the twe distance measure.
#
# :param X: dataset to derive parameter ranges from
# :returns: distance measure and parameter range dictionary
# """
# return {
# "distance_measure": [cython_wrapper(twe_distance)],
# "penalty": [
# 0,
# 0.011111111,
# 0.022222222,
# 0.033333333,
# 0.044444444,
# 0.055555556,
# 0.066666667,
# 0.077777778,
# 0.088888889,
# 0.1,
# ],
# "stiffness": [0.00001, 0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1],
# }
def wdtw_distance_measure_getter(X):
"""Generate the wdtw distance measure.
Parameters
----------
X: dataset to derive parameter ranges from
Returns
-------
ret: distance measure and parameter range dictionary
"""
return {
"distance_measure": [numba_wrapper(wdtw_distance)],
"g": stats.uniform(0, 1),
}
def euclidean_distance_measure_getter(X):
"""Generate the ed distance measure.
Parameters
----------
X: dataset to derive parameter ranges from
Returns
-------
ret: distance measure and parameter range dictionary
"""
return {"distance_measure": [numba_wrapper(dtw_distance)], "w": [0]}
def setup_wddtw_distance_measure_getter(transformer):
"""Generate the wddtw distance measure.
Bakes the derivative transformer into the dtw distance measure
Parameters
----------
transformer: the transformer to use
Returns
-------
ret: a getter to produce the distance measure
"""
def getter(X):
return {
"distance_measure": [
_derivative_distance(numba_wrapper(wdtw_distance), transformer)
],
"g": stats.uniform(0, 1),
}
return getter
def setup_ddtw_distance_measure_getter(transformer):
"""Generate the ddtw distance measure.
Bakes the derivative transformer into the dtw distance measure
Parameters
----------
transformer: the transformer to use
Returns
-------
ret: a getter to produce the distance measure
"""
def getter(X):
return {
"distance_measure": [
_derivative_distance(numba_wrapper(dtw_distance), transformer)
],
"w": stats.uniform(0, 0.25),
}
return getter
def pick_rand_param_perm_from_dict(param_pool, random_state):
"""Pick a parameter permutation.
Given a list of dictionaries contain potential values OR a list of values OR a
distribution of values (a distribution must have the .rvs() function to sample
values)
Parameters
----------
param_pool : list of dicts OR list OR distribution
parameters in the same format as GridSearchCV from scikit-learn.
example:
param_grid = [
{'C': [1, 10, 100, 1000], 'kernel': ['linear']},
{'C': [1, 10, 100, 1000], 'gamma': [{'C': [1, 10, 100, 1000],
'kernel': ['linear']}],
'kernel': ['rbf']},
]
Returns
-------
param_perm : dict
distance measure and corresponding parameters in dictionary format
"""
# construct empty permutation
param_perm = {}
# for each parameter
for param_name, param_values in param_pool.items():
# if it is a list
if isinstance(param_values, list):
# randomly pick a value
param_value = param_values[random_state.randint(len(param_values))]
# if the value is another dict then get a random parameter
# permutation from that dict (recursive over
# 2 funcs)
# if isinstance(param_value, dict): # no longer require
# recursive param perms
# param_value = _pick_param_permutation(param_value,
# random_state)
# else if parameter is a distribution
elif hasattr(param_values, "rvs"):
# sample from the distribution
param_value = param_values.rvs(random_state=random_state)
else:
# otherwise we don't know how to obtain a value from the parameter
raise Exception("unknown type of parameter pool")
# add parameter name and value to permutation
param_perm[param_name] = param_value
return param_perm
def pick_rand_param_perm_from_list(params, random_state):
"""Get a random parameter permutation.
Permutation providing a distance measure and corresponding parameters.
Parameters
----------
params : list of dicts
parameters in the same format as GridSearchCV from scikit-learn.
example:
param_grid = [
{'C': [1, 10, 100, 1000], 'kernel': ['linear']},
{'C': [1, 10, 100, 1000], 'gamma': [{'C': [1, 10, 100, 1000],
'kernel': ['linear']}], 'kernel': ['rbf']},
]
Returns
-------
permutation : dict
distance measure and corresponding parameters in dictionary format
"""
#
param_pool = random_state.choice(params)
permutation = pick_rand_param_perm_from_dict(param_pool, random_state)
return permutation
# for distance measure getters
TRANSFORMER = _CachedTransformer(DerivativeSlopeTransformer())
DISTANCE_MEASURE_GETTERS = {
"euclidean": euclidean_distance_measure_getter,
"dtw": dtw_distance_measure_getter,
"ddtw": setup_ddtw_distance_measure_getter(TRANSFORMER),
"wdtw": wdtw_distance_measure_getter,
"wddtw": setup_wddtw_distance_measure_getter(TRANSFORMER),
"msm": msm_distance_measure_getter,
"lcss": lcss_distance_measure_getter,
"erp": erp_distance_measure_getter,
}
class ProximityStump(BaseClassifier):
"""Proximity Stump class.
Model a decision stump which uses a distance measure to partition data.
Parameters
----------
random_state: integer, the random state
distance_measure: ``None`` (default) or str; if str, one of
"euclidean", "dtw", "ddtw", "wdtw", "wddtw", "msm", "lcss", "erp"
distance measure to use
if ``None``, selects distances randomly from the list of available distances
verbosity: logging verbosity
n_jobs: number of jobs to run in parallel *across threads"
Examples
--------
>>> from sktime.classification.distance_based import ProximityStump
>>> from sktime.datasets import load_unit_test
>>> X_train, y_train = load_unit_test(split="train")
>>> X_test, y_test = load_unit_test(split="test")
>>> clf = ProximityStump()
>>> clf.fit(X_train, y_train)
ProximityStump(...)
>>> y_pred = clf.predict(X_test)
"""
_tags = {
# packaging info
# --------------
"authors": ["goastler", "moradabaz"],
"maintainers": ["goastler", "moradabaz"],
# estimator type
# --------------
"capability:multithreading": True,
"X_inner_mtype": "nested_univ", # input in nested dataframe
}
def __init__(
self,
random_state=None,
distance_measure=None,
verbosity=0,
n_jobs=1,
):
self.random_state = random_state
self.distance_measure = distance_measure
self.verbosity = verbosity
self.n_jobs = n_jobs
# set in fit
self.label_encoder = None
self.y_exemplar = None
self.X_exemplar = None
self.X_branches = None
self.y_branches = None
self.X = None
self.y = None
self.entropy = None
self._random_object = None
super().__init__()
def pick_distance_measure(self):
"""Pick a distance measure.
Parameters
----------
self : ProximityStump object.
Returns
-------
ret: distance measure
"""
random_state = check_random_state(self.random_state)
if self.distance_measure is None:
distance_measure_getter = random_state.choice(
list(DISTANCE_MEASURE_GETTERS.values())
)
else:
distance_measure_getter = DISTANCE_MEASURE_GETTERS[self.distance_measure]
distance_measure_perm = distance_measure_getter(self.X)
param_perm = pick_rand_param_perm_from_dict(distance_measure_perm, random_state)
distance_measure = param_perm.pop("distance_measure")
return distance_predefined_params(distance_measure, **param_perm)
@staticmethod
def _distance_to_exemplars_inst(exemplars, instance, distance_measure):
"""Find distance between a given instance and the exemplar instances.
Parameters
----------
exemplars: the exemplars to use
instance: the instance to compare to each exemplar
distance_measure: the distance measure to provide similarity values
Returns
-------
list of distances to each exemplar
"""
n_exemplars = len(exemplars)
distances = np.empty(n_exemplars)
min_distance = math.inf
for exemplar_index in range(n_exemplars):
exemplar = exemplars[exemplar_index]
if exemplar.name == instance.name:
distance = 0
else:
distance = distance_measure(instance, exemplar) # , min_distance)
if distance < min_distance:
min_distance = distance
distances[exemplar_index] = distance
return distances
def get_exemplars(self):
"""Extract exemplars from a dataframe and class value list.
Parameters
----------
self : ProximityStump, the proximity stump object.
Returns
-------
ret: One exemplar per class
"""
# find unique class labels
unique_class_labels = np.unique(self.y)
n_unique_class_labels = len(unique_class_labels)
chosen_instances = [None] * n_unique_class_labels
# for each class randomly choose and instance
for class_label_index in range(n_unique_class_labels):
class_label = unique_class_labels[class_label_index]
# filter class labels for desired class and get indices
indices = np.argwhere(self.y == class_label)
# flatten numpy output
indices = np.ravel(indices)
# random choice
index = self._random_object.choice(indices)
# record exemplar instance and class label
instance = self.X.iloc[index, :]
chosen_instances[class_label_index] = instance
# convert lists to numpy arrays
return chosen_instances, unique_class_labels
def _distance_measure(self):
"""Get the distance measure.
Parameters
----------
self : ProximityStump
the proximity stump object.
Returns
-------
ret: distance measure
"""
return self.pick_distance_measure()
def distance_to_exemplars(self, X):
"""Find distance to exemplars.
Parameters
----------
X: the dataset containing a list of instances
Returns
-------
ret: 2d numpy array of distances from each instance to each
exemplar (instance by exemplar)
"""
if self._threads_to_use > 1:
parallel = Parallel(self._threads_to_use)
distances = parallel(
delayed(self._distance_to_exemplars_inst)(
self.X_exemplar, X.iloc[index, :], self._distance_measure()
)
for index in range(X.shape[0])
)
else:
distances = [
self._distance_to_exemplars_inst(
self.X_exemplar, X.iloc[index, :], self._distance_measure()
)
for index in range(X.shape[0])
]
distances = np.nan_to_num(np.vstack(np.array(distances)))
return distances
def _fit(self, X, y):
"""Build the classifier on the training set (X, y).
Parameters
----------
X : array-like or sparse matrix of shape = [n_instances, n_columns]
The training input samples. If a Pandas data frame is passed,
column 0 is extracted.
y : array-like, shape = [n_instances]
The class labels.
Returns
-------
self : object
"""
self.X = _positive_dataframe_indices(X)
self._random_object = check_random_state(self.random_state)
self.y = y
self.X_exemplar, self.y_exemplar = self.get_exemplars()
return self
def find_closest_exemplar_indices(self, X):
"""Find the closest exemplar index for each instance in a dataframe.
Parameters
----------
X: the dataframe containing instances
Returns
-------
ret: 1d numpy array of indices, one for each instance,
reflecting the index of the closest exemplar
"""
n_instances = X.shape[0]
distances = self.distance_to_exemplars(X)
indices = np.empty(X.shape[0], dtype=int)
for index in range(n_instances):
exemplar_distances = distances[index]
closest_exemplar_index = _arg_min(exemplar_distances, self._random_object)
indices[index] = closest_exemplar_index
return indices
def grow(self):
"""Grow the stump, creating branches for each exemplar."""
n_exemplars = len(self.y_exemplar)
indices = self.find_closest_exemplar_indices(self.X)
self.X_branches = [None] * n_exemplars
self.y_branches = [None] * n_exemplars
for index in range(n_exemplars):
instance_indices = np.argwhere(indices == index)
instance_indices = np.ravel(instance_indices)
self.X_branches[index] = self.X.iloc[instance_indices, :]
y = np.take(self.y, instance_indices)
self.y_branches[index] = y
# if you have custom gain function implemented in the future, you can
# change the line below
self.entropy = gini_gain(self.y, self.y_branches)
return self
def _predict(self, X) -> np.ndarray:
"""Predicts labels for sequences in X.
Parameters
----------
X : array-like or sparse matrix of shape = [n_instances, n_columns]
The training input samples.
If a Pandas data frame is passed (sktime format)
If a Pandas data frame is passed, a check is performed that it
only has one column.
If not, an exception is thrown, since this classifier does not
yet have
multivariate capability.
Returns
-------
y : array-like, shape = [n_instances] - predicted class labels
"""
distributions = self._predict_proba(X)
predictions = []
for instance_index in range(0, X.shape[0]):
distribution = distributions[instance_index]
prediction = np.argmax(distribution)
predictions.append(prediction)
return np.array(predictions)
def _predict_proba(self, X) -> np.ndarray:
"""Find probability estimates for each class for all cases in X.
Parameters
----------
X : array-like or sparse matrix of shape = [n_instances, n_columns]
The training input samples.
If a Pandas data frame is passed (sktime format)
If a Pandas data frame is passed, a check is performed that it
only has one column.
If not, an exception is thrown, since this classifier does not
yet have
multivariate capability.
Returns
-------
output : array of shape = [n_instances, n_classes] of probabilities
"""
X = _negative_dataframe_indices(X)
distances = self.distance_to_exemplars(X)
ones = np.ones(distances.shape)
distances = np.add(distances, ones)
distributions = np.reciprocal(distances)
normalize(distributions, copy=False, norm="l1")
return distributions
@classmethod
def get_test_params(cls, parameter_set="default"):
"""Return testing parameter settings for the estimator.
Returns
-------
params : dict or list of dict, default = {}
Parameters to create testing instances of the class
Each dict are parameters to construct an "interesting" test instance, i.e.,
``MyClass(**params)`` or ``MyClass(**params[i])`` creates a valid test
instance.
``create_test_instance`` uses the first (or only) dictionary in ``params``
"""
params1 = {
"random_state": 0,
}
params2 = {"random_state": 42, "distance_measure": "dtw"}
return [params1, params2]
class ProximityTree(BaseClassifier):
"""Proximity Tree class.
A decision tree which uses distance measures to partition data.
Parameters
----------
random_state: int or np.RandomState, default=0
random seed for the random number generator
distance_measure: ``None`` (default) or str; if str, one of
``euclidean``, ``dtw``, ``ddtw``, ``wdtw``, ``wddtw``, ``msm``,
``lcss``, ``erp`` distance measure to use
if ``None``, selects distances randomly from the list of available distances
max_depth: int or math.inf, default=math.inf
maximum depth of the tree
is_leaf : function, default=pure
decide when to mark a node as a leaf node
verbosity: 0 or 1
number reflecting the verbosity of logging
0 = no logging, 1 = verbose logging
n_jobs: int or None, default=1
number of parallel threads to use while building
n_stump_evaluations: number of stump evaluations to do if find_stump method is None
Examples