A multivariate mixed segment distance#

MixedSegmentDistance generalizes MDPLA to multivariate segment models: the dissimilarity of two segments is a weighted sum of the differences of their levels, trends, correlation structures, scales and durations. The weights are learned by leave-one-out accuracy on a simplex grid. The example uses the BasicMotions recordings (accelerometer and gyroscope, UEA archive).

import matplotlib.pyplot as plt
import pandas as pd

from mvtsa import pairwise_distances
from mvtsa import warping as wp
from mvtsa.datasets import load_basic_motions
from mvtsa.evaluation import knn_accuracy, mean_average_precision

C, y = load_basic_motions()

Learning the weights#

model = wp.CBDTW(
    n_segments=6,
    n_components=2,
    local=wp.MixedSegmentDistance(
        {"level": 1, "trend": 1, "structure": 1, "scale": 1}
    ),
)
best, scores = wp.learn_segment_weights(model, C, y)
print("learned weights:", best)
top = sorted(scores.items(), key=lambda kv: -kv[1])[:5]
print(
    pd.DataFrame(
        [{**dict(zip(best, w, strict=True)), "accuracy": a} for w, a in top]
    ).round(3)
)
learned weights: {'level': np.float64(0.0), 'trend': np.float64(0.0), 'structure': np.float64(0.75), 'scale': np.float64(0.25)}
   level  trend  structure  scale  accuracy
0    0.0   0.00       0.75   0.25     1.000
1    0.0   0.25       0.50   0.25     1.000
2    0.0   0.00       0.50   0.50     0.988
3    0.0   0.25       0.25   0.50     0.988
4    0.0   0.50       0.25   0.25     0.988

Comparison#

rows = []
for name, m in [
    ("mixed (learned)", model),
    ("CBDTW, Krzanowski", wp.CBDTW(6, 2).fit(C)),
    ("CBDTW, Gaussian W2", wp.CBDTW(6, 2, local="gaussian_w2").fit(C)),
    ("DTW", "dtw"),
]:
    D = pairwise_distances(C, metric=m)
    rows.append(
        {
            "measure": name,
            "1-NN": knn_accuracy(D, y),
            "mAP": mean_average_precision(D, y),
        }
    )
print(pd.DataFrame(rows).round(3).to_string(index=False))
           measure  1-NN   mAP
   mixed (learned) 1.000 0.937
 CBDTW, Krzanowski 0.900 0.739
CBDTW, Gaussian W2 0.975 0.866
               DTW 0.975 0.857

Accuracy over the weight simplex#

Every point is one weighting of the four components; the structure weight on the horizontal axis.

fig, ax = plt.subplots(figsize=(5, 3.2))
w_struct = [w[2] for w in scores]
ax.scatter(
    w_struct,
    list(scores.values()),
    c=[w[3] for w in scores],
    cmap="viridis",
    s=28,
)
ax.set_xlabel("weight of the correlation structure")
ax.set_ylabel("LOO 1-NN accuracy")
ax.set_title("colour: weight of the scale", fontsize=9, loc="left")
plt.show()
colour: weight of the scale

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

Gallery generated by Sphinx-Gallery