Build a Dimensionality Reduction Pipeline with PCA for High-Dimensional Data


classical-ml feature-engineering model-evaluation mlops
View full code for this problem

ML Problem & Solution

PCA for High-Dimensional Sensor Data

968 collinear channels, 1,180 scrap events: variance is cheap, predictive variance is not.

⏱ 26 min read 📐 Intermediate 🧩 Classical ML

A plasma etch tool in a semiconductor fab streams 968 sensor channels per wafer: chamber pressure in mTorr, RF forward and reflected power in watts, six gas mass-flow setpoints and six actuals in sccm, electrode temperature in Celsius, endpoint optical emission intensity at 84 wavelengths, valve angles, coil currents, and a long tail of derived rates the tool vendor computes in firmware. Over 14 months across three tools we have 84,320 wafers, and 1,180 of them (1.4%) were scrapped at electrical test six days later. The process engineers want two things from that telemetry: a scrap risk score at the moment the wafer leaves the chamber, and a single number on the operator’s screen that goes red when the tool starts behaving unlike itself.

The obvious move is to standardize all 968 channels and feed them into a regularized logistic regression. That model gets ROC-AUC 0.806, which reads like a success until you look at the PR-AUC of 0.19 and the 5-fold standard deviation of 0.061. With 1,180 positives and 968 features we have roughly 1.2 positive examples per parameter. The coefficient on chamber_pressure_mtorr is positive in three folds and negative in two. Refit on next week’s data and the top ten features by absolute coefficient change almost entirely. Nothing about this model is stable enough to show a process engineer, and no engineer will accept “the model says so” about a 300 dollar wafer.

The reason is collinearity, and it is severe rather than incidental. The 84 optical emission channels are measurements of the same plasma through one window; adjacent wavelengths correlate at 0.97. The six gas flow actuals track their own setpoints at 0.99. Chamber pressure, throttle valve angle, and total flow are linked by the physics of the pump. The design matrix has a condition number of 4.1e6, which means the least-squares problem is numerically close to singular and the fitted coefficients are being asked to resolve differences between channels that carry almost no independent information. Ridge penalties keep the coefficients finite but do not make them meaningful: the penalty spreads weight arbitrarily across a group of near-identical columns, so which channel “wins” is decided by noise.

Think of it as 968 microphones in one small room. Every microphone is recording the same conversation with a slightly different echo. Asking which microphone predicts the argument is the wrong question. There are maybe forty independent things happening in that room, and the job is to recover those forty things first, then ask which of them predicts the argument.

Formally: given a wafer’s 968-channel standardized sensor vector, predict whether that wafer is scrapped at electrical test, optimizing PR-AUC under a 1.4% positive rate, subject to a 2 ms p99 scoring budget at the tool, a model that a process engineer can audit, and weekly retraining on commodity CPU.

Framing the Problem

This is two problems sharing one representation. The supervised half is binary classification with heavy class imbalance. The unsupervised half is multivariate process monitoring: an unlabelled “is this tool normal today” statistic that must fire on failure modes that have never produced a labelled scrap event. PCA is the shared substrate because it is the only step that serves both.

The target is scrapped, defined as a wafer whose electrical test yield falls below the 82% line item that the fab’s disposition rule uses to scrap rather than rework. Two properties of this label matter more than its definition. It arrives with a six day lag, because electrical test happens after the remaining 180 process steps, so at scoring time we never have recent labels. And it is noisy in one direction: a wafer can be scrapped for reasons that have nothing to do with the etch step, which puts an irreducible ceiling on achievable precision. Roughly 30% of scrapped wafers in a hand-audited sample of 200 had root causes attributed to lithography or CMP, not etch.

Constraints, in the order they constrain:

  • Latency: p99 under 2 ms, single-threaded, inside the tool’s equipment interface. This rules out anything that loads a 968-feature model per wafer over the network.
  • Auditability: a process engineer must be able to ask “why did this wafer score high” and get an answer in terms of a small number of named quantities. Not 968 coefficients.
  • Label starvation: 1,180 positives total, and the monitoring half of the problem has zero labels by construction.
  • Non-stationarity: chambers drift between wet cleans. The same physical process produces measurably different sensor distributions on day 1 and day 19 of a clean cycle.
  • No GPU, weekly retrain, under 10 minutes wall clock.

The success metric is PR-AUC on scrap. The guardrail metrics are the false alarm count at the operating point, which must stay under 30 wafers flagged per day out of roughly 6,000 processed, and subspace stability across retrains, measured as the principal angle between this week’s component basis and last week’s. A representation that is accurate but rotates every week is unusable for monitoring, because the control limits on the monitoring statistic would have to be re-derived from scratch every time.

Metric That Matters

At a 1.4% base rate, ROC-AUC 0.806 and ROC-AUC 0.883 look like a modest difference while their `PR-AUC` values differ by 79% (0.19 to 0.34). ROC-AUC integrates over the false-positive-rate axis, where 98.6% of the data lives, so it rewards a model for ranking the vast normal population correctly. Precision-recall integrates over the 1.4% we actually care about.

Out of scope: attributing a component back to a specific physical root cause (that needs the tool’s own fault dictionary), nonlinear manifold learning, and multi-step models that combine etch telemetry with upstream litho data. We reduce one step’s telemetry, well.

Data and Features

