Correlation-based dynamic time warping#

Bankó and Abonyi (2012) compare multivariate series by the sequence of their correlation structures: every series is segmented bottom-up so that the segments are homogeneous in the PCA sense, and DTW aligns the segment sequences with the local dissimilarity \(1-s_{PCA}\) (Krzanowski). The warping runs over a few dozen segments instead of hundreds of samples, so it is fast, and it ignores differences that do not change the correlation of the variables. The example uses synthetic on-line signatures (pen position, pressure and angles).

import matplotlib.pyplot as plt
import numpy as np

from mvtsa import pairwise_distances, viz
from mvtsa import warping as wp
from mvtsa.datasets import make_signatures
from mvtsa.evaluation import (
    knn_accuracy,
    mean_average_precision,
    precision_recall_curve_knn,
)

data, writer = make_signatures(n_writers=6, n_per_writer=8, random_state=0)

Segment-level alignment of two signatures of the same writer#

cb = wp.CBDTW(n_segments=10, n_components=2).fit(data)
path = cb.path(0, 1)
print(
    "segments:",
    len(cb.models_[0]),
    len(cb.models_[1]),
    "| CBDTW distance:",
    round(cb.distance(0, 1), 3),
)
viz.plot_segment_alignment(
    data[0], data[1], cb.models_[0], cb.models_[1], path, channel=0
)
plot 01 cbdtw signatures
segments: 10 10 | CBDTW distance: 2.673

<Axes: xlabel='time'>

Retrieval: precision–recall curves#

For every query the other signatures are ranked by distance (Bankó, 2015, Alg. 3.1).

std = [(x - np.vstack(data).mean(0)) / np.vstack(data).std(0) for x in data]
measures = {
    "CBDTW": cb.pairwise(),
    "SEGPCA (no warping)": wp.CBDTW(10, 2, warping=False).fit(data).pairwise(),
    "DTW": pairwise_distances(std, metric="dtw"),
    "DTW, 10% band": pairwise_distances(std, metric="dtw", window=0.1),
}
curves = {}
for name, D in measures.items():
    curves[name] = precision_recall_curve_knn(D, writer, r_items=7)
    print(
        f"{name:20s} 1-NN {knn_accuracy(D, writer):.3f}  "
        f"mAP {mean_average_precision(D, writer):.3f}"
    )
viz.plot_precision_recall(curves)
plot 01 cbdtw signatures
CBDTW                1-NN 1.000  mAP 0.999
SEGPCA (no warping)  1-NN 1.000  mAP 0.981
DTW                  1-NN 1.000  mAP 1.000
DTW, 10% band        1-NN 1.000  mAP 0.998

<Axes: xlabel='recall', ylabel='precision'>

Parameter study: the number of segments#

for k in (4, 6, 10, 15, 25):
    D = wp.CBDTW(n_segments=k, n_components=2).fit(data).pairwise()
    print(f"{k:3d} segments: mAP {mean_average_precision(D, writer):.3f}")
plt.show()
 4 segments: mAP 0.997
 6 segments: mAP 1.000
10 segments: mAP 0.999
15 segments: mAP 1.000
25 segments: mAP 1.000

Total running time of the script: (0 minutes 6.238 seconds)

Gallery generated by Sphinx-Gallery