PCA models: T², Q and similarity factors#

A PCA model fitted on normal operation describes the correlation of the variables; the Hotelling \(T^2\) statistic measures the variation inside the model, the \(Q\) statistic the distance from it. When the correlation structure changes, \(Q\) exceeds its control limit – the principle behind PCA-based segmentation and monitoring.

import matplotlib.pyplot as plt
import numpy as np

from mvtsa import viz
from mvtsa.datasets import make_correlation_switching
from mvtsa.representation import (
    PCAModel,
    chordal_distance,
    krzanowski_similarity,
)

X, cps, _ = make_correlation_switching(
    n_segments=2, length=300, random_state=3
)

Monitoring statistics of a reference model#

model = PCAModel(n_components=1).fit(X[:300])  # first regime as reference
t2_lim, q_lim = model.control_limits(alpha=0.01)
q = model.q_statistic(X)
print(
    f"Q limit {q_lim:.3f}; exceedance before/after the change: "
    f"{np.mean(q[:300] > q_lim):.2f} / {np.mean(q[300:] > q_lim):.2f}"
)
viz.plot_pca_statistics(X, model)
plot 03 pca models
Q limit 0.088; exceedance before/after the change: 0.01 / 0.86

<Figure size 700x360 with 2 Axes>

Comparing PCA models: Krzanowski similarity#

m1, m2 = PCAModel(1).fit(X[:300]), PCAModel(1).fit(X[300:])
print(
    "s_PCA(regime 1, regime 1 half) =",
    round(m1.similarity(PCAModel(1).fit(X[:150])), 3),
)
print("s_PCA(regime 1, regime 2)      =", round(m1.similarity(m2), 3))
print(
    "chordal distance               =",
    round(chordal_distance(m1.components_, m2.components_), 3),
)
s_PCA(regime 1, regime 1 half) = 1.0
s_PCA(regime 1, regime 2)      = 0.11
chordal distance               = 0.943

Parameter study: window length and similarity#

The similarity of short windows to the reference fluctuates; longer windows estimate the subspace better.

fig, ax = plt.subplots(figsize=(6, 3))
for w in (20, 50, 100):
    s = [
        krzanowski_similarity(
            m1.components_, PCAModel(1).fit(X[a : a + w]).components_
        )
        for a in range(0, len(X) - w, 5)
    ]
    ax.plot(np.arange(0, len(X) - w, 5) + w, s, label=f"window {w}")
ax.axvline(300, color="gray", ls=":")
ax.set_xlabel("window end")
ax.set_ylabel("Krzanowski similarity")
ax.legend(frameon=False)
plt.show()
plot 03 pca models

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

Gallery generated by Sphinx-Gallery