Evaluation#

The tsseg.metrics namespace provides classes implementing common segmentation quality measures. Every metric inherits from BaseMetric and shares the same compute(y_true, y_pred) contract: it returns a dictionary with at least a "score" key (calling the metric object directly is a shortcut for compute).

Change point metrics#

These metrics compare two sets of sparse change point indices. F1Score, Covering, BidirectionalCovering and GaussianF1Score also need the series length: pass it as compute(y_true, y_pred, n_timepoints=n), and the change points may then include or omit 0 and n. Without it, the length is read from the change points (y_true must end with it) and a UserWarning is emitted; with dense labels and convert_labels_to_segments=True, it is the length of the labels. HausdorffDistance takes the same n_timepoints and convert_labels_to_segments arguments: it then compares only the change points inside the series, without 0 and n. Without either, it compares the two lists as they are given, boundaries included.

The figures below score one prediction, on a series of 1,000 points with true change points at 300, 600 and 800 and predicted ones at 320, 450 and 790. The scores they show are computed by the metrics when the documentation is built.

F1 score#

F1Score matches each true change point with the closest predicted one within margin points (a float is a fraction of the series length), each prediction being matched at most once. Precision is the share of matched predictions, recall the share of matched true change points.

F1Score with a margin of 50 points: true change points [300, 600, 800], predicted [320, 450, 790], F1 0.67window [250, 350] around 300±50window [550, 650] around 600window [750, 850] around 800TruthPrediction300600800320450790true change point 300true change point 600: missed (FN)FNtrue change point 800predicted 320: TPTPpredicted 450: FPFPpredicted 790: TPTP2 TP, 1 FP, 1 FN · precision 2/3 = 0.67 · recall 2/3 = 0.67 · F1 = 0.67

Gaussian F1 score#

GaussianF1Score replaces the window by a Gaussian reward of width \(\sigma\) = sigma_fraction · n around each true change point (1 % of the length by default; 2.5 % in the figure). A prediction earns the height of the curve at its position, so a close miss keeps partial credit. Predictions and true change points are paired one to one so that the total reward is maximal. Precision and recall divide that reward by the number of predictions and of true change points.

GaussianF1Score with sigma = 25 points: each prediction earns the height of the Gaussian around the true change point it is paired with (one to one, maximum total reward); Gaussian F1 0.55TruthPrediction300600800predicted 320: reward 0.7260.73320predicted 450: reward 0.0000.00450predicted 790: reward 0.9230.92790W = 0.73 + 0.00 + 0.92 = 1.65 · precision W/3 = 0.55 · recall W/3 = 0.55 · Gaussian F1 = 0.55σ = 25 points

Hausdorff distance#

HausdorffDistance is the largest distance, in points, from a change point of either set to the nearest change point of the other set (lower is better). A single missed or spurious change point is enough to make it large.

HausdorffDistance: the largest distance from a change point to the nearest change point of the other set, 150 pointsTruthPrediction300600800320450790300 to 320: 20 points20600 to 450: 150 points150800 to 790: 10 points10largest distance to the nearest change point of the other set: Hausdorff = 150 points

Covering#

Covering scores segments rather than change points: each true segment takes its best intersection over union (IoU) with a predicted segment, and the average is weighted by the length of the true segments. BidirectionalCovering also covers the predicted segments by the true ones and combines the two directions (harmonic mean by default).

Covering: each true segment takes its best intersection over union with a predicted segment, weighted by its length; Covering 0.71TruthPredictiontrue segment [0, 300)true segment [300, 600)true segment [600, 800)true segment [800, 1000)predicted segment [0, 320)predicted segment [320, 450)predicted segment [450, 790)predicted segment [790, 1000)[0, 300) best matches [0, 320): IoU 0.938IoU 0.94[300, 600) best matches [320, 450): IoU 0.433IoU 0.43[600, 800) best matches [450, 790): IoU 0.543IoU 0.54[800, 1000) best matches [790, 1000): IoU 0.952IoU 0.950n = 1,000Covering = (300·0.94 + 300·0.43 + 200·0.54 + 200·0.95) / 1,000 = 0.71prediction covered by the truth: 0.74 · BidirectionalCovering (harmonic mean) = 0.73

F1Score

Computes the F1-score for change point detection.

Covering

Computes the Covering score for a segmentation.

HausdorffDistance

Computes the Hausdorff distance between two sets of change points.

GaussianF1Score

Gaussian-weighted alternative to the classic F1 score.

BidirectionalCovering

Bidirectional extension of the classical Covering metric.

Online detection metrics#

OnlineF1Score(max_delay=D) scores the event log emitted by an online detector. Pass true change point indices without 0 or n, the structured EVENT_DTYPE array (typically detector.events_), and the observed length explicitly as n_timepoints=n.

