Design a Tabular Classification Pipeline from Raw CSV to Deployment
Machine LearningModel answerLast updated
Build a complete ML classification system: data splits, preprocessing, model training and tuning, evaluation metrics, serialization, and a batch inference entry point.
Tabular Classification Pipeline
You are given a CSV file containing labeled tabular data. Your task is to build a complete, production-minded classification pipeline from raw data to batch inference.
Your implementation must cover each of the following stages:
- Data loading — read the CSV and drop rows where the target label is missing.
- Stratified splits — divide the data into train, validation, and test sets while preserving class proportions in each split. Cross-validation runs only on the training portion; the test set is used exactly once.
- Preprocessing — handle missing values in numeric and categorical columns separately. Scale numeric features. Encode categorical features in a way that gracefully handles categories not seen during training.
- Model training — train at least two models: a simple linear baseline and a stronger tree-based or neural model.
- Hyperparameter tuning — use cross-validation to search over key hyperparameters for each model.
- Evaluation — report accuracy, precision, recall, and ROC-AUC on both the validation and test sets. Justify your choice of primary metric.
- Persistence — serialize the fully fitted pipeline (preprocessing + model) into a single artifact.
- Batch inference — implement a
predict(input_csv_path, output_csv_path)function that loads the saved artifact, validates the input schema, runs prediction, and writes predictions and class probabilities to a CSV.
If you include a neural network, show a correct training loop: optimizer initialization, forward pass, loss computation, backward pass, and an explicit optimizer step.
After presenting your code, briefly address:
- How you would detect and prevent data leakage.
- How you would productionize this pipeline (monitoring, retraining triggers, schema validation).
- How your approach changes if the classes are severely imbalanced.
Assume the dataset fits in memory. The target column name and any ID column (pass-through, not a feature) are supplied as arguments.
Hints
Hint 1
Fit all preprocessing statistics — imputer means, scaler parameters, encoder vocabulary — on training data only. Wrapping them in a single scikit-learn Pipeline with ColumnTransformer enforces this automatically inside every cross-validation fold and makes the artifact a single serializable object.
Hint 2
When choosing a primary metric, ask whether class imbalance is present. Accuracy can be misleading on skewed datasets; ROC-AUC or PR-AUC are more informative and threshold-independent, making them safer choices for hyperparameter selection.
Hint 3
For batch inference, enforce column order and check for missing features before calling predict. Silently dropping or reordering columns is a common source of silent prediction errors in production.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach before writing a single line
State your plan out loud: clarify the target, class count, and data size, then sketch the five components — splits, preprocessor, model zoo, evaluation, and inference — before coding. A 150-line implementation with a clear design rationale is stronger than 300 lines without one.
Key clarifying questions (roughly one minute)
- Binary or multiclass? This changes how ROC-AUC and precision/recall are averaged.
- How imbalanced is the target? If one class is under 10% of the data, accuracy is nearly useless as a selection criterion.
- Is there an ID column? It must be passed through to inference output but excluded from features entirely.
- Data volume? If it exceeds RAM, pandas + scikit-learn must be swapped for chunked or distributed processing.
Design decisions and trade-offs
Splits: 70 / 15 / 15 with double stratification. Call train_test_split twice, both times with stratify=y. The first call carves off 15% as a held-out test set. The second splits the remainder into train (≈70%) and validation (≈15%). Cross-validation runs inside the training fold only. The validation set selects the winning model family. The test set produces a single unbiased estimate at the very end.
Common mistake: running cross-validation across the full dataset and then reporting test metrics. This contaminates the test set and produces optimistically biased numbers.
Single Pipeline wrapping ColumnTransformer and the classifier. This is the most important structural decision. It guarantees that imputation statistics and scaling parameters are recomputed from scratch inside every CV fold, eliminating leakage. It also means serialization is trivial: one joblib.dump call captures the full inference graph.
Preprocessing choices:
- Numeric: median impute (robust to outliers) plus a binary missing-indicator column, then
StandardScaler. The indicator lets the model learn whether missingness itself is informative. - Categorical: constant impute with a sentinel string like
"__missing__", thenOneHotEncoder(handle_unknown="ignore"). Thehandle_unknownsetting silently zeroes out unseen categories at inference rather than crashing — essential for production.
Models:
- Baseline:
LogisticRegressionwithclass_weight="balanced"and tunableC. Fast, interpretable, sets a floor. - Stronger model:
HistGradientBoostingClassifier. It is fast on tabular data, handles moderate imbalance well, and exposes meaningful knobs (learning_rate,max_leaf_nodes,l2_regularization). - Alternative stronger model: a small two-layer MLP via PyTorch or scikit-learn's
MLPClassifierif a neural path is required. The training loop must explicitly calloptimizer.zero_grad(),loss.backward(), andoptimizer.step()in that order. Forgettingzero_grad()accumulates gradients across batches and produces incorrect updates.
Hyperparameter tuning: GridSearchCV or RandomizedSearchCV with StratifiedKFold(5) and scoring="roc_auc" (or "roc_auc_ovr" for multiclass). Tuning on AUC avoids threshold sensitivity.
Full implementation
import json, joblib, numpy as np, pandas as pd, sklearn
from sklearn.model_selection import (train_test_split, StratifiedKFold,
GridSearchCV)
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import (accuracy_score, precision_score,
recall_score, roc_auc_score)
SEED = 42
def build_preprocessor(X):
num_cols = X.select_dtypes(include="number").columns.tolist()
cat_cols = [c for c in X.columns if c not in num_cols]
num_pipe = Pipeline([
("imp", SimpleImputer(strategy="median", add_indicator=True)),
("sc", StandardScaler()),
])
cat_pipe = Pipeline([
("imp", SimpleImputer(strategy="constant", fill_value="__missing__")),
("oh", OneHotEncoder(handle_unknown="ignore", sparse_output=False)),
])
return ColumnTransformer([
("num", num_pipe, num_cols),
("cat", cat_pipe, cat_cols),
])
def evaluate(model, X, y):
pred = model.predict(X)
proba = model.predict_proba(X)
binary = proba.shape[1] == 2
avg = "binary" if binary else "macro"
kw = {"pos_label": model.classes_[1]} if binary else {}
auc = (roc_auc_score(y, proba[:, 1])
if binary else
roc_auc_score(y, proba, multi_class="ovr",
labels=model.classes_))
return {
"accuracy": round(accuracy_score(y, pred), 4),
"precision": round(precision_score(y, pred, average=avg,
zero_division=0, **kw), 4),
"recall": round(recall_score(y, pred, average=avg,
zero_division=0, **kw), 4),
"roc_auc": round(auc, 4),
}
def train(csv_path, target, model_path="model.joblib", id_col=None):
df = pd.read_csv(csv_path).dropna(subset=[target])
y = df[target]
X = df.drop(columns=[target] + ([id_col] if id_col else []))
# Double-stratified split: carve test first, then train/val
X_tmp, X_te, y_tmp, y_te = train_test_split(
X, y, test_size=0.15, stratify=y, random_state=SEED)
X_tr, X_va, y_tr, y_va = train_test_split(
X_tmp, y_tmp, test_size=0.15/0.85,
stratify=y_tmp, random_state=SEED)
binary = y.nunique() == 2
scoring = "roc_auc" if binary else "roc_auc_ovr"
cv = StratifiedKFold(5, shuffle=True, random_state=SEED)
candidates = {
"logreg": (
LogisticRegression(max_iter=2000, class_weight="balanced"),
{"clf__C": [0.01, 0.1, 1, 10]},
),
"hgb": (
HistGradientBoostingClassifier(random_state=SEED),
{
"clf__learning_rate": [0.05, 0.1],
"clf__max_leaf_nodes": [15, 31],
"clf__l2_regularization":[0.0, 1.0],
},
),
}
results, best_name, best_auc, best_model = {}, None, -1, None
for name, (clf, grid) in candidates.items():
pipe = Pipeline([("prep", build_preprocessor(X_tr)), ("clf", clf)])
gs = GridSearchCV(pipe, grid, cv=cv, scoring=scoring,
n_jobs=-1).fit(X_tr, y_tr)
val = evaluate(gs.best_estimator_, X_va, y_va)
results[name] = {
"best_params": gs.best_params_,
"cv_auc": round(gs.best_score_, 4),
"val": val,
}
if val["roc_auc"] > best_auc:
best_name, best_auc, best_model = name, val["roc_auc"], gs.best_estimator_
# Test set touched exactly once, after model family is chosen
results[best_name]["test"] = evaluate(best_model, X_te, y_te)
artifact = {
"pipeline": best_model,
"features": X.columns.tolist(),
"id_col": id_col,
"model_name": best_name,
"metrics": results,
"sklearn_version": sklearn.__version__,
}
joblib.dump(artifact, model_path)
print(json.dumps(results, indent=2, default=str))
return artifact
def predict(input_csv_path, output_csv_path, model_path="model.joblib"):
art = joblib.load(model_path)
df = pd.read_csv(input_csv_path)
missing = set(art["features"]) - set(df.columns)
if missing:
raise ValueError(f"Input is missing columns: {sorted(missing)}")
X = df[art["features"]] # enforce training column order
pipe = art["pipeline"]
proba = pipe.predict_proba(X)
preds = pipe.classes_[proba.argmax(axis=1)]
out = pd.DataFrame({"prediction": preds})
for i, cls in enumerate(pipe.classes_):
out[f"proba_{cls}"] = proba[:, i]
if art["id_col"] and art["id_col"] in df.columns:
out.insert(0, art["id_col"], df[art["id_col"]].values)
out.to_csv(output_csv_path, index=False)
print(f"Wrote {len(out)} rows to {output_csv_path}")
Production considerations
Monitoring. Track input feature distributions (mean, missing rate, category frequencies) and compare them against training baselines. A significant drift triggers a retraining alert. Track prediction distribution shift too — a sudden change in the proportion of predicted positives often reveals upstream data issues before labels arrive.
Schema validation. The predict function above raises an error on missing columns. In a service context, wrap this in a Pydantic model or Great Expectations suite and return a structured error response rather than crashing the worker.
Retraining. Set a performance threshold on a rolling window of labeled production examples. When ROC-AUC on recent data drops below that threshold, trigger a retrain on the expanded dataset using the same pipeline code with pinned library versions (captured in the artifact).
Severe class imbalance. Switch the primary metric to PR-AUC, add class_weight="balanced" to logistic regression (already done above), and consider scale_pos_weight for gradient boosting. Consider oversampling (SMOTE) inside the CV fold — never applied before splitting.