The raw table is one row per wafer per chamber pass, 84,320 rows by 968 numeric columns, joined to the electrical test result on wafer_id. Each sensor column is already a within-wafer summary the tool emits at end of process: mean over the main etch step, standard deviation, and slope for the channels where the vendor computes it. Full time-series traces exist but are 40 GB per month and add little for this problem once the summaries are in place.

Channel group Count Typical unit Native variance scale
Optical emission intensity 84 counts 1e6
Chamber pressure and valve 12 mTorr, degrees 1e2
RF power forward and reflected 18 watts 1e3
Gas mass flow setpoint and actual 24 sccm 1e2
Temperatures 16 Celsius 1e0
Vendor-derived rates and ratios 814 mixed 1e-2 to 1e4

That last column is the whole story for why scaling is not optional. PCA finds the directions of maximum variance, and variance is not unit-free. Emission intensity is measured in counts with a variance around 1e6; electrode temperature is in Celsius with a variance around 1. Run PCA on the raw matrix and the first component is 94% emission intensity, not because emission carries the most information but because counts are a bigger number than degrees. Change the emission channel to kilocounts and PC1 becomes something else entirely. Standardizing every column to zero mean and unit variance makes PCA operate on the correlation matrix instead of the covariance matrix, which is the only defensible choice when columns have different units.

# Feature pipeline: drop degenerate channels, standardize, then reduce.
# ColumnTransformer keeps the group structure so we can name components later.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
from sklearn.feature_selection import VarianceThreshold
from sklearn.decomposition import PCA

SENSOR_PREFIXES = ("oes_", "press_", "rf_", "mfc_", "temp_", "drv_")

def sensor_columns(df: pd.DataFrame) -> list[str]:
    """Numeric sensor channels only. Never include ids, timestamps, or the label."""
    return [
        c for c in df.columns
        if c.startswith(SENSOR_PREFIXES) and pd.api.types.is_numeric_dtype(df[c])
    ]

def build_reducer(n_components: int | float = 0.95, seed: int = 17) -> Pipeline:
    """Impute, drop constant channels, standardize, then project. Order matters."""
    return Pipeline([
        ("impute", SimpleImputer(strategy="median")),
        ("drop_constant", VarianceThreshold(threshold=1e-10)),
        ("scale", StandardScaler()),
        ("pca", PCA(n_components=n_components, svd_solver="randomized", random_state=seed)),
    ])

Three details in that pipeline earn their place. SimpleImputer runs first because a channel that drops out during a chamber fault leaves NaNs, and PCA has no NaN handling at all: one missing value propagates to the whole component vector. VarianceThreshold runs before the scaler because 31 of the 968 channels are constant across the whole dataset (unused gas lines reading exactly 0.0), and StandardScaler would divide by a zero standard deviation and emit NaN. And the scaler runs before PCA for the unit reason above.

Common Pitfall

Calling `PCA().fit(X)` on unscaled multi-unit data. The components come out as a ranking of measurement units rather than of process behaviour, and the failure is silent: `explained_variance_ratio_` looks great (PC1 alone at 0.94) precisely because one high-variance unit dominates. High explained variance on unscaled data is a symptom, not a success.

The leakage that makes PCA look better than it is

PCA is fitted from data, so it is a model, and every rule about fitting models on training data only applies to it. The tempting shortcut is to reduce once up front, because it feels like preprocessing:

# WRONG: the component basis has seen the test set's covariance structure.
X_reduced = build_reducer(0.95).fit_transform(X_all)
X_train, X_test, y_train, y_test = train_test_split(X_reduced, y, stratify=y)

On this dataset that shortcut reports PR-AUC 0.41. The honest pipeline reports 0.34. Seven points of the reported performance, a 21% relative overstatement, is the test set’s own covariance leaking into the axes used to describe it. The mechanism is easy to miss because no label is involved: the scaler’s means and standard deviations, and the rotation itself, were estimated from rows the model is later scored on. Put the reducer inside the Pipeline and inside the cross-validation fold, and the leak closes by construction.

There is a second, sneakier leak specific to fab data. Wafers travel in lots of 25, and wafers in a lot share their upstream history, their operator, and their chamber state. A random split puts wafers 1 to 12 of a lot in train and 13 to 25 in test, so the model can score a test wafer by recognising its lot rather than its physics. Splitting by time also matters because chamber state drifts within a wet-clean cycle. We split on both axes:

# Time-ordered split with lot-level grouping. Never a random split on fab data.
from sklearn.model_selection import GroupKFold

def time_split(df: pd.DataFrame, test_frac: float = 0.2):
    """Last test_frac of the timeline is the test set. Lots never straddle the cut."""
    df = df.sort_values("process_ts")
    cut_idx = int(len(df) * (1 - test_frac))
    cut_lot = df.iloc[cut_idx]["lot_id"]
    first_row_of_cut_lot = df.index[df["lot_id"] == cut_lot][0]
    boundary = df.index.get_loc(first_row_of_cut_lot)
    return df.iloc[:boundary], df.iloc[boundary:]

def cv_folds(df: pd.DataFrame, n_splits: int = 5):
    """GroupKFold on lot_id so a lot is never split across train and validation."""
    return GroupKFold(n_splits=n_splits).split(df, groups=df["lot_id"])

Switching from a stratified random split to the grouped time split moved the baseline PR-AUC from 0.27 to 0.19. That 0.08 was lot memorisation, and it would have evaporated in production on the first lot the model had never seen.

Key Insight

PCA is an unsupervised model, not a preprocessing step, and the distinction is entirely about where you fit it. Transforming the full dataset before splitting leaks the test set's covariance structure into the basis and inflated our reported `PR-AUC` by 21% with no label ever crossing the boundary.

