Week 08 · Dimensionality reduction and anomaly detection
Detect departures from a training subspace.
← Week 7 · Subject contents · Week 9 →
Detect departures from a training subspace.
Work through the problem
Fit PCA to centered training data. Let U contain the retained orthonormal directions. The reconstruction of row x is μ+UUᵀ(x−μ) in column-vector notation. Squared residual ‖x−x̂‖² scores displacement out of that subspace.
For training rows near y=x, moving from (1,1) to (3,3) stays along the learned line. Moving to (1,−1) is perpendicular. The latter has squared distance 2 to the line even though its coordinates are smaller. A residual score may miss large changes along a retained direction, so compare it with a score that tracks those too.
Run the Python lab
import numpy as np
from sklearn.decomposition import PCA
train = np.array([[-2,-2],[-1,-1],[0,0],[1,1],[2,2]])
test = np.array([[1,1],[3,3],[1,-1]])
model = PCA(n_components=1).fit(train)
components = model.transform(test)
residual = ((test-model.inverse_transform(components))**2).sum(1)
print("Residual score:", residual.round(2))
print("Magnitude along the line:", abs(components[:,0]).round(2))
assert np.allclose(residual,[0,0,2])
Output from the lab
Residual score: [0. 0. 2.]
Magnitude along the line: [1.41 4.24 0. ]
Practice
- Why fit PCA without the suspect batch?
Check your reasoning
- If the shift is large, the suspected observations can rotate the fitted subspace toward the very anomaly you want to measure.