Predictive homogeneity with any scikit-learn model#

Two neighbouring segments belong together if no model can tell their samples apart. PredictiveSegmenter turns this idea – the classifier two-sample test (Lopez-Paz and Oquab, 2017) – into a bottom-up merging criterion: the cross-validated accuracy of a classifier that predicts the side of every sample, rescaled so that chance level is zero. With kind="regression" the criterion is the loss of predicting the variables of one segment with a model trained on the other. Any scikit-learn estimator can be plugged in.

import matplotlib.pyplot as plt
import pandas as pd
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression

import mvtsa as mv
from mvtsa import segmentation as sg
from mvtsa.evaluation import evaluate_segmentation

X, cps, _ = mv.datasets.make_piecewise_stationary(
    n_segments=4, length=150, n_variables=3, change="all", random_state=12
)

Three classifiers#

A linear classifier sees mean shifts only; quadratic discriminant analysis and random forests also see changes of the covariance.

rows = []
for name, est in [
    ("logistic", LogisticRegression(max_iter=500)),
    ("QDA", QuadraticDiscriminantAnalysis()),
    ("random forest", RandomForestClassifier(n_estimators=60, random_state=0)),
]:
    s = sg.PredictiveSegmenter(
        "classifier", estimator=est, n_segments=4, initial_size=30
    ).segment(X)
    rows.append(
        {"estimator": name, **evaluate_segmentation(cps, s, len(X), margin=15)}
    )
print(pd.DataFrame(rows)[["estimator", "f1", "covering"]].round(3))
seg = sg.PredictiveSegmenter(
    "classifier",
    estimator=QuadraticDiscriminantAnalysis(),
    n_segments=4,
    initial_size=30,
).segment(X)
mv.viz.plot_segmentation(
    X, seg, truth=cps, title="Predictive homogeneity (QDA)"
)
plt.show()
Predictive homogeneity (QDA)
       estimator   f1  covering
0       logistic  1.0       1.0
1            QDA  1.0       1.0
2  random forest  1.0       1.0

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

Gallery generated by Sphinx-Gallery