Abdelhafid Guesmia
All posts
The Full ML Loop: From Training to Monitored Production
MLOpsXGBoostFastAPIPythonProduction

The Full ML Loop: From Training to Monitored Production


The Full ML Loop: From Training to Monitored Production

The gap between a Jupyter notebook and a production ML system is enormous. A model that scores 90% on your local test set is worth nothing if there's no inference endpoint, no monitoring, and no retraining trigger.

Here's the complete loop I run for every ML project.

1. Feature Engineering First

Bad features kill good models. Before any modeling:

  • Profile the data — distributions, missing rates, outliers
  • Engineer domain-specific features, not just raw columns
  • Handle leakage — features computed from future information are the most common mistake

I always build a FeatureStore class that transforms raw data identically in training and inference:

class FeatureStore:
    def __init__(self, scaler=None, encoders=None):
        self.scaler = scaler or StandardScaler()
        self.encoders = encoders or {}

    def fit_transform(self, df: pd.DataFrame) -> np.ndarray:
        df = self._engineer(df)
        return self.scaler.fit_transform(df)

    def transform(self, df: pd.DataFrame) -> np.ndarray:
        df = self._engineer(df)
        return self.scaler.transform(df)

    def _engineer(self, df: pd.DataFrame) -> pd.DataFrame:
        # feature logic here — same in training and inference
        return df

2. Training with Optuna

Grid search is dead. Optuna's TPE sampler finds better hyperparameters in fewer trials:

import optuna
from xgboost import XGBClassifier
from sklearn.model_selection import cross_val_score

def objective(trial):
    params = {
        "n_estimators": trial.suggest_int("n_estimators", 100, 1000),
        "max_depth": trial.suggest_int("max_depth", 3, 10),
        "learning_rate": trial.suggest_float("learning_rate", 1e-4, 0.3, log=True),
        "subsample": trial.suggest_float("subsample", 0.6, 1.0),
        "colsample_bytree": trial.suggest_float("colsample_bytree", 0.6, 1.0),
    }
    model = XGBClassifier(**params, eval_metric="logloss", random_state=42)
    return cross_val_score(model, X_train, y_train, cv=5, scoring="f1").mean()

study = optuna.create_study(direction="maximize")
study.optimize(objective, n_trials=100)

3. Inference with FastAPI

A model file is not a product. Wrap it in a FastAPI endpoint:

from fastapi import FastAPI
from pydantic import BaseModel
import joblib

app = FastAPI()
model = joblib.load("model.pkl")
feature_store = joblib.load("feature_store.pkl")

class PredictRequest(BaseModel):
    features: dict

@app.post("/predict")
def predict(req: PredictRequest):
    df = pd.DataFrame([req.features])
    X = feature_store.transform(df)
    prob = model.predict_proba(X)[0][1]
    return {"probability": round(float(prob), 4), "label": int(prob > 0.5)}

4. Monitoring for Drift

Model accuracy degrades silently without monitoring. I track:

  • Input distribution drift — compare incoming feature distributions to training distributions using PSI (Population Stability Index)
  • Prediction drift — watch the distribution of model scores over time
  • Ground-truth drift — when labels become available (with delay), track actual accuracy

PSI > 0.2 triggers a retraining alert.

5. Automated Retraining

With a good pipeline, retraining is a GitHub Actions workflow:

name: Retrain Model
on:
  schedule:
    - cron: "0 2 * * 1"  # weekly, 2am Monday
  workflow_dispatch:

jobs:
  retrain:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: pip install -r requirements.txt
      - run: python scripts/retrain.py
      - run: python scripts/evaluate.py --threshold 0.85
      - run: python scripts/deploy.py

Summary

The full ML loop:

  1. Feature store — identical logic in training and inference
  2. Optuna for hyperparameter search
  3. FastAPI inference endpoint
  4. Distribution and prediction drift monitoring
  5. Scheduled retraining with quality gates

Notebooks are for exploration. The loop is the product.