Design an end-to-end machine learning pipeline from data to deployment. Outputs data preparation, training, evaluation, deployment, and monitoring steps.
Design an end-to-end machine learning pipeline from data to deployment. Outputs data preparation, training, evaluation, deployment, and monitoring steps.
argument-hint
["ML problem type","data sources","model requirements"]
allowed-tools
Read, Write, Bash
Machine Learning Pipeline
Design a production ML pipeline that takes raw data, trains models, evaluates performance, deploys to production, and monitors for drift. Not just "train a model" — versioning, experiment tracking, A/B testing, retraining, and observability.
Process
Define ML problem. Classification, regression, ranking, recommendation — what's the task?
Prepare data pipeline. Extract, clean, feature engineering, train/val/test split.
import pandas as pd
from sqlalchemy import create_engine
defextract_training_data(start_date, end_date):
"""Extract user data for training"""
engine = create_engine('postgresql://localhost/analytics')
query = f"""
SELECT
u.user_id,
u.signup_date,
u.country,
u.subscription_tier,
COUNT(DISTINCT o.order_id) as order_count,
SUM(o.amount) as total_revenue,
MAX(o.order_date) as last_order_date,
CASE WHEN u.churned_at IS NOT NULL THEN 1 ELSE 0 END as churned
FROM users u
LEFT JOIN orders o ON u.user_id = o.user_id
WHERE u.signup_date BETWEEN '{start_date}' AND '{end_date}'
GROUP BY u.user_id, u.signup_date, u.country, u.subscription_tier, u.churned_at
"""
df = pd.read_sql(query, engine)
return df
from airflow import DAG
from airflow.operators.python import PythonOperator
defcheck_performance_degradation():
"""Check if model performance dropped below threshold"""# Get recent predictions vs actuals
recent_auc = calculate_recent_auc()
training_auc = 0.85# AUC from trainingif recent_auc < training_auc * 0.9: # 10% degradation
trigger_retraining()
deftrigger_retraining():
"""Initiate full pipeline retrain"""from airflow.api.common.experimental.trigger_dag import trigger_dag
trigger_dag('ml_training_pipeline')
# DAG to check performance daily
dag = DAG(
'model_monitoring',
schedule_interval='@daily',
catchup=False
)
check_perf = PythonOperator(
task_id='check_performance',
python_callable=check_performance_degradation,
dag=dag
)
Best Practices
Version Everything
# Code version
git_commit = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode().strip()
mlflow.log_param("git_commit", git_commit)
# Data version
data_hash = hashlib.md5(df.to_csv().encode()).hexdigest()
mlflow.log_param("data_hash", data_hash)
# Model version
mlflow.log_param("model_version", "v1.2.0")
Reproducibility
import random
import numpy as np
# Set seeds
SEED = 42
random.seed(SEED)
np.random.seed(SEED)
mlflow.log_param("random_seed", SEED)
Model Cards
# Churn Prediction Model Card## Model Details-**Model Type:** XGBoost Classifier
-**Version:** 1.2.0
-**Training Date:** 2024-01-15
-**Author:** Data Science Team
## Intended Use-**Primary Use:** Predict customer churn for proactive retention
-**Out of Scope:** Not for legal decisions, hiring, credit scoring
## Training Data-**Source:** User behavior data (2023-01-01 to 2024-01-01)
-**Size:** 50,000 users
-**Positive Class:** 15% (churn rate)
## Performance-**AUC:** 0.85
-**Precision:** 0.72
-**Recall:** 0.68
## Limitations- Model trained on US users only
- May not generalize to international markets
- Performance degrades for users with < 30 days history
## Ethical Considerations- No sensitive attributes (race, gender) used in training
- Regular bias audits for fair treatment across user segments
Rules
All experiments must be tracked with MLflow, Weights & Biases, or equivalent — no "training on laptop without logging."
Train/validation/test splits must be time-based for temporal data to prevent data leakage.
Model evaluation requires multiple metrics (accuracy/precision/recall/AUC), not just one.
Production models must have monitoring for data drift and performance degradation.
Retaining triggers automatically when performance drops > 10% from training baseline.
Feature engineering logic must be versioned and reproducible — same code for training and inference.
Models deployed to production must have health check endpoints.
Prediction latency must be logged — p95 latency > 500ms triggers investigation.
All code, data versions, hyperparameters must be logged for reproducibility.
Model cards documenting intended use, limitations, and biases are mandatory for production models.