Segmentation, Warping and Clustering of Multivariate Time Series in PythonThe mvtsa toolbox

Chapter 12
Model operations

An analysis that runs once in a notebook is an experiment; an analysis that runs every day on new data is a model in operation, and it has to be reproducible, versioned, monitored and documented. This chapter shows how mvtsa supports the life cycle of time-series models: configurations as code, an analysis pipeline that learns regimes and labels new data, model files with integrity checks, a registry with stages, experiment tracking, data contracts, drift monitoring and model cards. The layer is deliberately light – files and JSON – and mirrors to MLflow when it is available [145].

12.1 The life cycle

Figure 12.1 shows the life cycle the package supports. An analysis is designed and tuned on historical data (chapter 10); its configuration is written to a file; the fitted model is saved with its metadata and registered; the production version labels new data; a monitor compares every new batch with the reference data and raises an alert when the data drift; the alert triggers a new round of analysis. Every arrow of the figure is a function of the package.

Figure12.1
Figure 12.1. Life cycle of a time-series model in mvtsa: design on historical data, configuration as code, fitted and registered models, production use, drift monitoring that triggers a new analysis, and documentation.

12.2 Configurations and pipelines

Every object of the package – segmenters, costs, warping models, clusterers, pipelines, nested ensembles – is written to a plain dictionary by to_config and rebuilt by from_config; save_config and load_config store the dictionary as JSON or YAML. A configuration file under version control is the reproducible description of an analysis. AnalysisPipeline is the deployable unit: it standardizes the data, segments them, learns recurring regimes by clustering the segment models of the training data (Gaussian descriptors and the 2-Wasserstein distance by default) and labels the segments of new data with the nearest regime model.

pipe = mlops.AnalysisPipeline( 
    sg.BottomUp("normal", n_segments=8, initial_size=15), n_regimes=3 
) 
cfg = mlops.to_config(pipe) 
print(mlops.save_config(pipe, workdir / "pipeline.yaml").read_text()) 
same = mlops.from_config(cfg)  # an identical, unfitted pipeline
   

12.3 Model files, registry and tracking

save_model writes a model directory with the pickled object, its configuration and a metadata file: the versions of the package and its libraries, the creation time, a fingerprint of the training data, metrics and tags, and a SHA-256 hash of the model file that load_model verifies, so that a corrupted or replaced file is detected before it is used. ModelRegistry keeps the versions of named models in a folder with stages – staging, production, archived – and loads the production version by name. ExperimentTracker records runs with their parameters, metrics, figures and models in local JSON files and mirrors them to MLflow when it is installed.

pipe.fit(X_train) 
seg = pipe.predict(X_new) 
print( 
    "regimes of the new data:", 
    seg.labels.tolist(), 
    "| true regimes:", 
    states[8:].tolist(), 
) 
reg = mlops.ModelRegistry(workdir / "registry") 
v1 = reg.register( 
    "regimes", 
    pipe, 
    data=X_train, 
    metrics={"covering": 0.97}, 
    tags={"plant": "demo"}, 
) 
reg.promote("regimes", v1, "production") 
print(reg.list()[["name", "version", "stage", "created"]]) 
production = reg.load("regimes", stage="production")
   

12.4 Contracts and drift

A model is valid only while the data look like the training data. A DataContract inferred from the reference data checks the schema (number and names of the variables), missing values and ranges of new data before anything else. The DriftMonitor checks every new batch against the reference in several ways: the fractions of samples beyond the T2 and Q limits of the reference PCA model (expected: the significance level), the Krzanowski similarity of the batch PCA model to the reference model, the largest per-variable Kolmogorov–Smirnov statistic, the population stability index of every variable,

PSI = ∑ b(qb −pb)log⁡ qb pb, (12.1)

with pb and qb the reference and current shares of bin b, and optionally the distribution of segment durations under a segmenter. An alert is raised when an exceedance rate is several times the significance level, the similarity falls below a threshold or a PSI exceeds 0.25. In fig. 12.2 the correlation structure of the process changes after the reference period; the Q exceedance and the similarity react in the first batch after the change.

mon = mlops.DriftMonitor(n_components=1, similarity_threshold=0.8).fit( 
    reference 
) 
for a in range(300, len(X), 100): 
    r = mon.update(X[a : a + 100]) 
    print( 
        f"batch {a:4d}-{a + 100:4d}: Q exceed {r[’q_exceedance’]:.2f}  " 
        f"similarity {r[’similarity’]:.2f}  " 
        f"alerts {r[’alerts’]}" 
    )
   

Figure12.2

Figure 12.2. Batch-wise drift monitoring: Krzanowski similarity of every batch model to the reference model (circles) and the rate of Q exceedances (squares); the true changes of the correlation structure are dashed. Produced by examples/10_mlops/plot_02_drift_monitoring.py.

Open in ColabExample plot_02_drift_monitoring.py in the gallery

12.5 Model cards and the command line

A model card documents what a model is for, on which data it was evaluated, how well it performed and where its limits are [146]; model_card writes one in Markdown from the model’s configuration, the metrics and free-text fields. Finally, the mvtsa command line segments a CSV file with any registered method and writes the segmentation and a plot, computes the distance matrix of a folder of series, monitors a file against a saved reference, and reports the installation – the entry points for scheduled jobs.

card = mlops.model_card( 
    sg.PCASegmenter(n_segments=5, n_components=1), 
    name="PCA segmentation of unit 7", 
    purpose="Detect changes of the correlation structure of four process variables.", 
    data_description="Synthetic data with four correlation switches.", 
    metrics={"f1": 1.0, "covering": 1.0}, 
    limitations="Blind to pure mean shifts; assumes one latent variable.", 
    path=workdir / "MODEL_CARD.md", 
) 
print(card)
   

In a nutshell: Model operations

Configurations as code make analyses reproducible; AnalysisPipeline learns regimes and labels new data; model files carry versions, data fingerprints and integrity hashes; the registry manages versions and stages; the tracker records experiments locally and in MLflow; data contracts and the drift monitor – T2/Q exceedances, PCA similarity, KS, PSI, segment durations – tell when a model is no longer valid; model cards document it. In mvtsa: to_config, from_config, AnalysisPipeline, save_model, load_model, ModelRegistry, ExperimentTracker, DataContract, DriftMonitor, model_card, the mvtsa command.