Machine Learning Fundamentals interview question · Most asked
Write scikit-learn code that trains and evaluates a classifier without leaking preprocessing.
Hands-on Asked in Machine Learning Engineer interviews
Summary
Put preprocessing and the model into one Pipeline (with a ColumnTransformer for numeric and categorical
columns), split the data first, and evaluate with cross-validation on the training data and once on the test set.
Fitting inside the pipeline means each fold's imputers and encoders only see that fold's training rows.
Longer Answer
Points to mention: stratified split, handle_unknown="ignore" for categories seen only in production, class
weights for imbalance, a metric suited to the problem (PR-AUC here), and saving the whole pipeline (not just the
model) with joblib so serving applies identical preprocessing.
Example
import joblib
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.impute import SimpleImputer
from sklearn.metrics import average_precision_score
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
df = pd.read_csv("customers.csv")
X, y = df.drop(columns=["churned"]), df["churned"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
numeric = ["tenure_months", "monthly_spend", "support_tickets"]
categorical = ["plan", "country"]
prep = ColumnTransformer([
("num", SimpleImputer(strategy="median"), numeric),
("cat", Pipeline([("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore"))]), categorical),
])
model = Pipeline([("prep", prep),
("clf", HistGradientBoostingClassifier(class_weight="balanced", random_state=42))])
cv = cross_val_score(model, X_train, y_train, cv=5, scoring="average_precision")
print(f"CV PR-AUC {cv.mean():.3f} ± {cv.std():.3f}")
model.fit(X_train, y_train)
print("Test PR-AUC", average_precision_score(y_test, model.predict_proba(X_test)[:, 1]))
joblib.dump(model, "churn_model.joblib")
Key Points
- Split first, then fit.
- Pipeline + ColumnTransformer prevents leakage.
- Cross-validate on training data only.
- Persist the whole pipeline.
Explanation
What interviewers look for
Correct, leak-free code and the reasons behind each choice.
More Machine Learning Fundamentals questions
- Compare decision trees, random forests and gradient boosting.
- What is the difference between supervised, unsupervised and reinforcement learning?
- Explain the bias-variance trade-off.
- What is data leakage, and how do you detect it?
- Which metrics would you use for a classification model, and when is accuracy misleading?
- What is overfitting, and how do you prevent it?
- How do you split data for training, validation and testing, and what is cross-validation?
- Your model scored well offline but performs badly in production. What do you check?