Pipeline from 968 raw sensor channels through imputation, variance filtering and standardization into a 62-component basis fitted inside the cross-validation fold, feeding both a scrap classifier and a Hotelling T-squared and Q-residual monitor

The Naive Baseline

Two baselines, because the first one sets the floor and the second one is the model a competent engineer would actually ship first.

The floor is the majority-class predictor: call every wafer good. Accuracy 98.6%, which is the standard demonstration of why accuracy is the wrong metric here. PR-AUC equals the base rate, 0.014, and recall is 0. Any model that cannot beat 0.014 is not a model.

The real baseline is L2 logistic regression on all 968 standardized channels, class-weighted to compensate for the imbalance:

# Baseline: every channel, regularized, honest split. This is what PCA has to beat.
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, roc_auc_score
from sklearn.model_selection import cross_val_score
import numpy as np

baseline = Pipeline([
    ("impute", SimpleImputer(strategy="median")),
    ("drop_constant", VarianceThreshold(threshold=1e-10)),
    ("scale", StandardScaler()),
    ("clf", LogisticRegression(
        penalty="l2", C=1.0, class_weight="balanced",
        solver="lbfgs", max_iter=4000, random_state=17,
    )),
])

scores = cross_val_score(
    baseline, X_train, y_train,
    groups=lot_ids_train, cv=GroupKFold(n_splits=5),
    scoring="average_precision",
)
print(f"baseline PR-AUC {scores.mean():.3f} +/- {scores.std():.3f}")
# baseline PR-AUC 0.190 +/- 0.061

That model is insufficient on three of the four constraints from the framing section, and it is worth being specific about which:

  • Stability: a fold-to-fold PR-AUC standard deviation of 0.061 on a mean of 0.190 is a 32% coefficient of variation. We cannot tell a 0.02 improvement from noise, which means we cannot iterate.
  • Auditability: 937 non-zero coefficients, with the top-ranked features reshuffling every refit because groups of collinear channels trade weight arbitrarily. There is no engineer-facing answer to “why did this wafer score high”.
  • Latency: 8.2 ms p99. The dot product itself is trivial; the cost is assembling, imputing and scaling a 968-element vector per wafer inside the equipment interface, which is Python-level work on a machine that is also running the tool.

It does satisfy the retrain budget at 41 seconds, so speed of training is not the problem. The problem is that we are asking 968 parameters to be estimated from 1,180 positive examples drawn from a design matrix of rank roughly 40.

The Solution

PCA rotates the 968 correlated channels into 968 uncorrelated directions ordered by variance, then we keep the first k and throw the rest away. The analogy from the opening holds: we are replacing 968 microphones with 62 recordings of the independent things happening in the room, and the recordings are constructed so that no two of them capture the same thing twice.

Mechanically, PCA computes the eigendecomposition of the correlation matrix. The eigenvectors (components_, shape 62 by 968) are the new axes, each a weighted combination of all 968 original channels. The eigenvalues (explained_variance_) say how much of the total spread lies along each axis. Because the axes are orthogonal, the resulting 62 features have zero pairwise correlation by construction, which is exactly the pathology the baseline was suffering from. The condition number drops from 4.1e6 to 43.

It beats two plausible alternatives on this data for concrete reasons. Univariate feature selection (keep the top 100 channels by mutual information with scrap) scores PR-AUC 0.22, because selecting channels one at a time keeps 100 columns that are still mutually correlated at 0.97 and discards the combinations that actually matter: the predictive signal here is a ratio between reflected power and pressure, which no single channel expresses. L1 logistic regression scores 0.24 and does produce a sparse model, but it picks one arbitrary representative from each collinear group, so the selected set changes completely between refits and gives the monitoring half of the problem nothing at all.

Choosing the number of components

The default advice is to keep enough components to reach 95% explained variance. On this dataset that rule gives k = 21, because severe collinearity concentrates variance into very few directions. The variance profile:

Components kept Cumulative explained variance Downstream PR-AUC
3 71.0% 0.09
10 87.2% 0.21
21 95.4% 0.28
38 97.4% 0.32
62 98.6% 0.341
121 99.5% 0.31
400 99.97% 0.25

The 95% rule is off by a factor of three here, and it errs in the direction that quietly costs accuracy: stopping at 21 components gives up 6 points of PR-AUC, because components 22 through 62 hold only 3.5% of the variance and a large share of the signal. Going too far the other way is also penalised, with 121 components costing twice the parameters for 3 points less. Explained variance measures how well the components reconstruct the sensor matrix, and nobody downstream wants to reconstruct the sensor matrix. Sweep k against the metric you actually optimize:

# Select k by the downstream metric, not by a variance threshold.
# The reducer is refitted inside every fold, so no fold sees another fold's basis.
from sklearn.model_selection import GridSearchCV

pipe = Pipeline([
    ("impute", SimpleImputer(strategy="median")),
    ("drop_constant", VarianceThreshold(threshold=1e-10)),
    ("scale", StandardScaler()),
    ("pca", PCA(svd_solver="randomized", whiten=True, random_state=17)),
    ("clf", LogisticRegression(
        penalty="l2", C=0.5, class_weight="balanced",
        solver="lbfgs", max_iter=4000, random_state=17,
    )),
])

