Model Stacking for Fraud Detection: Long-Term vs. Short-Term Models
From the publisher’s feed, collected in the ZeroLabs newsroom.
Fraud in digital commerce evolves quickly. Some patterns persist for years, while new tactics emerge every few weeks. Relying on a single machine learning model is often not enough.One powerful approach is model stacking — combining models trained on different time horizons and with different strengths. In this article, I’ll walk through how stacking long-term and short-term fraud models works, why it’s effective, and three practical ways to implement it. A runnable notebook and a diagram are linked at the end.Long-Term vs. Short-Term ModelsLong-Term ModelTrained on 1.5–2 years of historical dataCaptures established fraud patternsRetrained less often (e.g., quarterly/bi-annually)Pros: stable, robust coverage; Cons: slower to adaptShort-Term ModelTrained on 3–6 months of recent dataCaptures emerging/seasonal patternsRetrained frequently (e.g., monthly)Pros: agile to new attacks; Cons: less historical contextWhy stack them? You get the stability of the long-term model and the agility of the short-term model in one decisioning layer.Advantages of StackingComprehensive coverage of both established and emerging fraud.Faster ramp-up — adapt quickly without retraining big models.Efficiency — reduce cost by training large models less often.Better decisioning — improve capture while controlling false positives.Methods of Stacking1) Recommendation StackingEach model outputs a recommendation:Accept → 0Manual Review → 1Reject → 2Sum the two model recommendations to get a stacked score (0–4), then apply thresholds for final action.When to use: operational simplicity; easy to explain to risk ops.2) Average-Score StackingStandardize each model’s probability to a 0–1000 score.Take the average and apply thresholds for Accept/Review/Reject.When to use: one model excels at high-dollar fraud while the other excels at low-dollar fraud — you want both strengths.3) Meta-Model StackingUse the two model outputs (probabilities or logits) as features.Train a small meta-model (e.g., logistic regression, gradient boosting) to produce the final decision.When to use: you can support a small extra model and want the best lift.Closing ThoughtFraudsters evolve constantly, and relying on a single model is like locking just one door in a house with many entry points. By stacking long-term and short-term models, we create a layered defense that is both stable and adaptive.In practice, I’ve seen stacking approaches significantly improve fraud capture rates while reducing false positives — protecting businesses and enhancing customer experience.Try It Yourself (Notebook)I’ve published a notebook that simulates an imbalanced, time-ordered dataset; trains a long-term and short-term model; and demonstrates all three stacking methods:Notebook:#%% md# Model Stacking for Fraud Detection: Long‑Term vs. Short‑Term ModelsThis notebook simulates two fraud models trained on different time horizons and shows three stacking strategies:1. **Recommendation stacking** (Accept/Review/Reject → score 0–4) 2. **Average‑score stacking** (standardize to 0–1000, then average) 3. **Meta‑model stacking** (use model outputs as features for a logistic regression)> **Note:** This is a synthetic, educational demo. Replace the data generation with your dataset and keep your company’s confidential details out of any public derivative.#%%# If needed, install packages (uncomment when running locally)# !pip install xgboost scikit-learn pandas numpy matplotlib#%%import numpy as np, pandas as pdfrom sklearn.datasets import make_classificationfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import roc_auc_score, precision_recall_fscore_supportfrom sklearn.linear_model import LogisticRegressionfrom xgboost import XGBClassifier # swap for LightGBM if preferredRANDOM_STATE = 42np.random.seed(RANDOM_STATE)#%% md## 1) Simulate an imbalanced, time‑ordered fraud dataset#%%# 50k samples, highly imbalanced (0.8% fraud)X, y = make_classification( n_samples=50000, n_features=40, n_informative=15, n_redundant=5, weights=[0.992, 0.008], flip_y=0.001, random_state=RANDOM_STATE)df = pd.DataFrame(X)df["label"] = ydf["t"] = np.arange(len(df)) # chronological index# Train/test split by time (not random shuffle)cut = int(0.8 * len(df))train_df = df.iloc[:cut].copy()test_df = df.iloc[cut:].copy()# Within train, define long-term (older ~18 months) vs short-term (recent ~3-6 months) windowslt_cut = int(0.85 * len(train_df))long_train = train_df.iloc[:lt_cut]short_train = train_df.iloc[lt_cut:]X_long, y_long = long_train.drop(columns=["label","t"]).values, long_train["label"].valuesX_short, y_short = short_train.drop(columns=["label","t"]).values, short_train["label"].valuesX_test, y_test = test_df.drop(columns=["label","t"]).values, test_df["label"].valuesX_long.shape, X_short.shape, X_test.shape#%% md## 2) Train long‑term & short‑term models#%%# Long‑term model: larger window, retrained less frequentlylong_model = XGBClassifier( n_estimators=400, max_depth=6, learning_rate=0.05, subsample=0.9, colsample_bytree=0.9, reg_lambda=1.0, random_state=RANDOM_STATE, n_jobs=-1, scale_pos_weight=(1/0.008 - 1))long_model.fit(X_long, y_long)# Short‑term model: recent window, adapts fastershort_model = XGBClassifier( n_estimators=250, max_depth=5, learning_rate=0.07, subsample=0.9, colsample_bytree=0.9, reg_lambda=1.0, random_state=RANDOM_STATE+1, n_jobs=-1, scale_pos_weight=(1/0.008 - 1))short_model.fit(X_short, y_short)# Predictions on testp_long = long_model.predict_proba(X_test)[:, 1]p_short = short_model.predict_proba(X_test)[:, 1]#%% md## 3) Baseline metrics#%%def summarize(y_true, scores, name, thr=0.5): auc = roc_auc_score(y_true, scores) y_pred = (scores >= thr).astype(int) p, r, f1, _ = precision_recall_fscore_support(y_true, y_pred, average="binary", zero_division=0) return {"model": name, "AUC": auc, "precision": p, "recall": r, "f1": f1}metrics = []metrics.append(summarize(y_test, p_long, "Long‑term"))metrics.append(summarize(y_test, p_short, "Short‑term"))pd.DataFrame(metrics).round(4)#%% md## 4) Stacking methods#%%# (A) Recommendation stackingdef label_from_prob(p, t_accept=0.2, t_reject=0.8): # accept(0), 0.2–0.8 -> review(1), >=0.8 -> reject(2) return np.where(p >= t_reject, 2, np.where(p lt_rec = label_from_prob(p_long)st_rec = label_from_prob(p_short)stack_score_rec = lt_rec + st_rec # 0..4# Convert back to a score for AUC (scale 0..1) and a binary decision for P/R/F1auc_rec = roc_auc_score(y_test, stack_score_rec / 4.0)y_pred_rec = (stack_score_rec >= 3).astype(int) # threshold examplep, r, f1, _ = precision_recall_fscore_support(y_test, y_pred_rec, average="binary", zero_division=0)rec_metrics = {"model": "Stacking: recommendation", "AUC": auc_rec, "precision": p, "recall": r, "f1": f1}# (B) Average‑score stackings_long = (p_long * 1000.0)s_short = (p_short * 1000.0)s_avg = (s_long + s_short) / 2.0auc_avg = roc_auc_score(y_test, s_avg / 1000.0)y_pred_avg = (s_avg >= 700).astype(int) # threshold examplep, r, f1, _ = precision_recall_fscore_support(y_test, y_pred_avg, average="binary", zero_division=0)avg_metrics = {"model": "Stacking: average score", "AUC": auc_avg, "precision": p, "recall": r, "f1": f1}# (C) Meta‑model stackingmeta_X = np.c_[p_long, p_short]X_tr, X_va, y_tr, y_va = train_test_split(meta_X, y_test, test_size=0.5, random_state=RANDOM_STATE)meta = LogisticRegression(max_iter=200)meta.fit(X_tr, y_tr)p_meta = meta.predict_proba(meta_X)[:, 1]meta_metrics = summarize(y_test, p_meta, "Stacking: meta‑model", thr=0.5)pd.DataFrame([rec_metrics, avg_metrics, meta_metrics]).round(4)#%% md## 5) Compare all approaches#%%import pandas as pdall_metrics = pd.DataFrame([ summarize(y_test, p_long, "Long‑term"), summarize(y_test, p_short, "Short‑term"), rec_metrics, avg_metrics, meta_metrics]).round(4)all_metrics.sort_values("AUC", ascending=False).reset_index(drop=True)Follow me here and on LinkedIn if you’d like to learn more about building ML for fraud prevention in the real world.Model Stacking for Fraud Detection: Long-Term vs. Short-Term Models was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.