End-to-End Classification: Text Features, Ensembles, and CTR
Machine LearningModel answerLast updated
Walk through a full supervised ML lifecycle covering bag-of-words pipelines, OOB validation, CTR modeling from data to deployment, and debugging a model that degrades in production.
Building and Operating Classification Systems
You're in a technical interview for an ML Engineer role. The interviewer wants to assess how you think end-to-end about supervised classification — from raw features to a live production system.
Address each of the following areas in turn. Be concrete: give technique names, explain why you'd make each choice, and flag trade-offs or common pitfalls.
Part 1 — Text Vectorization
Describe how you'd build a bag-of-words feature pipeline for a text classification task. Your answer should cover:
- How you tokenize and normalize raw text
- How you construct and prune a vocabulary without leaking test data
- What you do with rare terms and words not seen during training
- How you store the resulting matrix efficiently
- When you'd use raw counts versus TF-IDF, and what normalization step follows
Part 2 — Out-of-Bag Validation in Ensembles
Explain the out-of-bag (OOB) evaluation technique used in bagging-based methods like random forests:
- How OOB rows are generated and what fraction you'd expect to be left out per tree
- How individual OOB predictions are aggregated into a single error estimate
- Why this is useful and where it can mislead you
Part 3 — Click-Through Rate Prediction
Suppose your team needs a model to predict the probability that a user clicks on an item (ad, recommendation, search result). Walk through the full process:
- How you define the problem and what makes a well-formed label
- Where bias enters the training data and how to reduce its impact
- What features you'd engineer and how you'd handle high-cardinality IDs
- Which model families you'd try and in what order
- How you'd verify the model is well-calibrated and evaluate it both offline and online
Part 4 — General Classification Checklist
Separate from the CTR example: if you were handed a new classification problem from scratch, what are the major stages you'd work through? Mention concrete technique choices at each stage.
Part 5 — Debugging a Deployed Model
Three months after launch, online metrics start declining even though offline metrics look fine. How do you investigate? Organize your answer around at least three distinct root-cause categories (data, model, serving, product).
Hints
Hint 1
For Part 1, think carefully about which split you fit the vocabulary on — fitting on all available data is a subtle but serious form of leakage. The hashing trick trades one problem for another; be explicit about the trade-off.
Hint 2
For OOB error, work out the math: what is the probability a single row is excluded from a given bootstrap sample? That number tells you how many trees contribute to each OOB prediction and why the estimate is slightly pessimistic with small ensembles.
Hint 3
For CTR, calibration and offline/online metric gaps are where candidates most often go shallow. Think about why AUC can look great while the model is systematically over- or under-predicting probability, and why offline AUC improvements frequently fail to reproduce in an A/B test.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1 — Bag-of-Words Feature Pipeline
Tokenization and normalization. Start by lowercasing and applying Unicode normalization (NFKC). Replace URLs and standalone numbers with placeholder tokens like <URL> and <NUM> so they don't inflate the vocabulary. Tokenize by splitting on whitespace and punctuation. Adding bigrams is often worthwhile because unigrams miss short negations ("not great" vs. "great").
Stemming and lemmatization are optional: they improve recall on small datasets and matter less once you have millions of examples.
Vocabulary construction. Fit only on the training split. Fitting on the full dataset leaks test-set term frequencies into your feature space. Prune aggressively:
- Drop terms appearing in fewer than 5 documents (
min_df): they're noise. - Drop terms appearing in more than 90% of documents (
max_df): they carry little signal. - Cap total size at the top N most frequent remaining terms (e.g., 100k).
Rare and unseen words. Map any token below min_df or seen for the first time at inference to a shared <UNK> index. An alternative is the hashing trick: index = hash(token) % 2^20. This needs no stored vocabulary and handles new tokens gracefully, but causes hash collisions and makes features uninterpretable. Prefer it for streaming or very large-scale settings.
Sparse storage. A typical document matrix is extremely sparse — each document touches only tens of tokens out of hundreds of thousands. Store it in CSR (Compressed Sparse Row) format, which allocates memory proportional to nonzero entries rather than rows × columns.
Weighting. Raw counts work fine for short documents. For longer ones, apply sublinear TF (1 + log tf) to dampen repetition, then IDF weighting to downweight common terms. Always follow with L2 row normalization so documents of different lengths are comparable. A logistic regression or linear SVM on TF-IDF features is a strong, fast baseline before reaching for neural text encoders.
Part 2 — Out-of-Bag Evaluation
How OOB rows form. Each tree in a bagged ensemble trains on a bootstrap sample: n draws with replacement from n rows. The probability a specific row is never selected is (1 - 1/n)^n, which converges to 1/e ≈ 0.368. So roughly 37% of rows are out-of-bag for any given tree.
Aggregating predictions. For each row i, collect predictions only from trees where i was OOB. Average the predicted probabilities (or take a majority vote) and score against the true label. This gives the OOB error estimate — no separate validation fold needed.
Why it's useful. The OOB error is nearly unbiased for generalization error and comes free: no extra training runs or held-out splits. It also powers permutation feature importance: shuffle a feature's values in the OOB rows and measure how much the error increases.
Where it misleads you.
- With few trees (< 50), each OOB estimate is based on very few voters, making the estimate noisy and slightly pessimistic.
- It is invalid for time-series or grouped data, because bootstrap sampling can leak future rows into a tree that's "evaluating" earlier rows. Use a time-based holdout instead.
- It doesn't apply to boosting algorithms, which train sequentially on the full dataset.
Part 3 — CTR Prediction Workflow
Problem definition. The target is P(click | user, item, context) per impression. Define "impression" precisely (e.g., viewable for ≥ 1 second) and set a fixed attribution window for clicks. Decide upfront whether you need calibrated probabilities: ad auction systems multiply bid × pCTR to compute expected value, so miscalibrated scores directly cost money.
Data and bias. Positive rates are typically 0.1–5%, so downsampling negatives is common. If you downsample at rate w, correct predictions at inference: p = p' / (p' + (1 - p') / w). More importantly, your training data only reflects what your current system already showed users — selection bias. Mitigate it by logging position as a feature (and zeroing it at serving time), reserving a small random-traffic exploration slice, and logging propensity scores for inverse propensity weighting.
Feature engineering. Useful feature groups:
- User: historical CTR, recency/frequency signals
- Item: category, historical CTR with Bayesian smoothing:
(clicks + α·prior) / (impressions + α) - Context: device, time of day, placement, position
- Crosses: user × category, device × ad format
- High-cardinality IDs: hash into an embedding table rather than one-hot encoding
- Target encodings: always compute from rows strictly earlier in time than the label to prevent leakage
Model progression. Start with logistic regression on hashed feature crosses (low latency, highly interpretable). Move to LightGBM for dense numeric features and automatic interaction learning. For scale, try Wide & Deep, DeepFM, or DCN-style models that jointly learn memorization and generalization. Deep models require more infrastructure but tend to win on very large datasets.
Calibration. After training, plot reliability diagrams and check the ratio of mean predicted CTR to observed CTR globally and per segment. If miscalibrated, fit Platt scaling or isotonic regression on a held-out, chronologically later slice — never the validation set you used for model selection.
Evaluation. Offline: use log loss (normalized cross-entropy is more interpretable across different base rates) and AUC, stratified per user or query group. Online: run an A/B test measuring CTR, revenue, and guardrail metrics (latency, session depth, complaint rate). Offline AUC gains frequently fail to reproduce online, so the A/B test is the deciding signal.
Part 4 — General Classification Checklist
- Frame the problem. What label, what decision, what metric aligns with business cost? Set a majority-class or rule-based baseline before writing any model code.
- Data. Audit label quality and inter-annotator agreement. Check class balance, leakage, and split strategy (time or group splits when applicable).
- EDA. Examine distributions, missing rates, outliers, and label rate differences across segments.
- Feature engineering. Scale numerics; encode categoricals with one-hot, target encoding, or embeddings; vectorize text; impute and flag missing values. Wrap everything in a reproducible pipeline object.
- Model selection. Logistic regression → tree ensembles (random forest, LightGBM) → neural networks. Use cross-validation or time-based splits; track calibration alongside AUC.
- Threshold tuning. Select the decision threshold against the metric that reflects actual cost (F1, precision@recall target, cost-sensitive accuracy).
- Deployment. Align offline and online feature computation through a shared feature store. Shadow-launch, then canary rollout. Monitor score distributions, calibration, and latency continuously.
Part 5 — Debugging a Degraded Production Model
Data-layer causes. Check for distribution shift: compare feature distributions in current traffic against the training window using population stability index (PSI) or KL divergence. Look for upstream pipeline failures — null rates spiking, join keys mismatching, or features arriving at the wrong timestamp. Concept drift (the relationship between features and labels has changed) requires retraining on recent data.
Model-layer causes. Verify that the model artifact being served matches the expected version. Check whether a recent retrain introduced a feature that encodes the label (leakage that only matters at inference time when that future information is unavailable).
Serving-layer causes. Confirm that feature preprocessing at serving time is identical to training — the most common source of silent degradation. Check for latency increases forcing fallbacks to default scores. Look for schema mismatches between the feature store and the model's expected input types.
Product-level causes. Metric definitions may have changed (e.g., what counts as a "click"). A UI change might have shifted which impressions are shown, making the current traffic population different from the training population even if the model itself is fine. Competitor activity or seasonality can shift user intent without any system change.
Investigation order. Start with data: check null rates and distribution shift first because they're fast to diagnose. Then serving config and model version. Then model calibration on recent data. Finally, escalate to product and business context if the above are clean.