(+351) 21 24 10006  ·  info@bconcepts.pt
Carnaxide, Lisbon

How to create a concept drift detector in Machine Learning: step by step

João Barros 02 de December de 2026 5 min read

This tutorial shows how to create a simple concept drift detector in Machine Learning to identify when the relationship between features and the target changes. Detecting concept drift is useful to ensure that models in production continue to perform well and to trigger retraining or automated investigation.

Prerequisites

  • Python 3.8+ and pip
  • Pandas, scikit-learn, scipy, numpy, matplotlib
  • Basic knowledge of classification or regression
  • A historical labeled dataset and recent data (unlabeled or with delayed labels)

Step 1: Understand what concept drift is and choose the approach

Concept drift occurs when the relationship P(target|features) changes over time. Practical strategies include: monitoring performance metrics (if labels are available) or using statistical tests / two-sample models when there are no labels. Here we will implement two approaches: A) performance monitoring when labels are available; B) an unlabeled detector based on a classifier that distinguishes old from recent data (two-sample test).

Step 2: Prepare example data

Create a reference dataset and a current dataset. In the example we use simulated data where the distribution changes in some features.

import numpy as np
import pandas as pd
from sklearn.datasets import make_classification

# dados de referência
X_ref, y_ref = make_classification(n_samples=1000, n_features=5, n_informative=3, random_state=42)
ref = pd.DataFrame(X_ref, columns=[f'f{i}' for i in range(5)])
ref['target'] = y_ref

# dados actuais com drift: alteramos a média de f0 e a importância de f1
X_cur, y_cur = make_classification(n_samples=300, n_features=5, n_informative=3, random_state=7)
X_cur[:, 0] += 1.5  # deslocamento que causa drift
cur = pd.DataFrame(X_cur, columns=[f'f{i}' for i in range(5)])
cur['target'] = y_cur

Step 3: Performance monitoring (when labels are available)

If labels arrive with some latency, monitor metrics like accuracy, ROC AUC or MAE and compare them to a baseline. Use confidence intervals or thresholds defined from historical data.

from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, roc_auc_score

# treinar modelo no ref
clf = RandomForestClassifier(n_estimators=100, random_state=0)
clf.fit(ref.drop('target', axis=1), ref['target'])

# avaliar no conjunto actual (se houver rótulos)
y_pred = clf.predict(cur.drop('target', axis=1))
y_prob = clf.predict_proba(cur.drop('target', axis=1))[:,1]
acc = accuracy_score(cur['target'], y_pred)
auc = roc_auc_score(cur['target'], y_prob)
print('Accuracy:', acc)
print('ROC AUC:', auc)

Common mistakes: comparing metrics without accounting for variance; not using time windows or not adjusting for sample size.

Step 4: Two-sample classifier to detect drift without labels

When there are no labels, an effective technique is to train a classifier to distinguish samples from ref vs cur. If the classifier achieves good separation (high AUC), there is drift in the features.

from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score

# preparar dados rotulados pelo domínio (0=ref, 1=cur)
ref_samples = ref.drop('target', axis=1).copy()
cur_samples = cur.drop('target', axis=1).copy()
ref_samples['domain'] = 0
cur_samples['domain'] = 1

df_dom = pd.concat([ref_samples, cur_samples]).reset_index(drop=True)
X_dom = df_dom.drop('domain', axis=1)
y_dom = df_dom['domain']

X_tr, X_te, y_tr, y_te = train_test_split(X_dom, y_dom, test_size=0.3, stratify=y_dom, random_state=1)
clf_dom = RandomForestClassifier(n_estimators=100, random_state=1)
clf_dom.fit(X_tr, y_tr)
prob = clf_dom.predict_proba(X_te)[:,1]
auc_dom = roc_auc_score(y_te, prob)
print('Domain classifier AUC:', auc_dom)

Interpretation: AUC near 0.5 means no detectable drift; high AUC (e.g., >0.7) indicates drift. Common mistake: using imbalanced samples without stratifying.

Step 5: Detect which features changed (importance or univariate tests)

After confirming drift, identify the responsible features: use the domain classifier's feature importance or statistical tests (Kolmogorov-Smirnov for continuous variables, chi-square for categorical).

import numpy as np
from scipy.stats import ks_2samp

# importância do classificador de domínio
feat_imp = pd.Series(clf_dom.feature_importances_, index=X_dom.columns).sort_values(ascending=False)
print('Feature importances:\n', feat_imp)

# KS test para cada feature contínua
ks_results = {f: ks_2samp(ref[f], cur[f]).pvalue for f in ref.columns if f.startswith('f')}
print('KS p-values:\n', ks_results)

Common mistakes: not correcting for multiple testing (use Bonferroni or FDR) and interpreting p-values without context.

Step 6: Automate alerts and action

Define thresholds for AUC, p-values or metric drops. When exceeded, send an alert and create a routine to collect more labels, retrain or recalibrate the model.

def check_alert(auc_val, auc_thresh=0.7):
    if auc_val >= auc_thresh:
        return True
    return False

if check_alert(auc_dom):
    print('ALERTA: concept drift detectado — activar workflow de re-treino')

Verify the outcome

Confirm that the detector works: 1) Test with data without drift (AUC ≈ 0.5). 2) Test with synthetic data with changes (AUC rises). 3) Check which features appear with higher importance and whether the KS tests show low p-values. Simulate alerts and confirm that the retraining workflow is triggered.

Conclusion

Creating a concept drift detector by combining performance monitoring and a two-sample classifier allows detecting changes in the relationship between features and target even without immediate labels. Next steps: experiment with sliding-window detection, implement drift correction (reweighting, incremental retraining) and integrate alerts into production pipelines. Tip: start with conservative thresholds and adjust based on real data.