/
_distance.py
2420 lines (2136 loc) · 90.7 KB
/
_distance.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
__author__ = ["chrisholder", "TonyBagnall"]
from typing import Any, Callable, Union
import numpy as np
from sktime.distances._ddtw import _DdtwDistance
from sktime.distances._dtw import _DtwDistance
from sktime.distances._edr import _EdrDistance
from sktime.distances._erp import _ErpDistance
from sktime.distances._euclidean import _EuclideanDistance
from sktime.distances._lcss import _LcssDistance
from sktime.distances._msm import _MsmDistance
from sktime.distances._resolve_metric import (
_resolve_dist_instance,
_resolve_metric_to_factory,
)
from sktime.distances._squared import _SquaredDistance
from sktime.distances._twe import _TweDistance
from sktime.distances._wddtw import _WddtwDistance
from sktime.distances._wdtw import _WdtwDistance
from sktime.distances.base import (
AlignmentPathReturn,
DistanceAlignmentPathCallable,
DistanceCallable,
MetricInfo,
NumbaDistance,
)
def erp_distance(
x: np.ndarray,
y: np.ndarray,
window: Union[float, None] = None,
itakura_max_slope: Union[float, None] = None,
bounding_matrix: Union[np.ndarray, None] = None,
g: float = 0.0,
**kwargs: Any,
) -> float:
"""Compute the Edit distance for real penalty (ERP) distance between two series.
ERP, first proposed in [1]_, attempts align time series
by better considering how indexes are carried forward through the cost matrix.
Usually in the dtw cost matrix, if an alignment can't be found the previous value
is carried forward. Erp instead proposes the idea of gaps or sequences of points
that have no matches. These gaps are then punished based on their distance from 'g'.
Parameters
----------
x: np.ndarray (1d or 2d array)
First time series.
y: np.ndarray (1d or 2d array)
Second time series.
window: float, defaults = None
Float that is the radius of the sakoe chiba window (if using Sakoe-Chiba
lower bounding). Value must be between 0. and 1.
itakura_max_slope: float, defaults = None
Gradient of the slope for itakura parallelogram (if using Itakura
Parallelogram lower bounding). Value must be between 0. and 1.
bounding_matrix: np.ndarray (2d of size mxn where m is len(x) and n is len(y)),
defaults = None
Custom bounding matrix to use. If defined then other lower_bounding params
are ignored. The matrix should be structure so that indexes considered in
bound should be the value 0. and indexes outside the bounding matrix should be
infinity.
g: float, defaults = 0.
The reference value to penalise gaps.
kwargs: Any
Extra kwargs.
Returns
-------
float
ERP distance between x and y.
Raises
------
ValueError
If the sakoe_chiba_window_radius is not a float.
If the itakura_max_slope is not a float.
If the value of x or y provided is not a numpy array.
If the value of x or y has more than 3 dimensions.
If a metric string provided, and is not a defined valid string.
If a metric object (instance of class) is provided and doesn't inherit from
NumbaDistance.
If the metric type cannot be determined
If g is not a float.
If both window and itakura_max_slope are set
Examples
--------
>>> import numpy as np
>>> from sktime.distances import erp_distance
>>> x_1d = np.array([1, 2, 3, 4]) # 1d array
>>> y_1d = np.array([5, 6, 7, 8]) # 1d array
>>> erp_distance(x_1d, y_1d)
16.0
>>> x_2d = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) # 2d array
>>> y_2d = np.array([[9, 10, 11, 12], [13, 14, 15, 16]]) # 2d array
>>> erp_distance(x_2d, y_2d)
45.254833995939045
References
----------
.. [1] Lei Chen and Raymond Ng. 2004. On the marriage of Lp-norms and edit distance.
In Proceedings of the Thirtieth international conference on Very large data bases
- Volume 30 (VLDB '04). VLDB Endowment, 792–803.
"""
format_kwargs = {
"window": window,
"itakura_max_slope": itakura_max_slope,
"bounding_matrix": bounding_matrix,
"g": g,
}
format_kwargs = {**format_kwargs, **kwargs}
return distance(x, y, metric="erp", **format_kwargs)
def edr_distance(
x: np.ndarray,
y: np.ndarray,
window: Union[float, None] = None,
itakura_max_slope: Union[float, None] = None,
bounding_matrix: Union[np.ndarray, None] = None,
epsilon: float = None,
**kwargs: Any,
) -> float:
"""Compute the Edit distance for real sequences (EDR) between two series.
EDR computes the minimum number of elements (as a percentage) that must be removed
from x and y so that the sum of the distance between the remaining signal elements
lies within the tolerance (epsilon). EDR was originally proposed in [1]_.
The value returned will be between 0 and 1 per time series. The value will
represent as a percentage of elements that must be removed for the time series to
be an exact match.
Parameters
----------
x: np.ndarray (1d or 2d array)
First time series.
y: np.ndarray (1d or 2d array)
Second time series.
window: float, defaults = None
Float that is the radius of the sakoe chiba window (if using Sakoe-Chiba
lower bounding). Value must be between 0. and 1.
itakura_max_slope: float, defaults = None
Gradient of the slope for itakura parallelogram (if using Itakura
Parallelogram lower bounding). Value must be between 0. and 1.
bounding_matrix: np.ndarray (2d array), defaults = None
Custom bounding matrix to use. If defined then other lower_bounding params
are ignored. The matrix should be structure so that indexes considered in
bound should be the value 0. and indexes outside the bounding matrix should be
infinity.
epsilon : float, defaults = None
Matching threshold to determine if two subsequences are considered close
enough to be considered 'common'. If not specified as per the original paper
epsilon is set to a quarter of the maximum standard deviation.
kwargs: Any
Extra kwargs.
Returns
-------
float
Edr distance between the x and y. The value will be between 0.0 and 1.0
where 0.0 is an exact match between time series (i.e. they are the same) and
1.0 where there are no matching subsequences.
Raises
------
ValueError
If the sakoe_chiba_window_radius is not a float.
If the itakura_max_slope is not a float.
If the value of x or y provided is not a numpy array.
If the value of x or y has more than 3 dimensions.
If a metric string provided, and is not a defined valid string.
If a metric object (instance of class) is provided and doesn't inherit from
NumbaDistance.
If the metric type cannot be determined
If both window and itakura_max_slope are set
Examples
--------
>>> import numpy as np
>>> from sktime.distances import edr_distance
>>> x_1d = np.array([1, 2, 3, 4]) # 1d array
>>> y_1d = np.array([5, 6, 7, 8]) # 1d array
>>> edr_distance(x_1d, y_1d)
1.0
>>> x_2d = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) # 2d array
>>> y_2d = np.array([[9, 10, 11, 12], [13, 14, 15, 16]]) # 2d array
>>> edr_distance(x_2d, y_2d)
1.0
References
----------
.. [1] Lei Chen, M. Tamer Özsu, and Vincent Oria. 2005. Robust and fast similarity
search for moving object trajectories. In Proceedings of the 2005 ACM SIGMOD
international conference on Management of data (SIGMOD '05). Association for
Computing Machinery, New York, NY, USA, 491–502.
DOI:https://doi.org/10.1145/1066157.1066213
"""
format_kwargs = {
"window": window,
"itakura_max_slope": itakura_max_slope,
"bounding_matrix": bounding_matrix,
"epsilon": epsilon,
}
format_kwargs = {**format_kwargs, **kwargs}
return distance(x, y, metric="edr", **format_kwargs)
def lcss_distance(
x: np.ndarray,
y: np.ndarray,
window: Union[float, None] = None,
itakura_max_slope: Union[float, None] = None,
bounding_matrix: Union[np.ndarray, None] = None,
epsilon: float = 1.0,
**kwargs: Any,
) -> float:
"""Compute the longest common subsequence (LCSS) score between two time series.
LCSS attempts to find the longest common sequence between two time series and
returns a value that is the percentage that longest common sequence assumes.
Originally present in [1]_, LCSS is computed by matching indexes that are
similar up until a defined threshold (epsilon).
The value returned will be between 0.0 and 1.0, where 0.0 means the two time series
are exactly the same and 1.0 means they are complete opposites.
Parameters
----------
x: np.ndarray (1d or 2d array)
First time series.
y: np.ndarray (1d or 2d array)
Second time series.
window: float, defaults = None
Float that is the radius of the sakoe chiba window (if using Sakoe-Chiba
lower bounding). Value must be between 0. and 1.
itakura_max_slope: float, defaults = None
Gradient of the slope for itakura parallelogram (if using Itakura
Parallelogram lower bounding). Value must be between 0. and 1.
bounding_matrix: np.ndarray (2d of size mxn where m is len(x) and n is len(y)),
defaults = None
Custom bounding matrix to use. If defined then other lower_bounding params
are ignored. The matrix should be structure so that indexes considered in
bound should be the value 0. and indexes outside the bounding matrix should be
infinity.
epsilon : float, defaults = 1.
Matching threshold to determine if two subsequences are considered close
enough to be considered 'common'.
kwargs: Any
Extra kwargs.
Returns
-------
float
Lcss distance between x and y. The value returned will be between 0.0 and 1.0,
where 0.0 means the two time series are exactly the same and 1.0 means they
are complete opposites.
Raises
------
ValueError
If the sakoe_chiba_window_radius is not a float.
If the itakura_max_slope is not a float.
If the value of x or y provided is not a numpy array.
If the value of x or y has more than 2 dimensions.
If a metric string provided, and is not a defined valid string.
If a metric object (instance of class) is provided and doesn't inherit from
NumbaDistance.
If the metric type cannot be determined
If both window and itakura_max_slope are set
References
----------
.. [1] M. Vlachos, D. Gunopoulos, and G. Kollios. 2002. "Discovering
Similar Multidimensional Trajectories", In Proceedings of the
18th International Conference on Data Engineering (ICDE '02).
IEEE Computer Society, USA, 673.
"""
format_kwargs = {
"window": window,
"itakura_max_slope": itakura_max_slope,
"bounding_matrix": bounding_matrix,
"epsilon": epsilon,
}
format_kwargs = {**format_kwargs, **kwargs}
return distance(x, y, metric="lcss", **format_kwargs)
def wddtw_distance(
x: np.ndarray,
y: np.ndarray,
window: Union[float, None] = None,
itakura_max_slope: Union[float, None] = None,
bounding_matrix: Union[np.ndarray, None] = None,
compute_derivative=None,
g: float = 0.0,
**kwargs: Any,
) -> float:
r"""Compute the weighted derivative dynamic time warping (WDDTW) distance.
WDDTW was first proposed in [1]_ as an extension of DDTW. By adding a weight
to the derivative it means the alignment isn't only considering the shape of the
time series, but also the phase.
Formally the derivative is calculated as:
.. math::
D_{x}[q] = \frac{{}(q_{i} - q_{i-1} + ((q_{i+1} - q_{i-1}/2)}{2}
Therefore a weighted derivative can be calculated using D (the derivative) as:
.. math::
d_{w}(x_{i}, y_{j}) = ||w_{|i-j|}(D_{x_{i}} - D_{y_{j}})||
Parameters
----------
x: np.ndarray (1d or 2d array)
First time series.
y: np.ndarray (1d or 2d array)
Second time series.
window: float, defaults = None
Float that is the radius of the sakoe chiba window (if using Sakoe-Chiba
lower bounding). Value must be between 0. and 1.
itakura_max_slope: float, defaults = None
Gradient of the slope for itakura parallelogram (if using Itakura
Parallelogram lower bounding). Value must be between 0. and 1.
bounding_matrix: np.ndarray (2d of size mxn where m is len(x) and n is len(y)),
defaults = None
Custom bounding matrix to use. If defined then other lower_bounding params
are ignored. The matrix should be structure so that indexes considered in
bound should be the value 0. and indexes outside the bounding matrix should be
infinity.
compute_derivative: Callable[[np.ndarray], np.ndarray],
defaults = average slope difference
Callable that computes the derivative. If none is provided the average of the
slope between two points used.
g: float, defaults = 0.
Constant that controls the curvature (slope) of the function; that is, g
controls the level of penalisation for the points with larger phase
difference.
kwargs: Any
Extra kwargs.
Returns
-------
float
Wddtw distance between x and y.
Raises
------
ValueError
If the sakoe_chiba_window_radius is not float.
If the itakura_max_slope is not a float.
If the value of x or y provided is not a numpy array.
If the value of x or y has more than 2 dimensions.
If a metric string provided, and is not a defined valid string.
If a metric object (instance of class) is provided and doesn't inherit from
NumbaDistance.
If the metric type cannot be determined
If the compute derivative callable is not no_python compiled.
If the value of g is not a float
If both window and itakura_max_slope are set
Examples
--------
>>> import numpy as np
>>> from sktime.distances import wddtw_distance
>>> x_1d = np.array([1, 2, 3, 4]) # 1d array
>>> y_1d = np.array([5, 6, 7, 8]) # 1d array
>>> wddtw_distance(x_1d, y_1d) # doctest: +SKIP
0.0
>>> x_2d = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) # 2d array
>>> y_2d = np.array([[9, 10, 11, 12], [13, 14, 15, 16]]) # 2d array
>>> wddtw_distance(x_2d, y_2d) # doctest: +SKIP
0.0
References
----------
.. [1] Young-Seon Jeong, Myong K. Jeong, Olufemi A. Omitaomu, Weighted dynamic time
warping for time series classification, Pattern Recognition, Volume 44, Issue 9,
2011, Pages 2231-2240, ISSN 0031-3203, https://doi.org/10.1016/j.patcog.2010.09.022.
"""
if compute_derivative is None:
from sktime.distances._ddtw_numba import average_of_slope
compute_derivative = average_of_slope
format_kwargs = {
"window": window,
"itakura_max_slope": itakura_max_slope,
"bounding_matrix": bounding_matrix,
"compute_derivative": compute_derivative,
"g": g,
}
format_kwargs = {**format_kwargs, **kwargs}
return distance(x, y, metric="wddtw", **format_kwargs)
def wdtw_distance(
x: np.ndarray,
y: np.ndarray,
window: Union[float, None] = None,
itakura_max_slope: Union[float, None] = None,
bounding_matrix: np.ndarray = None,
g: float = 0.05,
**kwargs: Any,
) -> float:
"""Compute the weighted dynamic time warping (WDTW) distance between time series.
First proposed in [1]_, WDTW adds a adds a multiplicative weight penalty based on
the warping distance. This means that time series with lower phase difference have
a smaller weight imposed (i.e less penalty imposed) and time series with larger
phase difference have a larger weight imposed (i.e. larger penalty imposed).
Formally this can be described as:
.. math::
d_{w}(x_{i}, y_{j}) = ||w_{|i-j|}(x_{i} - y_{j})||
Where d_w is the distance with a the weight applied to it for points i, j, where
w(|i-j|) is a positive weight between the two points x_i and y_j.
Parameters
----------
x: np.ndarray (1d or 2d array)
First time series.
y: np.ndarray (1d or 2d array)
Second time series.
window: float, defaults = None
Float that is the radius of the sakoe chiba window (if using Sakoe-Chiba
lower bounding). Value must be between 0. and 1.
itakura_max_slope: float, defaults = None
Gradient of the slope for itakura parallelogram (if using Itakura
Parallelogram lower bounding). Value must be between 0. and 1.
bounding_matrix: np.ndarray (2d of size mxn where m is len(x) and n is len(y)),
defaults = None
Custom bounding matrix to use. If defined then other lower_bounding params
are ignored. The matrix should be structure so that indexes considered in
bound should be the value 0. and indexes outside the bounding matrix should be
infinity.
g: float, defaults = 0.
Constant that controls the curvature (slope) of the function; that is, g
controls the level of penalisation for the points with larger phase
difference.
kwargs: Any
Extra kwargs.
Returns
-------
float
Wdtw distance between the x and y.
Raises
------
ValueError
If the sakoe_chiba_window_radius is not a float.
If the itakura_max_slope is not a float.
If the value of x or y provided is not a numpy array.
If the value of x or y has more than 2 dimensions.
If a metric string provided, and is not a defined valid string.
If a metric object (instance of class) is provided and doesn't inherit from
NumbaDistance.
If the metric type cannot be determined
If both window and itakura_max_slope are set
Examples
--------
>>> import numpy as np
>>> from sktime.distances import wdtw_distance
>>> x_1d = np.array([1, 2, 3, 4]) # 1d array
>>> y_1d = np.array([5, 6, 7, 8]) # 1d array
>>> wdtw_distance(x_1d, y_1d)
27.975712863958133
>>> x_2d = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) # 2d array
>>> y_2d = np.array([[9, 10, 11, 12], [13, 14, 15, 16]]) # 2d array
>>> wdtw_distance(x_2d, y_2d)
243.2106560107827
References
----------
.. [1] Young-Seon Jeong, Myong K. Jeong, Olufemi A. Omitaomu, Weighted dynamic time
warping for time series classification, Pattern Recognition, Volume 44, Issue 9,
2011, Pages 2231-2240, ISSN 0031-3203, https://doi.org/10.1016/j.patcog.2010.09.022.
"""
format_kwargs = {
"window": window,
"itakura_max_slope": itakura_max_slope,
"bounding_matrix": bounding_matrix,
"g": g,
}
format_kwargs = {**format_kwargs, **kwargs}
return distance(x, y, metric="wdtw", **format_kwargs)
def ddtw_distance(
x: np.ndarray,
y: np.ndarray,
window: Union[float, None] = None,
itakura_max_slope: Union[float, None] = None,
bounding_matrix: np.ndarray = None,
compute_derivative=None,
**kwargs: Any,
) -> float:
r"""Compute the derivative dynamic time warping (DDTW) distance between time series.
DDTW is an adaptation of DTW originally proposed in [1]_. DDTW attempts to
improve on dtw by better account for the 'shape' of the time series.
This is done by considering y axis data points as higher level features of 'shape'.
To do this the first derivative of the sequence is taken, and then using this
derived sequence a dtw computation is done.
The default derivative used is:
.. math::
D_{x}[q] = \frac{{}(q_{i} - q_{i-1} + ((q_{i+1} - q_{i-1}/2)}{2}
Where q is the original time series and d_q is the derived time series.
Parameters
----------
x: np.ndarray (1d or 2d array)
First time series.
y: np.ndarray (1d or 2d array)
Second time series.
window: float, defaults = None
Float that is the radius of the sakoe chiba window (if using Sakoe-Chiba
lower bounding). Value must be between 0. and 1.
itakura_max_slope: float, defaults = None
Gradient of the slope for itakura parallelogram (if using Itakura
Parallelogram lower bounding). Value must be between 0. and 1.
bounding_matrix: np.ndarray (2d of size mxn where m is len(x) and n is len(y)),
defaults = None
Custom bounding matrix to use. If defined then other lower_bounding params
are ignored. The matrix should be structure so that indexes considered in
bound should be the value 0. and indexes outside the bounding matrix should be
infinity.
compute_derivative: Callable[[np.ndarray], np.ndarray],
defaults = average slope difference
Callable that computes the derivative. If none is provided the average of the
slope between two points used.
kwargs: Any
Extra kwargs.
Returns
-------
float
Ddtw distance between the x and y.
Raises
------
ValueError
If the sakoe_chiba_window_radius is not a float.
If the itakura_max_slope is not a float.
If the value of x or y provided is not a numpy array.
If the value of x or y has more than 2 dimensions.
If a metric string provided, and is not a defined valid string.
If a metric object (instance of class) is provided and doesn't inherit from
NumbaDistance.
If a resolved metric or compute derivative callable is not no_python compiled.
If the metric type cannot be determined
If the compute derivative callable is not no_python compiled.
If both window and itakura_max_slope are set
Examples
--------
>>> import numpy as np
>>> from sktime.distances import ddtw_distance
>>> x_1d = np.array([1, 2, 3, 4]) # 1d array
>>> y_1d = np.array([5, 6, 7, 8]) # 1d array
>>> ddtw_distance(x_1d, y_1d) # doctest: +SKIP
0.0
>>> x_2d = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) # 2d array
>>> y_2d = np.array([[9, 10, 11, 12], [13, 14, 15, 16]]) # 2d array
>>> ddtw_distance(x_2d, y_2d) # doctest: +SKIP
0.0
References
----------
.. [1] Keogh, Eamonn & Pazzani, Michael. (2002). Derivative Dynamic Time Warping.
First SIAM International Conference on Data Mining.
1. 10.1137/1.9781611972719.1.
"""
if compute_derivative is None:
from sktime.distances._ddtw_numba import average_of_slope
compute_derivative = average_of_slope
format_kwargs = {
"window": window,
"itakura_max_slope": itakura_max_slope,
"bounding_matrix": bounding_matrix,
"compute_derivative": compute_derivative,
}
format_kwargs = {**format_kwargs, **kwargs}
return distance(x, y, metric="ddtw", **format_kwargs)
def dtw_distance(
x: np.ndarray,
y: np.ndarray,
window: Union[float, None] = None,
itakura_max_slope: Union[float, None] = None,
bounding_matrix: np.ndarray = None,
**kwargs: Any,
) -> float:
r"""Compute the dynamic time warping (DTW) distance between two time series.
Originally proposed in [1]_, DTW is an elastic
distance measure, i.e., it is a distance computed after realigning (warping)
two time series to best match each other via time axis distortions [2]_.
This function computes time warping distances only for:
* sequences, time index is ignored
* two time series of equal length
* the Euclidean pairwise distance
For unequal length time series, use ``sktime.dists_kernels.DistFromAligner``
with a time warping aligner such as ``sktime.aligners.AlignerDTW``.
To use arbitrary pairwise distances, use ``sktime.aligners.AlignerDTWfromDist``.
Mathematically, for two sequences
:math:'\mathbf{a}=\{a_1,a_2,\ldots,a_m\}' and :math:'\mathbf{b}=\{b_1,b_2,\ldots,
b_n\}', (assumed equal length for simplicity), DTW first calculates
the pairwise distance matrix :math:'M(
\mathbf{a},\mathbf{b})', the :math:'m \times n',
between series :math:'\mathbf{a}' and :math:'\mathbf{b}',
where :math:'M_{i,j} = d(a_i, b_j)', for a chosen distance measure
:math:`d: \mathbb{R}^h \times \mathbb{R}^h \rightarrow \mathbb{R}`.
In this estimator, the squared Euclidean distance is used, i.e.,
:math:`d(x, y):= (x-y)^2`. A warping path
.. math:: P=((i_1, j_1), (i_2, j_2), \ldots, (i_s, j_s))
is an ordered tuple of indices
:math:`i_k \in \{1, \dots, m\}, j_k \in \{1, \dots, n\}`
which define a traversal path of matrix :math:'M'.
This implementation assumes for warping paths that:
* closed paths: :math:`i_1 = j_1 = 1`; :math:`i_s = m, j_s = n`
* monotonous paths: :math:`i_k \le i_{k+1}, j_k \le j_{k+1}` for all :math:`k`
* strictly monotonous paths: :math:`(i_k, j_k) \neq (i_{k+1}, j_{k+1})` for all
:math:`k`
The DTW path between sequences is the path through :math:'M' that minimizes the total
distance,
over all valid paths (satisfying the above assumptions), given the sequences.
Formally:
The distance for a warping path :math:'P' of length :math:'s' is
.. math:: D_P(\mathbf{a},\mathbf{b}) = \sum_{k=1}^s M_{i_k,j_k}.
If :math:'\mathcal{P}' is the set of all possible paths, the DTW path :math:'P^*'
is the path that has the minimum distance amongst those:
.. math:: P^* = \argmin_{P\in \mathcal{P}} D_{P}(\mathbf{a},\mathbf{b}).
The DTW distance between the two sequences :math:'\mathbf{a},\mathbf{b}' is
the minimum warping path distance:
.. math:: d_{dtw}(\mathbf{a}, \mathbf{b}) = \min_{P\in \mathcal{P}} D_{P}(\mathbf{a},\mathbf{b}) =
D_{P^*}(\mathbf{a},\mathbf{b}).
The optimal warping path $P^*$ can be found exactly through dynamic programming.
This can be a time consuming operation, and it is common to put a
restriction on the amount of warping allowed. This is implemented through
the ``bounding_matrix`` structure, that restricts allowable warpings by a mask.
Common bounding strategies include the Sakoe-Chiba band [3]_ and the Itakura
parallelogram [4_]. The Sakoe-Chiba band creates a warping path window that has
the same width along the diagonal of :math:'M'. The Itakura paralleogram allows
for less warping at the start or end of the sequence than in the middle.
If the function is called with multivariate time series, note that
the matrix :math:'M' is computed with the multivariate squared Euclidean distance,
:math:`d(x, y):= (x-y)^2` = \sum_{i=1}^h (x_i - y_i)^2`
This is sometimes called the "dependent" version of DTW, DTW_D, see [5]_.
Parameters
----------
x: np.ndarray (1d or 2d array)
First time series.
y: np.ndarray (1d or 2d array)
Second time series.
window: float, defaults = None
Float that is the radius of the sakoe chiba window (if using Sakoe-Chiba
lower bounding). Value must be between 0. and 1.
itakura_max_slope: float, defaults = None
Gradient of the slope for itakura parallelogram (if using Itakura
Parallelogram lower bounding). Value must be between 0. and 1.
bounding_matrix: np.ndarray (2d of size mxn where m is len(x) and n is len(y)),
defaults = None
Custom bounding matrix to use. If defined then other lower_bounding params
are ignored. The matrix should be structure so that indexes considered in
bound should be the value 0. and indexes outside the bounding matrix should be
infinity.
kwargs: Any
Extra kwargs.
Returns
-------
float
Dtw distance between x and y.
Raises
------
ValueError
If the sakoe_chiba_window_radius is not a float.
If the itakura_max_slope is not a float.
If the value of x or y provided is not a numpy array.
If the value of x or y has more than 2 dimensions.
If a metric string provided, and is not a defined valid string.
If a metric object (instance of class) is provided and doesn't inherit from
NumbaDistance.
If a resolved metric is not no_python compiled.
If the metric type cannot be determined
If both window and itakura_max_slope are set
Examples
--------
>>> import numpy as np
>>> from sktime.distances import dtw_distance
>>> x_1d = np.array([1, 2, 3, 4]) # 1d array
>>> y_1d = np.array([5, 6, 7, 8]) # 1d array
>>> dtw_distance(x_1d, y_1d)
58.0
>>> x_2d = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) # 2d array
>>> y_2d = np.array([[9, 10, 11, 12], [13, 14, 15, 16]]) # 2d array
>>> dtw_distance(x_2d, y_2d)
512.0
References
----------
.. [1] H. Sakoe, S. Chiba, "Dynamic programming algorithm optimization for
spoken word recognition," IEEE Transactions on Acoustics, Speech and
Signal Processing, vol. 26(1), pp. 43--49, 1978.
.. [2] Ratanamahatana C and Keogh E.: Three myths about dynamic time warping data
mining Proceedings of 5th SIAM International Conference on Data Mining, 2005
.. [3] Sakoe H. and Chiba S.: Dynamic programming algorithm optimization for
spoken word recognition. IEEE Transactions on Acoustics, Speech, and Signal
Processing 26(1):43–49, 1978.
.. [4] Itakura F: Minimum prediction residual principle applied to speech
recognition. IEEE Transactions on Acoustics, Speech, and Signal Processing 23(
1):67–72, 1975.
.. [5] Shokoohi-Yekta M et al.: Generalizing DTW to the multi-dimensional case
requires an adaptive approach. Data Mining and Knowledge Discovery, 31, 1–31 (2017).
""" # noqa: E501
format_kwargs = {
"window": window,
"itakura_max_slope": itakura_max_slope,
"bounding_matrix": bounding_matrix,
}
format_kwargs = {**format_kwargs, **kwargs}
return distance(x, y, metric="dtw", **format_kwargs)
def msm_distance(
x: np.ndarray,
y: np.ndarray,
c: float = 1.0,
window: float = None,
itakura_max_slope: float = None,
bounding_matrix: np.ndarray = None,
**kwargs: dict,
) -> float:
"""Compute the move-split-merge distance.
This metric uses as building blocks three fundamental operations: Move, Split,
and Merge. A Move operation changes the value of a single element, a Split
operation converts a single element into two consecutive elements, and a Merge
operation merges two consecutive elements into one. Each operation has an
associated cost, and the MSM distance between two time series is defined to be
the cost of the cheapest sequence of operations that transforms the first time
series into the second one.
Parameters
----------
x: np.ndarray (1d or 2d array)
First time series.
y: np.ndarray (1d or 2d array)
Second time series.
c: float, default = 1.0
Cost for split or merge operation.
window: Float, defaults = None
Float that is the radius of the sakoe chiba window (if using Sakoe-Chiba
lower bounding). Must be between 0 and 1.
itakura_max_slope: float, defaults = None
Gradient of the slope for itakura parallelogram (if using Itakura
Parallelogram lower bounding). Must be between 0 and 1.
bounding_matrix: np.ndarray (2d array of shape (m1,m2)), defaults = None
Custom bounding matrix to use. If defined then other lower_bounding params
are ignored. The matrix should be structure so that indexes considered in
bound should be the value 0. and indexes outside the bounding matrix should
be infinity.
kwargs: any
extra kwargs.
Returns
-------
float
Msm distance between x and y.
Raises
------
ValueError
If the value of x or y provided is not a numpy array.
If the value of x or y has more than 2 dimensions.
If a metric string provided, and is not a defined valid string.
If a metric object (instance of class) is provided and doesn't inherit from
NumbaDistance.
If a resolved metric is not no_python compiled.
If the metric type cannot be determined
References
----------
.. [1]A. Stefan, V. Athitsos, and G. Das. The Move-Split-Merge metric
for time series. IEEE Transactions on Knowledge and Data Engineering,
25(6):1425–1438, 2013.
"""
format_kwargs = {
"c": c,
"window": window,
"itakura_max_slope": itakura_max_slope,
"bounding_matrix": bounding_matrix,
}
format_kwargs = {**format_kwargs, **kwargs}
return distance(x, y, metric="msm", **format_kwargs)
def twe_distance(
x: np.ndarray,
y: np.ndarray,
window: Union[float, None] = None,
itakura_max_slope: Union[float, None] = None,
bounding_matrix: np.ndarray = None,
lmbda: float = 1.0,
nu: float = 0.001,
p: int = 2,
**kwargs: Any,
) -> float:
"""Time Warp Edit (TWE) distance between two time series.
The Time Warp Edit (TWE) distance is a distance measure for discrete time series
matching with time 'elasticity'. In comparison to other distance measures, (e.g.
DTW (Dynamic Time Warping) or LCS (Longest Common Subsequence Problem)), TWE is a
metric. Its computational time complexity is O(n^2), but can be drastically reduced
in some specific situation by using a corridor to reduce the search space. Its
memory space complexity can be reduced to O(n). It was first proposed in [1].
Parameters
----------
x: np.ndarray (1d or 2d array)
First time series.
y: np.ndarray (1d or 2d array)
Second time series.
window: float, defaults = None
Float that is the radius of the sakoe chiba window (if using Sakoe-Chiba
lower bounding). Value must be between 0. and 1.
itakura_max_slope: float, defaults = None
Gradient of the slope for itakura parallelogram (if using Itakura
Parallelogram lower bounding). Value must be between 0. and 1.
bounding_matrix: np.ndarray (2d of size mxn where m is len(x) and n is len(y)),
defaults = None
Custom bounding matrix to use. If defined then other lower_bounding params
are ignored. The matrix should be structure so that indexes considered in
bound should be the value 0. and indexes outside the bounding matrix should be
infinity.
lmbda: float, defaults = 1.0
A constant penalty that punishes the editing efforts. Must be >= 1.0.
nu: float, defaults = 0.001
A non-negative constant which characterizes the stiffness of the elastic
twe measure. Must be > 0.
p: int, defaults = 2
Order of the p-norm for local cost.
kwargs: Any
Extra kwargs.
Returns
-------
float
Dtw distance between x and y.
Raises
------
ValueError
If the sakoe_chiba_window_radius is not a float.
If the itakura_max_slope is not a float.
If the value of x or y provided is not a numpy array.
If the value of x or y has more than 2 dimensions.
If a metric string provided, and is not a defined valid string.
If a metric object (instance of class) is provided and doesn't inherit from
NumbaDistance.
If a resolved metric is not no_python compiled.
If the metric type cannot be determined
If both window and itakura_max_slope are set
Examples
--------
>>> import numpy as np
>>> from sktime.distances import twe_distance
>>> x_1d = np.array([1, 2, 3, 4]) # 1d array
>>> y_1d = np.array([5, 6, 7, 8]) # 1d array
>>> twe_distance(x_1d, y_1d)
28.0
>>> x_2d = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) # 2d array
>>> y_2d = np.array([[9, 10, 11, 12], [13, 14, 15, 16]]) # 2d array
>>> twe_distance(x_2d, y_2d)
78.37353236814714
References
----------
.. [1] Marteau, P.; F. (2009). "Time Warp Edit Distance with Stiffness Adjustment
for Time Series Matching". IEEE Transactions on Pattern Analysis and Machine
Intelligence. 31 (2): 306–318.
"""
format_kwargs = {
"window": window,
"itakura_max_slope": itakura_max_slope,
"bounding_matrix": bounding_matrix,
"lmbda": lmbda,
"nu": nu,
"p": p,
}
format_kwargs = {**format_kwargs, **kwargs}
return distance(x, y, metric="twe", **format_kwargs)
def squared_distance(x: np.ndarray, y: np.ndarray, **kwargs: Any) -> float:
r"""Compute the squared distance between two time series.
The squared distance between two time series is defined as:
.. math::
sd(x, y) = \sum_{i=1}^{n} (x_i - y_i)^2
Parameters
----------
x: np.ndarray (1d or 2d array)
First time series.
y: np.ndarray (1d or 2d array)
Second time series.
kwargs: Any
Extra kwargs. For squared there are none however, this is kept for
consistency.
Returns
-------
float
Squared distance between x and y.
Raises
------
ValueError
If the value of x or y provided is not a numpy array.
If the value of x or y has more than 2 dimensions.
If a metric string provided, and is not a defined valid string.
If a metric object (instance of class) is provided and doesn't inherit from
NumbaDistance.
If a resolved metric is not no_python compiled.
If the metric type cannot be determined.
Examples
--------
>>> import numpy as np
>>> from sktime.distances import squared_distance
>>> x_1d = np.array([1, 2, 3, 4]) # 1d array
>>> y_1d = np.array([5, 6, 7, 8]) # 1d array
>>> squared_distance(x_1d, y_1d)
64.0
>>> x_2d = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) # 2d array
>>> y_2d = np.array([[9, 10, 11, 12], [13, 14, 15, 16]]) # 2d array
>>> squared_distance(x_2d, y_2d)
512.0
"""
return distance(x, y, metric="squared", **kwargs)
def euclidean_distance(x: np.ndarray, y: np.ndarray, **kwargs: Any) -> float:
r"""Compute the Euclidean distance between two time series.
Euclidean distance is supported for 1d, 2d and 3d arrays.
The Euclidean distance between two time series of length m is the square root of
the squared distance and is defined as:
.. math::
ed(x, y) = \sqrt{\sum_{i=1}^{n} (x_i - y_i)^2}
Parameters
----------