Sub topic 13
Detecting multivariate drift with a domain classifier
This chapter assumes you can train and cross-validate a scikit-learn classifier, read a ROC AUC, and run the univariate drift tests from the earlier chapters (KS, chi-square, PSI). You should also know what the reference window and the current window are.
Why one-feature-at-a-time tests are not enough
KS, chi-square and PSI each look at a single column. They can miss a change that lives in the relationships between columns. Suppose income and spend are strongly positively correlated in training, and next month they become negatively correlated. Each column keeps the same marginal distribution, so every univariate test stays quiet. The model, which learned the joint pattern, can still fail badly.
A second problem is volume. With 200 features, you run 200 tests per window. A few small shifts that are individually below threshold may add up to a real change in the input population.
A domain classifier addresses both problems with one test on the whole feature matrix.
The idea
Label every reference row 0 and every current row 1. Train a classifier to predict that label from the features. Then ask how well it does on rows it did not train on.
- If the two windows come from the same distribution, the label cannot be predicted. Held-out ROC AUC stays near 0.5.
- If the joint distribution has shifted, the classifier finds the difference. AUC rises above 0.5.
The AUC is a single, bounded, interpretable drift score. The fitted model also tells you which features separate the windows, so it doubles as a diagnostic.
A case the univariate tests miss
In this example both features keep a standard normal marginal distribution. Only the correlation flips sign.
import numpy as np
from scipy.stats import ks_2samp
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
rng = np.random.default_rng(0)
n = 3000
reference = rng.multivariate_normal([0, 0], [[1, 0.8], [0.8, 1]], size=n)
current = rng.multivariate_normal([0, 0], [[1, -0.8], [-0.8, 1]], size=n)
for j in range(2):
p = ks_2samp(reference[:, j], current[:, j]).pvalue
print(f"feature {j}: KS p-value={p:.3f}")
X = np.vstack([reference, current])
y = np.concatenate([np.zeros(n), np.ones(n)])
clf = RandomForestClassifier(n_estimators=100, random_state=0)
auc = cross_val_score(clf, X, y, cv=5, scoring="roc_auc").mean()
print(f"Domain classifier ROC AUC: {auc:.3f}")The KS p-values behave like those of two samples from the same distribution, because the marginals match. The domain classifier AUC is far above 0.5, because trees can split on the sign of the product of the two features. The model that you monitor may depend on exactly that structure.
Choosing the classifier
The classifier must be able to represent the kinds of differences you care about.
| Classifier | Detects | Notes |
|---|---|---|
| Logistic regression | Shifts in means and linear combinations | Fast and stable. Misses a correlation flip like the one above. |
| Random forest or gradient boosting | Interactions, nonlinear shifts, shifts in rare categories | Good default for tabular data. Needs regularization to avoid overfitting. |
| Neural network | Shifts in images, text embeddings | Use on embeddings of unstructured inputs. Costly for routine checks. |
For tabular monitoring, start with a random forest or gradient boosting model with limited depth or a min_samples_leaf of 20 or more. A weak, regularized model gives a more honest AUC than a model that can memorize rows.
A reusable check that also locates the drift
The function below returns the out-of-fold AUC and a ranking of features. It uses cross_val_predict, so every score comes from a model that did not see that row during training.
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_val_predict
def domain_check(reference, current, feature_names, seed=0):
X = np.vstack([reference, current])
y = np.concatenate([np.zeros(len(reference)), np.ones(len(current))])
clf = RandomForestClassifier(
n_estimators=200, min_samples_leaf=20, random_state=seed, n_jobs=-1
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed)
proba = cross_val_predict(clf, X, y, cv=cv, method="predict_proba")[:, 1]
auc = roc_auc_score(y, proba)
clf.fit(X, y)
ranking = sorted(
zip(feature_names, clf.feature_importances_), key=lambda t: -t[1]
)
return auc, ranking
rng = np.random.default_rng(1)
names = ["age", "income", "tenure"]
reference = rng.normal(0, 1, size=(2000, 3))
current = rng.normal(0, 1, size=(2000, 3))
current[:, 0] += 0.5 # only "age" shifts
auc, ranking = domain_check(reference, current, names)
print(f"AUC={auc:.3f}")
for name, score in ranking:
print(f"{name}: {score:.3f}")age should rank first, with a clearly larger importance than the other two. Importances from a model fitted on all rows are a quick guide. For a more reliable ranking, use sklearn.inspection.permutation_importance on held-out rows.
Reading the AUC
There is no universal cutoff. These ranges are a starting point that you should calibrate on your own data.
| Held-out AUC | Rough reading |
|---|---|
| 0.50 to 0.55 | Windows are indistinguishable or nearly so |
| 0.55 to 0.70 | Detectable shift. Check the top features |
| 0.70 to 0.90 | Clear shift. Likely to matter for the model if the top features are important to it |
| Above 0.90 | Very different populations, or a pipeline bug |
To set a threshold for your system, compute the AUC for pairs of windows that you know are healthy, for example two adjacent weeks from a stable period. The spread of those values is your noise floor. Alert only well above it.
With very large windows, even a tiny shift gives a statistically detectable AUC. With small windows, the AUC is noisy and can sit above 0.5 by chance. A permutation baseline helps. Shuffle the labels, rerun the check a few dozen times, and see how high the shuffled AUCs go.
Gotchas
Leaky columns make the check useless
If any column identifies the window, the classifier will reach an AUC near 1.0 and tell you nothing. Typical culprits are timestamps, row IDs, batch IDs, model version fields, and features derived from the date, such as "days since signup" when the reference was frozen earlier.
Unbalanced windows
If the reference has 100,000 rows and the current window has 500, accuracy-style behavior is dominated by one class. AUC is less sensitive to imbalance than accuracy, but the fit is still worse. Subsample the larger window to a similar size, or use class_weight="balanced".
Train and score on different rows
Never score the classifier on its training rows. A random forest fits training data almost perfectly, so the in-sample AUC is close to 1.0 regardless of drift. Use cross-validation as above, or a held-out split.
Correlated rows
If the same user or device appears many times, random folds put the same entity in both train and test sets. The classifier then recognizes entities rather than distribution shifts. Use GroupKFold with an entity ID when rows are not independent.
Not every detected shift matters
The domain classifier says that the inputs differ. It does not say that the model got worse. A shift in a feature the model ignores is harmless. Combine the AUC and feature ranking with the importance of those features to the production model, and with performance metrics when labels arrive. The chapter on drift versus performance covers that decision.
Cost
Training a model on every window costs more than a KS test. Run it daily or weekly rather than per request. Use univariate tests for fast, per-feature alerts and the domain classifier as a periodic, whole-dataset check.
Putting it into practice
- Build the reference matrix from the data the model was trained or validated on, or from a known healthy period.
- Drop identifiers, timestamps and any column derived from them.
- Subsample both windows to similar sizes, with a few thousand rows each as a practical minimum.
- Run
domain_checkon a schedule and log the AUC as a time series. - Establish a noise floor from healthy window pairs and alert above it, with a hysteresis rule such as two consecutive breaches.
- On an alert, review the top features, then compare their univariate distributions to see what changed.
Exercise
Your domain classifier reports a held-out AUC of 0.99 on the first run against last month's reference. The univariate KS tests on all 40 features show only small shifts. What is the most likely cause, and what do you check first?
Show answer
A leaky column that identifies the window, such as a timestamp, row ID, batch ID or a date-derived feature, is the most likely cause. Look at the top-ranked feature in the importance ranking, drop any identifier or time-derived columns, and rerun. If the AUC stays high after that, investigate a joint shift such as a changed correlation between features.
Exercise
Why is it wrong to compute the domain classifier AUC on the same rows used to train it, and how do you avoid the problem?
Show answer
A flexible model such as a random forest can memorize its training rows, so the in-sample AUC is close to 1.0 even when the two windows come from the same distribution. Use out-of-fold predictions from cross-validation, as cross_val_predict does, or score on a held-out split. If rows come from repeated entities, use GroupKFold so one entity never appears in both train and test folds.