End-to-End ML Pipeline with NumPy and Pandas Only
Machine LearningModel answerLast updated
Build a complete, leak-free machine learning pipeline — preprocessing, training, and evaluation — using only NumPy and pandas, no ML libraries.
The Challenge
You receive a tabular dataset as a pandas DataFrame df. It contains a mix of numeric and categorical feature columns plus a target column y that is either a continuous value (regression) or a binary label (classification).
Your tools are limited to pandas, numpy, and the Python standard library. You may look up documentation freely, but ML frameworks like scikit-learn, statsmodels, or XGBoost are off the table.
Build a working, end-to-end pipeline that covers the following four areas.
1. Data Preparation
- Deal with missing values in both numeric and categorical columns.
- Convert categorical variables into a numeric representation the model can consume.
- Partition the data into training and validation sets (or implement cross-validation).
- Decide when feature scaling is necessary and apply it correctly, making sure nothing leaks from validation into the training fit.
2. Model Implementation
- Pick a sensible baseline: linear regression for a continuous target, logistic regression for a binary one.
- Write the training loop using gradient descent in NumPy — no
fit()calls from any library. - Implement a
predictfunction that works on new data.
3. Evaluation
- Choose metrics that match the task (e.g., RMSE / R² for regression; accuracy, precision, recall, F1, AUC for classification).
- Show how to detect overfitting from the train vs. validation metric gap, and describe what you would do about it.
4. Concept Questions
Be ready to explain:
- Bias–variance tradeoff — what it is and how your choices affect it.
- Regularization — how L1 and L2 differ mathematically and in the solutions they produce.
- Class imbalance — when it causes problems and how to handle it.
- Feature scaling — which algorithms need it and why.
- Data leakage — common sources and how to design a pipeline that avoids them.
What the answer should demonstrate: a correct, well-structured pipeline; awareness of edge cases; the ability to reason about trade-offs rather than just reciting formulas.
Hints
Hint 1
Split the data before computing any summary statistics (medians, means, standard deviations, category vocabularies). If you fit the preprocessor on the whole dataset first, you've already leaked information from the validation set into your features.
Hint 2
The gradient update rule for both linear and logistic regression has the same form: Xᵀ(ŷ − y) / n. The only difference is whether ŷ is a raw dot product or passed through a sigmoid. One training loop with a task flag handles both cases cleanly.
Hint 3
AUC can be computed without sorting predictions into a ROC curve by hand — use the Wilcoxon-Mann-Whitney statistic: rank the scores, sum the ranks of the positive examples, then apply the formula. Watch out for the edge case where a split contains only one class.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core principle is split first, fit nothing on the full dataset. Every preprocessing statistic — medians for imputation, means and standard deviations for scaling, category vocabularies for encoding — must be derived from the training partition only and then applied to validation and test. Violating this is the single most common mistake interviewers watch for.
Beyond that, the model choice should be deliberate but humble. Linear and logistic regression are the right defaults: they are convex, so gradient descent reaches the global optimum; they are interpretable; and they expose the concepts (regularization, scaling, the bias term) that concept questions will probe.
Data Preparation
Numeric missing values. Impute with the training median (more robust than the mean when outliers are present). Add a binary _isna indicator column for each affected feature — missingness is often predictive and this captures it without distorting the imputed values.
Categorical missing values. Treat NaN as its own explicit category, e.g. "__NA__". This avoids dropping rows and lets the model learn a coefficient for "unknown."
Encoding. Build a vocabulary of the top-K most frequent categories per column, using training data only. Categories that are rare or completely absent at validation/test time map to an all-zeros vector — they contribute nothing rather than crashing the pipeline. Drop very-high-cardinality columns (IDs, free text) outright, or bucket them.
Scaling. Z-score numeric features using training mean and standard deviation. Guard against zero-variance columns by replacing std = 0 with 1. Scaling matters for gradient descent because it conditions the loss surface: without it, features with large ranges dominate the gradient and a single learning rate works poorly for all dimensions.
Splitting. Shuffle with a fixed random seed. For classification, stratify so both partitions preserve the class ratio. If the data has a temporal structure, split by time instead — shuffling would be leakage.
Model and Training
Both linear and logistic regression share the update rule:
gradient_w = Xᵀ(ŷ − y) / n + λw
gradient_b = mean(ŷ − y)
w ← w − lr · gradient_w
b ← b − lr · gradient_b
The only difference is the forward pass: ŷ = Xw + b for regression, ŷ = σ(Xw + b) for classification. L2 regularization adds λw to the weight gradient but not to the bias gradient — penalizing the bias would shift all predictions toward zero for no good reason.
Clip logits to [-500, 500] before exp to avoid overflow in the sigmoid.
For class imbalance, weight each sample inversely proportional to its class frequency. This is equivalent to upsampling the minority class without replicating data.
Evaluation
| Task | Primary metric | Secondary |
|---|---|---|
| Regression | RMSE | MAE, R² |
| Classification | AUC | F1, precision, recall |
AUC is computed via the Wilcoxon-Mann-Whitney rank statistic — no need to build a full ROC curve. Sum the ranks of the positive examples, subtract the minimum possible rank sum, and divide by n_pos × n_neg.
Overfitting shows up as a widening gap between training and validation metrics. The remedies, in order of preference: increase L2 regularization λ, reduce feature count, collect more data.
Concept Trade-offs
L1 vs L2. L2 penalizes ½λ‖w‖² and produces a smooth gradient λw, which shrinks all weights toward zero proportionally — no weight ever reaches exactly zero. L1 penalizes λ‖w‖₁ and produces a subgradient with constant magnitude, which drives small weights to exactly zero and gives sparse solutions. L1 is better when you suspect only a few features are relevant; L2 is easier to optimize and works well when many features contribute weakly.
Bias–variance. High regularization → higher bias, lower variance (underfitting risk). Low regularization → lower bias, higher variance (overfitting risk). The validation curve is your empirical guide to where the sweet spot is.
Leakage sources beyond preprocessing. Duplicated rows split across train and validation; a feature that encodes the future (e.g., a downstream signal); target encoding computed on the full dataset before splitting. All have the same fix: the split is the first operation.
Full Implementation
import numpy as np
import pandas as pd
# ── 1. Train / validation split ──────────────────────────────────────────────
def train_val_split(df, target="y", val_frac=0.2, seed=0, stratify=False):
rng = np.random.default_rng(seed)
if stratify:
val_idx = []
for _, group in df.groupby(target):
k = max(1, int(round(len(group) * val_frac)))
val_idx.extend(rng.choice(group.index.to_numpy(), k, replace=False))
val_mask = df.index.isin(val_idx)
else:
val_mask = rng.random(len(df)) < val_frac
return df[~val_mask].copy(), df[val_mask].copy()
# ── 2. Preprocessor ──────────────────────────────────────────────────────────
class Preprocessor:
def __init__(self, max_categories=20):
self.max_categories = max_categories
def fit(self, X: pd.DataFrame):
self.num_cols = X.select_dtypes(include=np.number).columns.tolist()
self.cat_cols = [c for c in X.columns if c not in self.num_cols]
# imputation stats (training only)
self.medians = X[self.num_cols].median()
self.na_indicator_cols = [c for c in self.num_cols if X[c].isna().any()]
filled = X[self.num_cols].fillna(self.medians)
self.means = filled.mean()
self.stds = filled.std(ddof=0).replace(0, 1.0)
# category vocabularies (training only)
self.vocab = {}
for c in self.cat_cols:
counts = X[c].astype("object").fillna("__NA__").value_counts()
self.vocab[c] = counts.index[: self.max_categories].tolist()
return self
def transform(self, X: pd.DataFrame) -> np.ndarray:
filled = X[self.num_cols].fillna(self.medians)
scaled = (filled - self.means) / self.stds
parts = [scaled]
# missingness indicators
if self.na_indicator_cols:
indicators = (
X[self.na_indicator_cols]
.isna()
.astype(float)
.rename(columns=lambda c: f"{c}_isna")
)
parts.append(indicators)
# one-hot encoding; unseen categories → all zeros
for c in self.cat_cols:
col = X[c].astype("object").fillna("__NA__")
ohe = pd.DataFrame(
{f"{c}={v}": (col == v).astype(float) for v in self.vocab[c]},
index=X.index,
)
parts.append(ohe)
return pd.concat(parts, axis=1).to_numpy(dtype=float)
# ── 3. Linear / logistic regression with L2 ─────────────────────────────────
class LinearModel:
"""task = 'regression' (MSE + L2) or 'classification' (log-loss + L2)."""
def __init__(
self,
task: str,
lr: float = 0.1,
l2: float = 1e-3,
n_iter: int = 2000,
class_weight: str | None = None,
):
self.task = task
self.lr = lr
self.l2 = l2
self.n_iter = n_iter
self.class_weight = class_weight
def _sigmoid(self, z: np.ndarray) -> np.ndarray:
return 1.0 / (1.0 + np.exp(-np.clip(z, -500, 500)))
def _forward(self, X: np.ndarray) -> np.ndarray:
z = X @ self.w + self.b
return self._sigmoid(z) if self.task == "classification" else z
def fit(self, X: np.ndarray, y: np.ndarray):
n, d = X.shape
self.w = np.zeros(d)
self.b = 0.0
# sample weights for class imbalance
weights = np.ones(n)
if self.task == "classification" and self.class_weight == "balanced":
pos_rate = y.mean()
weights = np.where(y == 1, 0.5 / pos_rate, 0.5 / (1.0 - pos_rate))
weights /= weights.sum() # normalise so loss scale stays stable
for _ in range(self.n_iter):
residual = weights * (self._forward(X) - y) # (n,)
grad_w = X.T @ residual + self.l2 * self.w # L2 on weights only
grad_b = residual.sum()
self.w -= self.lr * grad_w
self.b -= self.lr * grad_b
return self
def predict_proba(self, X: np.ndarray) -> np.ndarray:
return self._forward(X)
def predict(self, X: np.ndarray, threshold: float = 0.5) -> np.ndarray:
out = self._forward(X)
if self.task == "classification":
return (out >= threshold).astype(int)
return out
# ── 4. Metrics ───────────────────────────────────────────────────────────────
def regression_metrics(y: np.ndarray, yhat: np.ndarray) -> dict:
mse = np.mean((y - yhat) ** 2)
r2 = 1.0 - mse / max(np.var(y), 1e-12)
return {"rmse": float(np.sqrt(mse)), "mae": float(np.mean(np.abs(y - yhat))), "r2": float(r2)}
def _roc_auc(y: np.ndarray, scores: np.ndarray) -> float:
"""AUC via the Wilcoxon-Mann-Whitney rank statistic."""
n_pos = int(y.sum())
n_neg = len(y) - n_pos
if n_pos == 0 or n_neg == 0:
return float("nan")
# average-rank ties
ranks = pd.Series(scores).rank(method="average").to_numpy()
return float((ranks[y == 1].sum() - n_pos * (n_pos + 1) / 2) / (n_pos * n_neg))
def classification_metrics(
y: np.ndarray, proba: np.ndarray, threshold: float = 0.5
) -> dict:
yhat = (proba >= threshold).astype(int)
tp = int(((yhat == 1) & (y == 1)).sum())
fp = int(((yhat == 1) & (y == 0)).sum())
fn = int(((yhat == 0) & (y == 1)).sum())
precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0
recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0
f1 = (2 * precision * recall / (precision + recall)
if (precision + recall) > 0 else 0.0)
return {
"accuracy": float(np.mean(yhat == y)),
"precision": precision,
"recall": recall,
"f1": f1,
"auc": _roc_auc(y, proba),
}
# ── 5. Full pipeline ─────────────────────────────────────────────────────────
def run_pipeline(df: pd.DataFrame, target: str = "y", task: str = "classification"):
# map string / bool targets to {0, 1}
if task == "classification" and df[target].dtype != float:
df = df.copy()
df[target] = df[target].map({v: i for i, v in enumerate(df[target].unique())})
train_df, val_df = train_val_split(
df, target=target, stratify=(task == "classification")
)
X_train_raw = train_df.drop(columns=[target])
y_train = train_df[target].to_numpy(dtype=float)
X_val_raw = val_df.drop(columns=[target])
y_val = val_df[target].to_numpy(dtype=float)
# fit preprocessor on training data only
prep = Preprocessor()
prep.fit(X_train_raw)
X_train = prep.transform(X_train_raw)
X_val = prep.transform(X_val_raw)
model = LinearModel(
task=task,
lr=0.05,
l2=1e-3,
n_iter=3000,
class_weight="balanced" if task == "classification" else None,
)
model.fit(X_train, y_train)
if task == "regression":
train_m = regression_metrics(y_train, model.predict(X_train))
val_m = regression_metrics(y_val, model.predict(X_val))
else:
train_m = classification_metrics(y_train, model.predict_proba(X_train))
val_m = classification_metrics(y_val, model.predict_proba(X_val))
print("Train:", {k: round(v, 4) for k, v in train_m.items()})
print("Val :", {k: round(v, 4) for k, v in val_m.items()})
return model, prep
Complexity
- Preprocessing: O(n · d) time and memory.
- Training: O(T · n · d) — each iteration is one matrix-vector multiply.
- AUC: O(n log n) due to the ranking step.
Common mistakes to avoid
- Fitting the scaler or imputer before the split.
- Regularizing the bias term.
- Using accuracy as the primary metric on an imbalanced dataset.
- Forgetting to clip logits before sigmoid — silent
nanpropagation kills the entire gradient. - Building the category vocabulary on the full dataset, leaking rare-category information into the fold statistics.