search = GridSearchCV(
    pipe,
    param_grid={"pca__n_components": [3, 10, 21, 38, 62, 121, 400], "clf__C": [0.1, 0.5, 2.0]},
    scoring="average_precision",
    cv=GroupKFold(n_splits=5),
    n_jobs=-1,
    refit=True,
)
search.fit(X_train, y_train, groups=lot_ids_train)
print(search.best_params_, round(search.best_score_, 3))
# {'clf__C': 0.5, 'pca__n_components': 62} 0.341

svd_solver="randomized" matters at this shape. Full SVD on an 84,320 by 968 matrix takes 94 seconds; randomized SVD with the default 7 power iterations takes 6.1 seconds and agrees with the full decomposition to 1e-9 on the top 62 singular values. Randomized SVD is stochastic, so random_state is not optional if you want a reproducible basis.

The whitening decision

This is the step that separated a mediocre result from a good one, and it is not obvious. After PCA with whiten=False, the component scores inherit the eigenvalue scale: PC1 has a standard deviation of 20.0 while PC62 has a standard deviation of 1.1. An L2 penalty is a single sphere in coefficient space, so it penalizes a unit of coefficient on PC62 exactly as hard as a unit on PC1, while PC62’s smaller scores mean it needs a larger coefficient to contribute the same amount to the logit. The penalty therefore systematically suppresses the low-variance components. On this problem the low-variance components are where the signal is, so the penalty was suppressing precisely the useful directions:

Configuration PR-AUC Largest coefficient sits on
whiten=False, L2 C=0.5 0.27 PC2 (18.3% variance)
whiten=True, L2 C=0.5 0.34 PC7 (2.1% variance)

whiten=True divides each score by the square root of its eigenvalue, so all 62 components arrive at unit variance and the penalty treats them even-handedly. The cost is that whitening amplifies the noise in near-zero-variance directions, which is why truncation has to happen before whitening: at k = 400 the whitened tail components are mostly sensor quantisation noise scaled up to unit variance, and that is a large part of why 400 components scores 0.25. This is also the reason the k sweep has a genuine interior optimum rather than a plateau, since each extra component adds both a little signal and a little amplified noise.

Common Pitfall

Assuming high-variance components are the predictive ones. PC1 holds 41.2% of the variance on this data and has a mutual information with scrap of 0.0004 nats: it is the recipe-A versus recipe-B pressure regime, a real and dominant axis of variation that is completely uninformative about yield. PCA is unsupervised. It optimizes reconstruction, and nothing in its objective mentions the label.

Scree plot of explained variance per component alongside the mutual information of each component with the scrap label, showing that the highest-variance components carry almost no predictive signal while components 7, 19 and 44 carry most of it

Turning components into a monitor

The unsupervised half of the problem is where PCA earns its place over any supervised reduction. Once we have a basis fitted on known-good wafers, every new wafer decomposes into two parts: its projection onto the 62-dimensional model space, and the residual that the model space cannot explain. Each gets a statistic with a real control limit.

Hotelling’s T-squared measures how far inside the model space a wafer sits: the sum over the kept components of the squared whitened score. It answers “is this wafer an extreme but recognisable version of normal operation”. Q, also called squared prediction error, is the squared euclidean norm of the reconstruction residual. It answers “is this wafer doing something the basis has never seen”, and it is the statistic that catches genuinely new failure modes, including ones with no labelled scrap history.

# Hotelling T2 and Q residual from a fitted PCA. The monitoring half of the pipeline.
import numpy as np
from scipy import stats

