Chapter 10
Evaluation and validation
A segmentation, an alignment or a clustering is a hypothesis about the data. This chapter shows how to test it: with metrics that compare it with a ground truth when one exists, with retrieval curves for distance measures, with stability under perturbations when no truth is available, and with statistical tests when many methods are compared on many data sets. It closes with the systematic tuning of parameters. Every metric has blind spots, so the chapter also shows how the metrics react to typical mistakes.
10.1 Segmentation metrics
Let be the true and the predicted change points of a series of length .
Detection. A predicted change point is a true positive if it lies within a margin of a true one that has not been matched yet; greedy matching in the order of the distances makes the matching one-to-one. Precision, recall and their harmonic mean, the F1 score, follow [31] (change_point_scores).
Overlap. The covering of the true segmentation by the predicted one ,
| (10.1) |
weights the best Jaccard overlap of every true segment by its length [31, 138] (covering). It needs no margin and degrades gracefully with small shifts.
Boundary error. The Hausdorff distance
| (10.2) |
is the worst boundary error; the annotation error compares the numbers of change points; the mean boundary error averages the distances of matched pairs.
States. When segments carry state labels, the adjusted Rand index and the adjusted mutual information of the per-sample labels measure how well the states are recovered, independently of the label names (state_scores). evaluate_segmentation returns all of these at once.
Figure 10.1 and the table printed by the example show how the metrics react to typical mistakes. A shift of 15 samples is a complete failure for the F1 score with a margin of 10 but costs little covering; a missed and an extra change point cost similar F1 but very different Hausdorff distances; a flood of spurious change points keeps the recall at one while precision and covering collapse. No single number describes a segmentation; F1 with a sensible margin and the covering together are a good default, and recent work proposes interpretable measures that also classify the kind of error [139].
rows = [ {"case": k, **evaluate_segmentation(truth, v, T, margin=10)} for k, v in cases.items() ] table = pd.DataFrame(rows)[ [ "case", "precision", "recall", "f1", "covering", "hausdorff", "annotation_error", ] ] print(table.round(3).to_string(index=False))
10.2 Clustering metrics
With true labels, a clustering is scored by the adjusted Rand index, the adjusted and normalized mutual information, the purity and the accuracy after the best matching of clusters to classes (clustering_scores). Without labels, internal indices compare the compactness and the separation of the clusters on the distance matrix: the silhouette and the Dunn index (silhouette, dunn_index); for fuzzy partitions the partition coefficient and the partition entropy measure how crisp the memberships are (partition_coefficient, partition_entropy).
10.3 Retrieval
A distance measure is evaluated by how well it retrieves objects of the same class. The leave-one-out 1-NN accuracy is the standard number (knn_accuracy). Bankó used a finer view [8]: for every query the other objects are ranked by distance, and when the -th object of the query’s class is reached after retrieved objects, the precision at recall level is ; averaging over the queries gives a precision–recall curve (precision_recall_curve_knn, fig. 8.3). The mean average precision summarizes the curve in one number (mean_average_precision); it rewards measures that rank all objects of a class high, not only the nearest one.
10.4 Stability
Without ground truth, a segmentation can still be validated by its stability. The series is perturbed many times – Gaussian noise of a relative level is added and a random block of a given fraction of the series is segmented – and the change points of every run are mapped back to global time. The boundary frequency, the agreement profile (6.4) over the runs, measures how often a change point is found near every sample; the frequency at a change point of the clean segmentation is its support, and the mean support is the stability (segmentation_stability). The same idea, with resampled objects instead of perturbed series, validates clusterings [140] (clustering_stability).
Stability is informative but not a substitute for a selection rule. With too few segments the boundaries wander between runs; once all true changes are found the support saturates. The extra change points of an over-segmentation can be stable too, if they sit at consistent features of the data – in fig. 10.2 right next to the true changes.
good = segmentation_stability( sg.BottomUp("normal", n_segments=5, initial_size=10), X, n_runs=20, random_state=0, ) over = segmentation_stability( sg.BottomUp("normal", n_segments=9, initial_size=10), X, n_runs=20, random_state=0, ) print( "5 segments: support", good["support"].round(2), "stability", round(good["stability"], 2), ) print( "9 segments: support", over["support"].round(2), "stability", round(over["stability"], 2), ) print( "change points with 9 segments:", over["reference"].change_points, "| true:", cps, )
10.5 Comparing methods
A claim that one method is better than another needs many data sets and a statistical test. The Benchmark class runs every method on every data set, records the metrics and the run times, and keeps going when a method fails. The Friedman test checks whether the average ranks of methods on data sets differ at all; if they do, the Nemenyi test declares two methods different when their average ranks differ by more than the critical difference
| (10.3) |
where is the studentized range statistic divided by [141] (friedman_nemenyi). The critical-difference diagram draws the ranks with bars joining methods that do not differ significantly (fig. 10.3). Because post-hoc tests on mean ranks depend on the other methods of the comparison [142], pairwise Wilcoxon signed-rank tests with Holm’s correction are provided as well (wilcoxon_holm). Ten data sets are too few to separate eight methods: the example finds the Friedman test highly significant, but only the largest rank differences exceed the critical difference.
stat = friedman_nemenyi(bench.pivot("covering")) print( f"Friedman p = {stat[’p_value’]:.2g}, CD = {stat[’critical_difference’]:.2f}" ) print( wilcoxon_holm(bench.pivot("covering")) .head(5) .round(4) .to_string(index=False) )
10.6 Tuning
Parameters are tuned against labelled series by a grid search on a segmentation metric averaged over the series (grid_search_segmenter), or without labels by maximizing stability (criterion="stability"). A one-parameter sensitivity study shows how robust a method is: sensitivity runs a factory over a range of values and records the number of segments, the change points, the run time and an optional score. The example scripts of the package end with such studies, and the parameters of the book’s figures come from them.
best, table = grid_search_segmenter( lambda **p: sg.PCASegmenter(n_segments=4, **p), { "n_components": [1, 2, 3], "statistic": ["Q", "T2", "both"], "initial_size": [5, 10, 20], }, train, criterion="covering", ) print("best:", best) print(table.head(6).round(3).to_string(index=False))
In a nutshell: Evaluation and validation
Change points are scored by F1 within a margin, by the covering of the true segments, by the Hausdorff distance and by the annotation error; states and clusterings by ARI and AMI; distance measures by 1-NN accuracy, precision–recall curves and mean average precision. Stability under noise and block resampling validates segmentations without ground truth. Methods are compared over many data sets with the Friedman test, the Nemenyi critical difference and Wilcoxon–Holm tests; parameters are tuned by grid search or stability. In mvtsa: evaluate_segmentation, clustering_scores, knn_accuracy, precision_recall_curve_knn, mean_average_precision, segmentation_stability, Benchmark, friedman_nemenyi, wilcoxon_holm, grid_search_segmenter, sensitivity.