For each true change \(c_i\), only the first event emitted at a time \(\tau\) satisfying \(c_i \leq \tau < \min(c_i+D, c_{i+1})\) counts as a true positive. The final change has no next-change bound. Other events are false alarms: an alarm before a change earns no credit for that change, and a duplicate alarm remains a false positive. Ties in detection time retain the event log’s order. Estimated positions and event scores do not affect matching; scores may be NaN. All indices are zero-based.

The returned score is F1@D, alongside precision, recall, mean_delay, median_delay, false_alarms_per_10000 and mean_localization_error. Delays use \(\tau-c_i\); localization uses \(|p-c_i|\), both in points and only over matches. With no matches, these summaries are NaN. With no changes and no events, F1, precision and recall are 1; if just one is empty, all three are 0. False alarms are divided by the whole observed length, including warm-up.

from tsseg.algorithms.base_online import make_events
from tsseg.metrics import OnlineF1Score

events = make_events([9, 19, 29], [12, 23, 36])
result = OnlineF1Score(max_delay=5).compute(
    [10, 20, 30], events, n_timepoints=100
)
# The third event misses its deadline at 35.
# score=2/3, mean_delay=2.5, median_delay=2.5,
# false_alarms_per_10000=100, mean_localization_error=1.

After streaming with detector.update(X), the same call accepts detector.events_ and n_timepoints=detector.n_seen_. A batch predict(X) returns positions only: it can be scored with the offline metrics above, while online delay evaluation requires the event log.

Choose D for the application’s allowed response time. Its upper bound is excluded, so D=1 requires detection exactly at the change. Average run length without a change and worst-case delay require controlled simulations; they are not estimated here from labelled series.

OnlineF1Score

F1 under a detection deadline, with delay and false-alarm diagnostics.

State detection metrics#

These metrics compare two dense label arrays of equal length. The label values carry no meaning: predicted states are compared with the true ones up to a renaming (by pairs of points, or after Hungarian matching for SMS). The figures use a series of 1,000 points in states A, B, A and C.

ARI, AMI and NMI#

The clustering scores of scikit-learn: the Adjusted Rand Index counts the pairs of time points that both labelings put in the same state or in different states, adjusted for chance; the Normalized and Adjusted Mutual Information measure how much one labeling tells about the other, AMI being adjusted for chance. They ignore time: every point counts the same, wherever it is.

ARI, AMI and NMI compare labelings up to a renaming of the states: the renamed prediction scores 1, the prediction that merges states A and C scores ARI 0.76TruthTruth: [0, 300): AATruth: [300, 600): BBTruth: [600, 800): AATruth: [800, 1000): CCRenamedRenamed: [0, 300): 22Renamed: [300, 600): 00Renamed: [600, 800): 22Renamed: [800, 1000): 11MergedMerged: [0, 300): AAMerged: [300, 600): BBMerged: [600, 800): AAMerged: [800, 1000): BBARIAMINMI1.001.001.001.001.001.000.760.800.80

WARI and WNMI#

WeightedAdjustedRandIndex and WeightedNormalizedMutualInformation weight each time point by \(1 + \alpha d\), where d is its distance to the nearest true boundary and \(\alpha\) = 0.1 by default. A boundary placed a little late costs less than the same number of wrong points inside a segment.

WARI and WNMI weight each time point by 1 + 0.1 times its distance to the nearest true boundary: 40 wrong points next to a boundary cost less than 40 wrong points inside a segmentTruthTruth: [0, 300): AATruth: [300, 600): BBTruth: [600, 800): AATruth: [800, 1000): CCWeightweights of [600, 640): 1 to 4.9weights of [430, 470): 14 to 16116w = 1 + 0.1·dd: distance to thenearest true boundaryLateLate: [0, 300): AALate: [300, 640): BBLate: [640, 800): AALate: [800, 1000): CCLate: 40 wrong points in [600, 640)InsideInside: [0, 300): AAInside: [300, 430): BBInside: [430, 470): AAInside: [470, 600): BBInside: [600, 800): AAInside: [800, 1000): CCInside: 40 wrong points in [430, 470)ARIWARINMIWNMI0.870.950.870.930.870.750.870.79

State Matching Score#

StateMatchingScore (SMS) first maps the predicted states to the true ones with the Hungarian algorithm. Each run of wrong points with the same predicted label is an error segment, typed by what it covers: a delay continues the neighbouring state (a boundary placed late or early), an isolation is a spurious state inside one true segment, a transition covers one true boundary and a missing error covers several, so that a whole true segment is lost. The score is \(1 - (L + P) / n\), with L the number of wrong points and P their penalties, weighted by type (weights); isolations and transitions are also weighted by their distance to the nearest true boundary.