def t2_and_q(pca, X_scaled: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """T2 = whitened score norm inside the model space. Q = residual norm outside it."""
    scores = pca.transform(X_scaled)                       # (n, k)
    t2 = np.sum(scores ** 2 / pca.explained_variance_, axis=1)
    reconstructed = pca.inverse_transform(scores)          # back to 968 dims
    q = np.sum((X_scaled - reconstructed) ** 2, axis=1)
    return t2, q

def control_limits(t2_train: np.ndarray, q_train: np.ndarray, k: int, alpha: float = 0.01):
    """T2 limit from the F distribution. Q limit empirical: residuals are not Gaussian."""
    n = len(t2_train)
    f_crit = stats.f.ppf(1 - alpha, k, n - k)
    t2_limit = k * (n - 1) * (n + 1) / (n * (n - k)) * f_crit
    q_limit = float(np.quantile(q_train, 1 - alpha))
    return t2_limit, q_limit

The T-squared limit has a closed form because whitened scores on Gaussian-ish data follow an F distribution. The Q limit does not, in practice: residuals are heavy-tailed because real sensor faults are heavy-tailed, and the textbook chi-squared approximation put our limit 2.3 times too low, flagging 4.8% of known-good wafers instead of the nominal 1%. An empirical quantile of the training residuals is less elegant and considerably more accurate.

The auditability constraint also falls out of this decomposition. When Q fires, the per-channel contribution to the residual is just the squared element-wise residual, which ranks the 968 channels by how badly the basis failed to explain them. That gives the engineer three named channels rather than 968 coefficients:

# Per-channel residual contributions: the engineer-facing answer to "why did this fire".
def q_contributions(pca, x_scaled: np.ndarray, channel_names: list[str], top: int = 3):
    """Rank channels by their share of this wafer's reconstruction residual."""
    score = pca.transform(x_scaled.reshape(1, -1))
    residual = (x_scaled - pca.inverse_transform(score).ravel()) ** 2
    order = np.argsort(residual)[::-1][:top]
    total = residual.sum()
    return [(channel_names[i], round(float(residual[i] / total), 3)) for i in order]
Key Insight

The single decision that mattered most was `whiten=True`. Without it the L2 penalty silently suppressed the low-variance components that carried the signal, costing 7 points of `PR-AUC` (0.27 versus 0.34) in a configuration that looks identical in every summary except the metric.

Evaluation and Metrics

Three things need measuring, and only one of them is the classifier’s accuracy.

Ranking quality on a 1.4% positive rate. PR-AUC (equivalently average precision) is the right summary because it is the area under the precision-recall curve, and precision is conditioned on predicted-positive rather than on actual-negative. ROC-AUC answers “how often does a random scrapped wafer outrank a random good wafer”, which is a question whose answer is dominated by the 98.6% of comparisons involving two easy negatives. A model can go from ROC-AUC 0.806 to 0.883 while its precision at a fixed alarm budget triples.

Recall at the alarm budget. The line can review 30 flagged wafers a day out of roughly 6,000 processed, a 0.5% flag rate. That is a fixed operating point set by human capacity, not by a threshold we choose, so the number that decides whether this ships is recall at a 0.5% flag rate. This is the metric the fab manager asks about.

Subspace stability. New for the dimensionality-reduction setting and easy to forget: the basis is refitted weekly, and a basis that rotates freely makes last week’s control limits meaningless. The measurement is the set of principal angles between the subspace spanned by this week’s components and last week’s. Zero degrees means the subspaces are identical even if individual components have swapped order or flipped sign, which is what we want, because subspace identity is what the monitoring statistics depend on.

# Three metrics: ranking, recall at the operating budget, and subspace stability.
import numpy as np
from scipy.linalg import subspace_angles
from sklearn.metrics import average_precision_score, roc_auc_score, classification_report

def recall_at_flag_rate(y_true, y_score, flag_rate: float = 0.005) -> float:
    """Recall when we flag exactly the top flag_rate fraction. The operating point."""
    n_flag = max(1, int(round(len(y_score) * flag_rate)))
    threshold = np.sort(y_score)[::-1][n_flag - 1]
    flagged = y_score >= threshold
    return float((flagged & (y_true == 1)).sum() / max(1, (y_true == 1).sum()))

def subspace_drift_degrees(components_a: np.ndarray, components_b: np.ndarray) -> dict:
    """Principal angles between two component bases. Invariant to order and sign."""
    angles = np.degrees(subspace_angles(components_a.T, components_b.T))
    return {"mean_deg": float(angles.mean()), "max_deg": float(angles.max())}

y_score = search.best_estimator_.predict_proba(X_test)[:, 1]
print(f"PR-AUC          {average_precision_score(y_test, y_score):.3f}")
print(f"ROC-AUC         {roc_auc_score(y_test, y_score):.3f}")
print(f"recall @ 0.5%   {recall_at_flag_rate(y_test.values, y_score):.3f}")
print(classification_report(y_test, y_score >= 0.83, digits=3))

Note what is not on that list: reconstruction error. Mean squared reconstruction error is the quantity PCA minimises, so it is the natural sanity check on the reduction itself, and it is close to useless as a model-selection metric here. Our k = 400 basis has one third the reconstruction error of k = 62 and scores 9 points worse on PR-AUC. Reconstruction error belongs in the monitoring half (that is what Q is) and nowhere near the supervised half.

Metric Majority class All 968 channels + L2 PCA 62 whitened + L2 Change
PR-AUC 0.014 0.190 0.341 +79%
ROC-AUC 0.500 0.806 0.883 +9.6%
Recall at 0.5% flag rate 0.005 0.110 0.270 +145%
5-fold PR-AUC std 0.000 0.061 0.018 3.4x tighter
Scoring p99 0.1 ms 8.2 ms 0.9 ms 9.1x faster
Model parameters 1 937 62 15x smaller
Design matrix condition number n/a 4.1e6 43 95,000x better

The stability row is the one that changes how the team works. A 0.018 fold standard deviation means a 0.02 improvement is now detectable, so hyperparameter work stops being guesswork. The latency row comes from a detail worth stating: at inference we do not run the sklearn Pipeline. We export the scaler means, the scaler scales, and the 62 by 968 component matrix as a single fused float32 array and score with one matrix multiply, which is 60,016 multiply-accumulates and takes 0.02 ms of the 0.9 ms budget. The rest is data assembly.

Metric That Matters

The signal that catches silent degradation is the 95th percentile of `Q` on the last 24 hours of wafers, tracked against its own value at basis-fit time. `PR-AUC` cannot catch it: labels arrive six days late, so by the time the classifier looks wrong, six days of wafers have shipped. Q needs no labels, updates per wafer, and rises whenever the tool moves off the manifold the basis was fitted on.

Common Pitfalls and Failure Modes

Pitfall Why It Happens How to Detect How to Fix
PCA on unscaled multi-unit data Variance is unit-dependent, so the biggest unit wins the first component explained_variance_ratio_[0] above 0.8 with one channel group dominating components_[0] StandardScaler before PCA, always, whenever columns have different units
Fitting the reducer before the split PCA feels like preprocessing, so it gets done once up front Cross-validated score noticeably better than a fresh holdout; here 0.41 versus 0.34 Put the reducer inside the Pipeline so it refits per fold
Choosing k by a variance threshold The 95% rule is the default advice and requires no labels The k sweep against the real metric peaks well away from the variance-selected k GridSearchCV over pca__n_components scored on the downstream metric
L2 penalty on unwhitened scores Component scores differ 20x in scale, so a spherical penalty is not neutral Largest coefficients all sit on the top three components whiten=True, or a StandardScaler between PCA and the classifier
Sign and order flips across retrains Eigenvector sign is arbitrary and near-equal eigenvalues swap order A per-component dashboard inverts overnight with no process change Compare subspaces with principal angles, not components; Procrustes-align new bases to the previous one before serving
Stale basis under process drift The basis is fitted once and the chamber keeps drifting Frozen-basis explained variance on recent wafers falls; Q p95 climbs Refit weekly on a rolling window, version the basis, alert when retained variance drops more than 3 points
PCA on one-hot or sparse columns Sparse binary columns have tiny variance and PCA is dense Components loaded almost entirely on continuous channels Keep categoricals out of the PCA and concatenate them after, or use TruncatedSVD if the matrix is genuinely sparse

The sign-flip problem deserves a note because it produces the most confusing incidents. Nothing in the eigendecomposition fixes the direction of an eigenvector: both v and -v are valid, and randomized SVD will pick differently across runs. If any dashboard or downstream rule reads a single component’s value directly, a refit can invert it and the rule silently reverses. Either depend only on sign-invariant quantities (T-squared, Q, principal angles) or align each new basis to the previous one:

# Align a fresh basis to the previous one so per-component series stay interpretable.
from scipy.linalg import orthogonal_procrustes

def align_basis(new_components: np.ndarray, old_components: np.ndarray) -> np.ndarray:
    """Rotate the new basis into the old basis's frame. Fixes sign flips and swaps."""
    rotation, _ = orthogonal_procrustes(new_components.T, old_components.T)
    return (new_components.T @ rotation).T
Common Pitfall

The mistake we see most on this exact problem is treating a component as if it has a physical meaning. A component is a weighted sum of all 968 channels chosen to maximise variance; it is a statistical axis, not a physical quantity. PC3 on our data loads at 0.31 on reflected RF power and 0.28 on the 703 nanometre emission line, which is suggestive and tempts an interpretation that does not survive the next refit. Use component loadings to generate hypotheses, then confirm with the residual contributions from the original channels.

Key Insight

Every pitfall in that table except the last one is silent. None of them raise an exception, none produce an obviously wrong number, and four of them make your reported metric look better. Dimensionality reduction has an unusually high ratio of quiet failures to loud ones, which is why the fold-refitted pipeline and the k sweep are not optional discipline.

Scaling and Productionizing

A notebook fits one basis on one dataframe. A production reducer is a versioned artifact with a lifecycle, and four things change.

The basis becomes a release. The scaler statistics and the component matrix are the model. They get a version, a fit window, a checksum, and the control limits derived from that exact fit. Serving code loads basis v2026w39 together with its T-squared and Q limits and refuses to mix a v39 basis with v38 limits, because a limit is only valid for the residual distribution of the basis it was computed from. Getting this wrong produces an alarm storm on the first wafer after deploy, which is how most teams learn the rule.

Refit cadence is set by drift, not by the calendar. We refit weekly on a rolling 90-day window, with the trigger being either the weekly schedule or the frozen-basis retained variance dropping below 95.6% (three points under the 98.6% at fit time), whichever comes first. The second condition has fired twice: once after a chamber hardware swap and once when the tool vendor shipped a firmware update that changed how two derived channels were computed.

Inference is a matrix multiply, not a pipeline. The sklearn pipeline is the training artifact. For serving we fuse the scaler and the rotation into one affine transform, since scaling then projecting is (x - mean) / scale @ W.T, which collapses to x @ A.T + b:

# Fuse scaler and PCA into one affine map for serving. 1 matmul, no sklearn at runtime.
def export_affine(pipeline) -> dict:
    """Collapse StandardScaler + PCA(whiten) into a single float32 matrix and offset."""
    scaler = pipeline.named_steps["scale"]
    pca = pipeline.named_steps["pca"]
    w = pca.components_ / np.sqrt(pca.explained_variance_)[:, None]   # whitening folded in
    a = (w / scaler.scale_).astype(np.float32)                        # (k, p_kept)
    b = (-(w @ (scaler.mean_ / scaler.scale_))).astype(np.float32)    # (k,)
    # VarianceThreshold dropped the 31 constant channels before the scaler saw
    # them, so the artifact must carry that mask or it gets 968 and expects 937.
    mask = pipeline.named_steps["drop_constant"].get_support()
    return {
        "A": a, "b": b,
        "kept_columns": np.flatnonzero(mask),
        "k": int(a.shape[0]),
        "n_channels_in": int(mask.size),
    }

def apply_affine(artifact: dict, x_raw: np.ndarray) -> np.ndarray:
    """One gather, one matmul. Agrees with the sklearn pipeline to 5e-4 in float32."""
    x = np.asarray(x_raw, dtype=np.float32).reshape(-1, artifact["n_channels_in"])
    return x[:, artifact["kept_columns"]] @ artifact["A"].T + artifact["b"]

Memory and time are small enough to stop thinking about, and it is worth knowing why:

Training data      84,320 x 968 float32          = 326 MB
Correlation matrix 968 x 968 float64             = 7.5 MB
Randomized SVD     84,320 x 968, k=62, 7 iters   = 6.1 s, 1.4 GB peak
Full SVD           same shape                    = 94 s, 2.9 GB peak
Serving artifact   62 x 968 float32 + 62 offsets = 240 KB
Per-wafer scoring  968 x 62 multiply-accumulate  = 60,016 FLOPs, 0.02 ms
Weekly retrain     fit + k sweep + limits        = 7 min 40 s, 8 vCPU

At ten times this data volume the correlation matrix is unchanged at 7.5 MB, because it depends only on the number of channels, and that is the property that makes PCA scale gracefully in n. If the matrix stops fitting in memory, IncrementalPCA processes it in batches with a bounded footprint and converges to the same basis to within 1e-6 on the top components, at roughly 2.5 times the wall clock.

The monitoring signal for silent degradation is the pair (Q p95 over 24 hours, frozen-basis retained variance). The classifier’s own score distribution is a weaker signal: it can look perfectly stable while the tool has moved, because the classifier only reads 62 dimensions and has no way to report that the other 906 have started misbehaving. Q reads exactly those 906 dimensions, which is why it is the alarm and the score distribution is only a confirmation.

Real World

This is the standard architecture of multivariate statistical process control, and it has been running in chemical plants and fabs since the mid-1990s. Wise and Gallagher's 1996 paper in the Journal of Process Control laid out the PCA plus T-squared plus Q residual pattern used in commercial fault detection and classification systems across the semiconductor industry, and the SEMI E133 standard for predictive equipment models assumes exactly this decomposition. The much older landmark is Turk and Pentland's 1991 Eigenfaces work, which reduced face images to roughly 40 principal components and was the first widely deployed proof that a 40-dimensional linear subspace can carry the signal in a 10,000-dimensional input.

Alternative Approaches

Approach PR-AUC Train / inference cost Interpretability Best fit
PCA 62 whitened + L2 logistic 0.341 6.1 s fit, 0.9 ms p99 Moderate: components are dense but residuals name channels You need one representation for both scoring and unlabelled monitoring
PLS-DA, 24 components 0.372 8.4 s fit, 0.9 ms p99 Moderate, same dense-loading caveat Label-rich supervised problems where monitoring is handled elsewhere
Sparse PCA, 62 components 0.334 4 min 10 s fit, 0.9 ms p99 Good: each component loads on 8 to 15 named channels Interpretability is the binding constraint and you can pay 40x fit cost
Undercomplete autoencoder, 64 units 0.351 22 min on GPU, 2.4 ms p99 Poor: no loadings, no analytic limits Genuinely nonlinear structure and enough data to prove it
LightGBM on raw 968 channels 0.412 3 min 20 s fit, 3.1 ms p99 Good for scoring via SHAP, none for monitoring Maximum ranking accuracy, labels available, no monitoring requirement
Gaussian random projection, 128 dims 0.213 0.3 s fit, 0.9 ms p99 None You need a fast, data-independent dimension cut and can lose accuracy

PLS-DA beating PCA by 3 points is the expected result, not a surprise: PLS finds directions of maximum covariance with the label rather than maximum variance, so it spends its components on what we are predicting. LightGBM beating both by 7 points is also expected, because the scrap boundary has interactions that no linear projection captures.

So what we would actually ship is not what the table’s top row says. LightGBM on the raw channels for the scrap score, and the PCA basis for the monitor, sharing the same scaler. The 3.1 ms p99 exceeds the 2 ms budget, so the gradient boosting model runs asynchronously and writes its score to the lot record rather than gating the wafer, while the PCA path stays inline because it fits in 0.9 ms. We would go PCA-only if the tool interface could not host two artifacts, and PLS-only if the monitoring requirement were dropped. The one configuration we would not ship is the 968-channel logistic regression that we started with, which loses to everything in the table including random projection.

Key Takeaways

  • Standardize or the units decide your components. Variance is not unit-free. On multi-unit sensor data, unscaled PCA returns a ranking of measurement scales and reports a high explained-variance ratio while doing it.
  • PCA is a fitted model, so it goes inside the fold. Reducing before splitting leaked the test covariance into the basis and overstated PR-AUC by 21% with no label crossing the boundary.
  • Choose k by the downstream metric. The 95% variance rule stopped at 21 components and cost 6 points of PR-AUC, because components 22 to 62 hold 3.5% of the variance and a large share of the signal. Explained variance answers a reconstruction question nobody asked.
  • Whiten before you regularize. An L2 penalty on unwhitened scores is not neutral across components and suppressed the low-variance directions that held the signal, at a cost of 7 PR-AUC points.
  • Variance is not predictiveness. PC1 carried 41.2% of the variance and 0.0004 nats of mutual information with the label. The predictive components were 7, 19 and 44.
  • The residual space is the part you cannot get from a supervised model. Q monitors the 906 dimensions the classifier never sees, needs no labels, and is the only signal that fires on a failure mode with no scrap history.
  • Compare subspaces, not components. Eigenvector signs are arbitrary and near-equal eigenvalues swap order, so per-component dashboards invert across refits. Principal angles are invariant to both.
  • Collinearity is the disease; dimensionality is the symptom. A condition number of 4.1e6 was why the baseline was unstable, and dropping it to 43 is why the fold variance fell 3.4x.

The counter-intuitive lesson is that PCA turned out to be the wrong tool for the job we thought we were doing and the right tool for the job we had not framed yet. Gradient boosting on the raw channels beat it by 7 points on scrap ranking, so as a classifier front-end PCA lost. What no supervised model could provide was a labelless statistic over the 906 discarded dimensions, and that Q residual monitor is now what the operators actually look at: it caught a matching-network fault 11 days before the first scrapped wafer from it reached electrical test. The value of the reduction was in what it threw away, not in what it kept.

Frequently Asked Questions

Q: Why not just use PLS if it scores better? A: We would, if scoring were the only requirement. PLS finds directions of maximum covariance with the label, which means it needs labels, and the monitoring half of this problem has none by construction. A PLS basis also has no meaningful residual space for unlabelled anomalies: it discards variance that is irrelevant to the label, so a new failure mode that does not resemble historical scrap lands in the discarded space and is invisible. PCA’s objective being label-free is what makes it work for both halves.

Q: Why not skip reduction and let L1 or tree models handle the 968 features? A: LightGBM does handle them, and better, which is why it is what we ship for scoring. L1 does not: it selects one arbitrary representative from each group of channels correlated at 0.97, so the selected set is unstable across refits and the model still cannot express the ratio features that carry the signal. The reduction is justified by the monitoring requirement and the 2 ms inline budget, not by classification accuracy.

Q: How do I choose the number of components without a downstream label? A: Three options in decreasing order of rigour. Cross-validated reconstruction error, where you hold out entries rather than rows and pick the k that best predicts the held-out values; this is the only genuinely unsupervised method that does not just measure training fit. Parallel analysis, where you compare each eigenvalue to the eigenvalue distribution from permuted data and keep components that exceed the 95th percentile of noise; on our data this gives k = 58, which is close to the 62 the label picked. And the broken-stick or elbow heuristic, which is fast and unreliable and gave k = 14 here.

Q: Why PR-AUC rather than ROC-AUC, concretely? A: At a 1.4% base rate, the false positive rate axis is dominated by the negative class, so a large absolute number of false positives is a tiny change in FPR. Our baseline at the 0.5% flag rate flags 30 wafers and catches 3 of the 27 daily scraps; the PCA model flags the same 30 and catches 7. That is more than double the value delivered, and it shows up as 0.19 to 0.34 in PR-AUC and only 0.806 to 0.883 in ROC-AUC. The metric that changes when the decision changes is the right one.

Q: What breaks first when this goes to production? A: The control limits, on the first refit. A basis and its T-squared and Q limits are a matched pair, because the limits are quantiles of the residual distribution of that basis. Deploying a new basis with the previous limits produces an immediate alarm storm, and the reverse produces silence. Version them as one artifact and have the serving code reject mismatched pairs.

Q: Does PCA help with the class imbalance? A: No, and expecting it to is a common confusion. PCA never sees the label, so it cannot change the positive rate or the difficulty of separating a rare class. It helps with collinearity and dimensionality, which in turn makes the imbalance easier to handle by reducing the number of parameters that have to be estimated from the 1,180 positives. The imbalance itself is handled by class_weight="balanced" and by evaluating at a fixed alarm budget.

Interview Questions

Q: You run PCA on a dataset and PC1 explains 97% of the variance. Is that good? Expected depth: Recognise this as the classic unscaled-data signature and ask about units first. Explain that variance is not scale-invariant, that PCA on raw data is PCA on the covariance matrix while PCA on standardized data is PCA on the correlation matrix, and that the choice between them is a modelling decision, not a default. Note that a genuinely dominant PC1 is possible and diagnosable by checking whether components_[0] loads broadly or concentrates on one high-variance unit group.

Q: Walk me through exactly where PCA goes relative to a train/test split, and why. Expected depth: PCA is fitted, so it belongs inside the fold. Be specific about what leaks: the scaler’s mean and standard deviation, and the rotation itself, both estimated from rows later used for scoring. Explain that the leak does not involve labels, which is why it survives review so often, and quantify that it typically inflates reported metrics by 10 to 25%. Mention Pipeline and GridSearchCV as the mechanical fix, and grouped or time-based splits when rows are not independent.

Q: Your PCA-based classifier scores well but the per-component monitoring dashboard inverts after each weekly refit. What is happening? Expected depth: Eigenvector sign is arbitrary, and components with near-equal eigenvalues can swap order between refits, especially with a randomized solver. The classifier is unaffected because it refits its coefficients in the new frame. Fixes: depend on sign-invariant statistics (T-squared, Q, principal angles), or align bases with orthogonal Procrustes, or pin signs by a deterministic convention such as forcing the largest-magnitude loading positive.

Q: How would you decide between PCA, PLS, and an autoencoder for a high-dimensional sensor problem? Expected depth: Frame it on three axes: label availability, linearity, and whether a residual space is needed. PCA when the representation must serve unlabelled monitoring or when labels are scarce. PLS when labels are plentiful and the only goal is prediction, noting it optimizes covariance with the target and so needs the same leakage discipline. Autoencoders when there is evidence of nonlinear structure and enough data to justify the parameters, with the tradeoff that reconstruction error no longer has analytic control limits and the representation is not inspectable. Mention that the linear methods have deterministic, reproducible bases and the autoencoder does not.

Q: Explain Hotelling’s T-squared and the Q residual, and give a failure mode that one catches and the other misses. Expected depth: T-squared is the sum of squared whitened scores inside the retained subspace, measuring distance from the centre of normal operation along known axes, with an F-distribution limit. Q is the squared norm of the reconstruction residual, measuring distance from the subspace itself. A gradual pressure drift along PC2 raises T-squared and leaves Q flat, because the tool is doing a known thing to an unusual degree. A newly failing RF matching network that decorrelates reflected power from pressure raises Q and can leave T-squared normal, because the correlation structure the basis encodes has broken. Both are needed, and in practice Q is the one that catches novel faults.

View full code for this problem