Note
Go to the end to download the full example code or to run this example in your browser via Binder.
PCA segmentation with the T² and Q statistics#
Abonyi et al. (2005) segment a multivariate series so that the PCA model of every segment describes its samples well: the cost of a segment is the sum of the reconstruction errors (\(Q\)) or of the Hotelling \(T^2\) values of its samples. Bankó (2015, Eq. 3.1) uses the same costs with bottom-up search for correlation-based warping. \(Q\) reacts to changes of the correlation structure, \(T^2\) to changes of the variation within the model; their sum is the full squared reconstruction distance.
import matplotlib.pyplot as plt
import pandas as pd
import mvtsa as mv
from mvtsa import segmentation as sg
from mvtsa.evaluation import evaluate_segmentation
X, cps, _ = mv.datasets.make_correlation_switching(
n_segments=5, length=120, n_variables=4, random_state=2
)
Q, T² and their sum#
rows = []
for stat in ("Q", "T2", "both"):
seg = sg.PCASegmenter(
n_segments=5, n_components=1, statistic=stat
).segment(X)
rows.append(
{
"statistic": stat,
**evaluate_segmentation(cps, seg, len(X), margin=6),
}
)
print(pd.DataFrame(rows)[["statistic", "f1", "covering", "hausdorff"]])
statistic f1 covering hausdorff
0 Q 1.0 1.000000 0.0
1 T2 0.0 0.198095 440.0
2 both 0.0 0.554853 90.0
The variances of the variables are the same in every segment, so the \(T^2\) statistic – the variation inside the model – has nothing to react to; the changes live entirely in the residual space.
The loadings of the segment models#
The first principal direction of every segment: the correlation structure that defines the segments.
seg = sg.PCASegmenter(n_segments=5, n_components=1).segment(X)
mv.viz.plot_segmentation(X, seg, truth=cps)
mv.viz.plot_segment_loadings(X, seg)
<Axes: xlabel='segment (loadings of PC1)'>
Parameter study: the number of principal components#
One latent variable generates the data. With more components the \(Q\) statistic sees less and less of the structure.
for q in (1, 2, 3):
s = sg.PCASegmenter(n_segments=5, n_components=q).segment(X)
print(
f"{q} components: covering {evaluate_segmentation(cps, s, len(X))['covering']:.3f}"
)
plt.show()
1 components: covering 1.000
2 components: covering 1.000
3 components: covering 0.717
Total running time of the script: (0 minutes 0.135 seconds)