State Matching Score: the wrong points form error segments typed as delay, isolation, transition and missing; SMS 0.81TruthTruth: [0, 200): AATruth: [200, 450): BBTruth: [450, 600): AATruth: [600, 640): CCTruth: [640, 800): AATruth: [800, 1000): CCPredictionPrediction: [0, 230): AAPrediction: [230, 320): BBPrediction: [320, 345): CCPrediction: [345, 435): BBPrediction: [435, 470): CCPrediction: [470, 590): AAPrediction: [590, 660): BBPrediction: [660, 800): AAPrediction: [800, 1000): CCdelay: [200, 230), 30 points, penalty 3.00delayisolation: [320, 345), 25 points, penalty 4.24isolationtransition: [435, 470), 35 points, penalty 2.75transitionmissing: [590, 660), 70 points, penalty 17.50missingSMS = 1 − (L + P) / n = 1 − (160 + 27.5) / 1,000 = 0.81L = 160 wrong points, P = their penalties (default weights)

AdjustedRandIndex

Computes the Adjusted Rand Index (ARI).

AdjustedMutualInformation

Computes the Adjusted Mutual Information (AMI).

NormalizedMutualInformation

Computes the Normalized Mutual Information (NMI).

WeightedAdjustedRandIndex

Computes the Weighted Adjusted Rand Index (WARI).

WeightedNormalizedMutualInformation

Computes the Weighted Normalized Mutual Information (WNMI).

StateMatchingScore

Computes the State Matching Score (SMS).

Partially annotated references#

A reference may leave points without a usable label: missing truth (often coded -1), labels the provider marks as unknown, or classes that are not scored, such as a background of unannotated activities. Deleting these points before scoring would join unrelated intervals and create transitions that no annotator saw. The metrics instead take scored_intervals, the half-open intervals [a, b) of the points to score, in original coordinates; the series keeps its length and the prediction is never cut. scored_islands() derives them from a label sequence.

  • ARI, AMI, NMI: the score of the scored points.

  • WARI, WNMI: the distances that weight the points are measured in original coordinates, to the true changes inside each interval and to its edges, before the other points are left out.

  • SMS (masked SMS): one Hungarian mapping, fitted on the scored points and applied to all; error segments stop at the edges of the intervals, where neighbours count as absent; the edges anchor the boundary distance without being true boundaries; losses are divided by the number of scored points. The output adds n_scored and n_total.

  • F1: an interval [a, b) judges the change points a + 1 to b - 1. True and predicted change points elsewhere count for nothing, and a match never crosses a gap, even within the margin.

  • Covering, BiC: true and predicted segments are clipped to each interval of at least two points and matched inside it; the coverings are weighted by the scored duration.

Scores do not depend on the length of the unscored gaps, and an interval covering the whole series gives the plain score. A reference without any scored point, or without any position where a change point can be judged, raises a ValueError. Gaussian F1 and the Hausdorff distance do not take scored_intervals.

import numpy as np
from tsseg.metrics import F1Score, StateMatchingScore, scored_islands

y_true = np.array([0, 0, 0, -1, -1, 1, 1, 1])  # -1: no reference
y_pred = np.array([0, 0, 0, 0, 1, 1, 1, 1])
support = scored_islands(y_true, unscored=[-1])  # [(0, 3), (5, 8)]
StateMatchingScore().compute(y_true, y_pred, scored_intervals=support)
# {'score': 1.0, 'n_scored': 6, 'n_total': 8}

# Change points: the prediction at 4 lies in the gap and counts for nothing.
# (For change points, background classes stay in the support: their edges
# are true change points. Only the points of unknown truth are left out.)
F1Score(margin=1).compute(
    [2], [2, 4], n_timepoints=8, scored_intervals=support
)["score"]  # 1.0

scored_islands

Maximal runs of samples whose label is not in unscored.

Base protocol#

class BaseMetric(**kwargs)[source]#

Bases: ABC

Base class for all metrics.

abstractmethod compute(y_true, y_pred, **kwargs)[source]#

Computes the value of the metric.

Parameters:
  • y_true (ndarray) – Ground truth labels or change points.

  • y_pred (ndarray) – Predicted labels or change points.

  • **kwargs – Additional arguments for metric computation.

Return type:

dict[str, float]

Returns:

A dictionary containing metric names and their values.

Usage#

from tsseg.algorithms import DynpDetector
from tsseg.algorithms.utils import extract_cps
from tsseg.data.datasets import load_mocap
from tsseg.metrics import F1Score, StateMatchingScore

X, y = load_mocap(trial=0)

# Change point evaluation: indices without 0 and n on both sides
y_pred_cps = DynpDetector(n_cps=len(extract_cps(y))).fit_predict(X)
f1 = F1Score(margin=0.01)  # a float margin is a fraction of n_timepoints
result = f1.compute(extract_cps(y), y_pred_cps, n_timepoints=len(y))
print(result["score"], result["precision"], result["recall"])

# State detection evaluation: one label per time point
sms = StateMatchingScore()
result = sms.compute(y, y)
print(result["score"])  # 1.0

See Getting started for end-to-end examples that combine detectors and metrics.