Click-Through Rate Modeling and Evaluation

Medium · Machine Learning · Machine Learning Engineer · Technical Screen

Prompt

You are given an impression-level feed dataset containing user attributes, content/item attributes, contextual request signals, and a binary click outcome (0 or 1). Design an end-to-end modeling and offline evaluation plan to predict click-through probabilities:

  1. Model progression: Establish a zero-skill naive baseline first, then train and compare three core tabular classifiers: logistic regression, random forests, and gradient-boosted decision trees.
  2. Algorithm trade-offs & deferred alternatives: Explain what each of the three chosen model families brings to the comparison and why other standard classifiers—such as support vector machines, Naive Bayes, or a basic feedforward neural network—are set aside initially, framing your reasoning around bias-variance behavior, interpretability, and training/serving cost.
  3. Validation & tuning: Specify a leak-free cross-validation scheme suited to logged user impressions and list the primary hyperparameters you would tune for each model family.
  4. Evaluation metrics: Choose and justify offline metrics for an approximately 50/50 class-balanced sample (weighing options such as log loss, ROC AUC, PR AUC, and classification accuracy), then explain how your metric selection and probability handling must adapt when clicks are rare (heavy class imbalance).
  5. Next iterations: Outline the highest-impact modeling, feature, calibration, and production improvements you would pursue given extra engineering time.

Scope & Expectations

  • Frame CTR prediction as calibrated probability estimation (P(click | features)), anchoring every model against a constant base-rate baseline before moving from linear models to bagged and sequentially boosted trees.
  • Compare chosen and rejected algorithms concretely across bias-variance dynamics, probability calibration quality, feature-interaction handling, interpretability, and training/inference latency.
  • Prevent temporal and preprocessing leakage in cross-validation, and connect each tuned hyperparameter to how it regularizes capacity or variance.
  • Contrast ranking metrics against proper probability-scoring rules on both balanced (~50% positive) and realistic rare-event (1%–2% CTR) traffic, followed by practical next steps for calibration, position bias, and live deployment.

Step-by-step walkthrough

  1. Frame click prediction as probability estimation

    In click-through rate (CTR) modeling, each row is one impression (one time a post or ad was shown to a user), and our goal is to predict the calibrated probability P(click = 1 | features), not just a hard 0/1 class label. Why do probabilities matter so much? Downstream ranking systems multiply P(click) by a downstream value—such as an advertiser's bid (expected_value = P(click) * bid) or an engagement weight—so predicting 0.40 vs 0.80 directly changes which item wins top slot, even though both exceed 0.50.

    Feature group   Example columns available BEFORE the impression is shown
    -------------   -----------------------------------------------------------------------
    User            account_age_days, user_7d_sessions, user_historical_ctr, device_os
    Item (post/ad)  community_id, media_type, post_age_minutes, item_historical_ctr
    Context         hour_of_day, day_of_week, feed_slot_position
    Target          clicked in {0, 1}  (~50% positive in this balanced exercise)
    

    Before fitting any model, enforce one iron rule against data leakage (accidentally giving the model information from the future that will not exist at serving time): rolling features like item_historical_ctr must be computed strictly from impressions prior to the current row's timestamp. Including the current click in a post's historical average produces spectacular offline scores and fails in production.

  2. Establish trivial and single-feature baselines

    Never jump straight to gradient boosting. Start with a trivial constant baseline that predicts the training set's overall click rate p_bar for every single row. It takes two lines of code, catches broken evaluation pipelines, and defines the "zero-skill" floor for every metric on a roughly 50/50 balanced dataset (p_bar = 0.50):

    Metric          Formula on constant p = 0.50                        Baseline value
    --------------  --------------------------------------------------  --------------
    Log loss        -(0.5 * ln(0.5) + 0.5 * ln(0.5)) = ln(2)            0.693 (lower is better)
    Brier score     mean((y - 0.5)^2) = 0.5^2                           0.250 (lower is better)
    ROC AUC         random-tie ranking across (pos, neg) pairs          0.500 (higher is better)
    PR AUC          constant precision = positive base rate             0.500 (higher is better)
    Accuracy @ 0.5  max(p_bar, 1 - p_bar)                               0.500 (higher is better)
    

    Add a second, single-feature heuristic baseline—such as ranking directly by smoothed item_historical_ctr—so you can measure how much lift multi-feature machine learning actually buys beyond historical popularity.

    from sklearn.dummy import DummyClassifier
    
    # Predicts the training base rate P(y = 1) for every row
    trivial_baseline = DummyClassifier(strategy="prior")
    
  3. Walk up the model ladder: linear, bagged, and boosted

    The three requested models form a deliberate ladder across the bias-variance trade-off (bias is systematic error from an overly rigid model; variance is sensitivity to noise in a specific training sample):

    Model                 Bias / Variance Profile         Interpretability      Train / Serve Cost
    --------------------  ------------------------------  --------------------  -----------------------------
    Logistic regression   High bias, very low variance    High (1 weight/feat)  Fastest / 1 dot product (~us)
    Random forest         Low bias; variance reduced by   Medium (feature       Parallel train / T deep trees
                          averaging independent trees     importances, SHAP)    (heavier memory & latency)
    Gradient-boosted      Low bias (sequential residual   Medium (SHAP,         Sequential train, more knobs /
    trees (GBT)           fitting); variance controlled   monotone constraints) T shallow trees (~ms)
                          via shrinkage & early stopping
    
    • Logistic regression models the log-odds (ln(p / (1 - p)), the logarithm of click odds) as a linear weighted sum w_0 + w_1 * x_1 + ... + w_d * x_d. Because it directly minimizes log loss, its output probabilities are naturally well-calibrated, training scales to tens of millions of rows, and every coefficient has a clear meaning (+1 unit in x_j multiplies click odds by exp(w_j)). Its limitation is high bias: it cannot see non-linear thresholds or feature interactions (such as "mobile users click video posts more, desktop users click text posts more") unless you engineer crossed features by hand.
    • Random forest grows many deep decision trees independently on bootstrap samples (random row samples drawn with replacement) while considering a random subset of features at each split, then averages their predicted probabilities. Deep trees automatically capture non-linearities and multi-way interactions (low bias), while averaging decorrelated trees cuts variance without overfitting as more trees are added. However, because every prediction is an average across diverse trees, random forests rarely output extreme probabilities near 0 or 1, often compressing predictions toward 0.5.
    • Gradient-boosted trees (GBT) (such as LightGBM, XGBoost, or HistGradientBoostingClassifier) build shallow trees sequentially: each new tree predicts the negative gradient (for log loss, simply the residual error y_i - p_i between the true click and the ensemble's current probability), scaled by a small learning rate. Boosting chips away at bias step by step and typically delivers the best accuracy and log loss on tabular CTR features, at the cost of sequential training and careful regularization to prevent overfitting.
  4. Why defer kernel margins, independence assumptions, and dense neural nets

    Interviewers ask about rejected models to check that you match algorithms to problem constraints rather than picking favorites blindly:

    • Support Vector Machines (SVM): SVMs optimize hinge loss (which only cares about pushing points past a decision margin, not estimating probabilities). Getting probabilities requires fitting a separate post-hoc Platt scaling logistic curve, and non-linear kernel SVMs take O(N^2) to O(N^3) training time and O(N^2) memory—completely infeasible on millions of click logs. Linear SVMs scale linearly, yet offer no advantage over L2-regularized logistic regression, which gives calibrated probabilities natively.
    • Naive Bayes: Assumes every feature is conditionally independent given the click label. Real CTR tables violate this badly (user_7d_sessions, user_30d_clicks, and user_historical_ctr all measure user activity). Naive Bayes multiplies their likelihoods together as if they were independent clues, double-counting correlated evidence and pushing predicted probabilities violently toward 0.0001 or 0.9999, which ruins log loss and calibration.
    • Simple multilayer perceptron (MLP / dense neural network): On medium-sized dense tabular data, plain MLPs usually trail gradient-boosted trees on accuracy, require sensitive preprocessing (imputation, scaling, architecture and learning-rate schedules), and offer weak interpretability. Neural architectures (such as Wide & Deep or Deep & Cross Networks) become the right upgrade later when you have hundreds of millions of rows and massive sparse ID vocabularies (user_id, post_id, community_id) that benefit from learned embedding tables.
  5. Prevent time leakage in cross-validation and hyperparameter tuning

    Click logs arrive over time and contain repeat users, so standard shuffled k-fold cross-validation leaks future trends—and the exact same user's later behavior—into earlier training folds.

    Use forward-chaining time-based validation (TimeSeriesSplit) instead, keeping a untouched final test window at the very end:

    Timeline (weeks):   [ W1 ][ W2 ][ W3 ][ W4 ][ W5 ][ W6 ][ W7 ][ W8 ]
    Fold 1:             Train [ W1..W3 ] -> Val [ W4 ]
    Fold 2:             Train [ W1..W4 ] -> Val [ W5 ]
    Fold 3:             Train [ W1..W5 ] -> Val [ W6 ]
    Fold 4:             Train [ W1..W6 ] -> Val [ W7 ]
    Final locked test:                                            [ W8 ] (evaluate once!)
    

    Two additional safeguards keep validation honest: - Fit preprocessors inside each fold: Scaling (StandardScaler), missing-value imputation, and any target encoding (replacing a category ID with its smoothed historical click rate) must be fit only on the training slice of each fold using a Pipeline. - Group by user when cold-start generalization matters: If you specifically want to measure performance on brand-new users, split users across folds (GroupKFold within time windows) so the model cannot memorize user-specific habits.

    Tune hyperparameters against validation log loss using randomized search or Bayesian optimization: - Logistic regression: Inverse regularization strength C (log-uniform 1e-4 to 1e2), penalty (L2 vs L1 / ElasticNet for sparse crossed features), and numeric transforms (log1p on skewed count columns). - Random forest: max_features per split (sqrt(d) to 0.5 * d, controlling tree diversity), min_samples_leaf (10 to 200, smoothing leaf probabilities), max_depth, and n_estimators (increase until validation loss plateaus). - Gradient-boosted trees: learning_rate (0.01 to 0.1) paired with n_estimators via early stopping on the latest validation slice, tree complexity (max_leaf_nodes 15 to 63 or max_depth 3 to 8), min_samples_leaf, row subsample / feature colsample_bytree (0.6 to 1.0), and l2_regularization.

  6. Choose metrics for balanced data — and adapt them for rare clicks

    On a roughly 50/50 balanced CTR dataset, pair one calibration-sensitive metric with one ranking metric:

    1. Log loss (binary cross-entropy) — Primary probability metric: -(1/N) * sum(y_i * ln(p_i) + (1 - y_i) * ln(1 - p_i)). Log loss is a proper scoring rule (a metric mathematically minimized if and only if the model outputs the true underlying probability), heavily penalizing confident wrong predictions.
    2. ROC AUC — Primary ranking metric: Measures the probability that a randomly chosen clicked impression receives a higher predicted score than a randomly chosen non-clicked impression (1.0 = perfect ordering, 0.5 = coin flip). Because ROC AUC depends only on rank order, it cannot tell whether probabilities are calibrated—making it the ideal partner to log loss.
    3. PR AUC (Average Precision), Brier score, and Accuracy @ 0.5 — Secondary checks: On 50/50 data, PR AUC also has a 0.50 baseline and tracks ROC AUC closely; Brier score (mean((y_i - p_i)^2)) gives a bounded squared probability error; and Accuracy @ 0.5 is intuitive for non-technical stakeholders, though dangerous on its own.

    Walk through a concrete 6-impression example to see why accuracy and ROC AUC alone are not enough:

    True click y:       [  1,    1,    1,    0,    0,    0  ]   (3 clicks, 3 non-clicks)
    Predicted prob p:   [ 0.9,  0.7,  0.4,  0.6,  0.3,  0.2 ]
    
    1. ROC AUC: 3 * 3 = 9 (positive, negative) pairs.
       - p=0.9 beats [0.6, 0.3, 0.2] -> 3 wins
       - p=0.7 beats [0.6, 0.3, 0.2] -> 3 wins
       - p=0.4 beats [0.3, 0.2]      -> 2 wins
       ROC AUC = (3 + 3 + 2) / 9 = 8 / 9 = 0.889  (baseline: 0.500)
    
    2. PR AUC (Average Precision across the 3 positive recall steps):
       Sorted by p: (0.9, y=1 -> prec 1/1), (0.7, y=1 -> prec 2/2), (0.6, y=0), (0.4, y=1 -> prec 3/4)
       PR AUC = (1.00 + 1.00 + 0.75) / 3 = 0.917  (baseline: 0.500)
    
    3. Log loss:
       -(ln 0.9 + ln 0.7 + ln 0.4 + ln(1 - 0.6) + ln(1 - 0.3) + ln(1 - 0.2)) / 6
       = (0.1054 + 0.3567 + 0.9163 + 0.9163 + 0.3567 + 0.2231) / 6 = 0.479  (baseline: 0.693)
    
    4. Brier score = (0.01 + 0.09 + 0.36 + 0.36 + 0.09 + 0.04) / 6 = 0.158  (baseline: 0.250)
    5. Accuracy @ 0.5 = 4 / 6 = 0.667  (rows 1, 2, 5, 6 correct)
    

    Notice the trap: if a timid model predicted 0.51 for every click and 0.49 for every non-click, it would score Accuracy = 1.000 and ROC AUC = 1.000, yet its log loss would be -ln(0.51) = 0.673—barely beating the 0.693 coin flip! Log loss catches that underconfidence immediately.

    import numpy as np
    
    
    def roc_auc_mann_whitney(y: np.ndarray, p: np.ndarray) -> float:
        """Compute exact ROC AUC as fraction of (positive, negative) pairs ordered right."""
        pos_scores = p[y == 1]
        neg_scores = p[y == 0]
        wins = 0.0
        for score in pos_scores:
            wins += float(np.sum(score > neg_scores)) + 0.5 * float(np.sum(score == neg_scores))
        return wins / (len(pos_scores) * len(neg_scores))
    
    
    def binary_log_loss(y: np.ndarray, p: np.ndarray, eps: float = 1e-15) -> float:
        """Compute binary cross-entropy loss with probability clipping for stability."""
        clipped = np.clip(p, eps, 1.0 - eps)
        return float(-np.mean(y * np.log(clipped) + (1.0 - y) * np.log(1.0 - clipped)))
    

    What changes if classes are heavily imbalanced (say a realistic 2% CTR)? - Drop Accuracy @ 0.5: Always predicting "no click" scores 98% accuracy while finding zero clicks. - Promote PR AUC and Precision@K alongside ROC AUC: Out of 1,000 impressions (20 clicks, 980 non-clicks), a model whose top bucket captures 18 clicks (90% recall) alongside 98 non-clicks (10% false-positive rate) looks strong on ROC AUC, yet its precision in that bucket is only 18 / (18 + 98) = 15.5%. PR AUC (baseline 0.02) highlights top-of-ranking precision directly. - Normalize log loss into Normalized Cross-Entropy (NE): At 2% CTR, the constant baseline achieves -(0.02 * ln 0.02 + 0.98 * ln 0.98) = 0.098 log loss. Dividing model log loss by 0.098 (NE = model_log_loss / baseline_log_loss) makes improvements comparable across traffic slices with different base CTRs. - Recalibrate after negative downsampling: If you keep all clicks and subsample non-clicks at rate w = 0.10 to speed up training, map raw predictions p back to true CTR scale q via Bayes' rule: q = p / (p + (1 - p) / w) (so p = 0.50 maps back to 0.50 / (0.50 + 5.0) = 0.091, not 50%!).

  7. End-to-end comparison pipeline and next-step improvements

    Putting the entire comparison into one leak-free scikit-learn loop ensures every model is judged on the exact same forward-chaining folds:

    from sklearn.dummy import DummyClassifier
    from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier
    from sklearn.impute import SimpleImputer
    from sklearn.linear_model import LogisticRegression
    from sklearn.model_selection import TimeSeriesSplit, cross_validate
    from sklearn.pipeline import make_pipeline
    from sklearn.preprocessing import StandardScaler
    
    
    def evaluate_ctr_models(X, y):
        """Compare baseline, logistic regression, RF, and GBT on time-ordered impressions."""
        models = {
            "baseline": DummyClassifier(strategy="prior"),
            "logistic": make_pipeline(
                SimpleImputer(strategy="median"),
                StandardScaler(),
                LogisticRegression(C=1.0, max_iter=1000),
            ),
            "random_forest": make_pipeline(
                SimpleImputer(strategy="median"),
                RandomForestClassifier(
                    n_estimators=300,
                    min_samples_leaf=20,
                    max_features="sqrt",
                    n_jobs=-1,
                    random_state=0,
                ),
            ),
            "gbt": HistGradientBoostingClassifier(
                learning_rate=0.05,
                max_iter=300,
                max_leaf_nodes=31,
                min_samples_leaf=20,
                l2_regularization=1.0,
                random_state=0,
            ),
        }
    
        folds = TimeSeriesSplit(n_splits=5)
        scoring = ["roc_auc", "average_precision", "neg_log_loss", "accuracy"]
        summary = {}
        for name, model in models.items():
            cv = cross_validate(model, X, y, cv=folds, scoring=scoring)
            summary[name] = {
                "roc_auc": float(cv["test_roc_auc"].mean()),
                "pr_auc": float(cv["test_average_precision"].mean()),
                "log_loss": float(-cv["test_neg_log_loss"].mean()),
                "accuracy": float(cv["test_accuracy"].mean()),
            }
        return summary
    

    With more time, prioritize improvements with the highest real-world ROI: 1. Richer leak-free features: Multi-window interaction counts (1h, 24h, 7d), user-to-community affinity ratios, Bayesian-smoothed out-of-fold target encoding for high-cardinality IDs, and pre-trained text/image embeddings for post content. 2. Post-hoc probability calibration: Verify reliability diagrams per segment (mobile vs desktop, new vs power users) and apply isotonic regression (a non-parametric monotonic curve fit on a held-out validation slice) if tree models show S-shaped probability distortion. 3. De-biasing feed position: Posts in slot #1 get clicked simply because eyes land there first (position bias). Include feed_slot_position as a feature during training so content features do not absorb slot luck, then evaluate all candidate items at a standardized reference position (position = 1) at serving time. 4. Production serving, monitoring, and online A/B testing: Benchmark p99 inference latency, monitor feature drift and live calibration ratio (mean_predicted_ctr / observed_ctr, which should stay near 1.0), and validate offline wins with an online A/B test tracking net clicks alongside guardrail metrics (post hides, reports, and return sessions).

Intuition & how it works

Predicting whether a user will click a post or ad is like estimating rain probabilities rather than just shouting "umbrella" or "no umbrella": ranking feeds and ad auctions multiply your predicted click-through rate (CTR) by downstream values like advertiser bids or long-term engagement weights, so predicting 0.80 vs 0.55 changes which item wins Slot #1 even though both round to 1. That means we need models that both rank clicked items above ignored ones and output honest, calibrated probabilities (meaning among impressions where the model predicts 0.30, roughly 30% actually get clicked).

A naive workflow throws a complex model straight at randomly shuffled click logs and picks the winner by classification accuracy. That fails in three ways: shuffled splits leak future user behavior into past training rows, accuracy hides broken probabilities (and awards 98% to a useless "never click" predictor when true CTR is 2%), and without a trivial base-rate baseline you cannot tell if your feature pipeline is even beating ln(2) = 0.693 coin-flip log loss. Instead, we progress deliberately from a constant base-rate baseline (DummyClassifier) up a bias-variance ladder—logistic regression (fast linear log-odds baseline), random forest (bagged deep trees that capture interactions automatically), and gradient-boosted trees (sequential shallow trees minimizing log-loss residuals)—evaluated on forward-chaining time splits.

Trace a tiny 4-impression validation slice with balanced labels y = [1, 1, 0, 0]: - Trivial baseline predicts p = [0.5, 0.5, 0.5, 0.5]: every (positive, negative) pair ties (ROC AUC = 0.50), and log loss = -ln(0.5) = 0.693. - Underconfident ranker predicts p = [0.51, 0.51, 0.49, 0.49]: every positive beats every negative (ROC AUC = 1.00, Accuracy = 1.00), yet log loss = -ln(0.51) = 0.673—exposing that its probabilities are nearly coin flips. - Well-calibrated boosted model predicts p = [0.85, 0.75, 0.25, 0.15]: ROC AUC = 1.00, and log loss = -(ln 0.85 + ln 0.75 + ln 0.75 + ln 0.85) / 4 = 0.225, rewarding both sharp ranking and trustworthy confidence.

Key points

  • Start with baselines to anchor metrics: Predicting constant p_bar = 0.50 sets the floor at log loss = 0.693, Brier = 0.250, ROC AUC = 0.50, PR AUC = 0.50, and accuracy = 0.50; a single-feature baseline (item_historical_ctr) shows how much lift complex models add beyond item popularity.
  • Three models span the bias-variance spectrum: Logistic regression has high bias and low variance, trains and serves fastest (one dot product), and gives interpretable odds ratios, but misses interactions unless crossed by hand. Random forest cuts the high variance of deep trees by averaging bootstrap-sampled trees (random row samples with replacement), finding interactions automatically but compressing extreme probabilities away from 0 and 1. Gradient-boosted trees cut bias sequentially by fitting shallow trees to residuals (y - p), usually winning on tabular CTR data when regularized with shrinkage, subsampling, and early stopping.
  • Clear reasons for skipping plausible alternatives: SVMs optimize margin hinge loss without native probabilities and kernel SVMs scale at least quadratically (O(N^2)) in row count; Naive Bayes double-counts correlated activity features, producing extreme, poorly calibrated probabilities; and plain dense neural networks require heavier tuning without beating boosted trees until dataset size and high-cardinality ID embeddings justify deep architectures (like Wide & Deep).
  • Split strictly by time and prevent pipeline leakage: Hold out the newest time window as a locked test set, tune hyperparameters with forward-chaining TimeSeriesSplit folds, and fit scalers, imputers, and encoders inside each training fold.
  • Pair Log Loss with ROC AUC on balanced data, and shift for rare clicks: Log loss (a proper scoring rule, minimized only by the true probability) evaluates calibration and sharpness, while ROC AUC evaluates pure pairwise ranking. Under severe class imbalance (e.g., 2% CTR), drop accuracy, add PR AUC and Precision@K, report Normalized Cross-Entropy (model_log_loss / baseline_log_loss, where 2% baseline entropy is 0.098), and recalibrate negative-downsampled predictions via q = p / (p + (1 - p) / w).

Common mistakes

  • Using random shuffled KFold on timestamped logs: Training on Tuesday's clicks to predict Monday's impressions leaks future post virality and user activity, inflating offline AUC and log loss.
  • Computing rolling historical CTRs across the full dataset before splitting: Including the target click inside post_ctr or user_ctr is direct target leakage.
  • Fitting StandardScaler or target encoders before cross-validation: Precomputing statistics across validation rows leaks validation distributions into training folds.
  • Selecting CTR models by Accuracy @ 0.5 alone: Accuracy ignores probability calibration completely and collapses on imbalanced production traffic.
  • Serving raw probabilities after negative downsampling or class_weight="balanced": Reweighting shifts predicted log-odds by -ln(w), causing the ranker to wildly overestimate click rates in ad pricing unless recalibrated back to the natural base rate.
  • Ignoring position bias in feed data: Items previously shown in Slot #1 received extra clicks purely from visibility; if position is omitted during training, the new model confuses old ranker placement with intrinsic post quality.

Follow-up questions

  • How would you check whether predicted click probabilities are well calibrated, and how do you recalibrate them if they drift? Group validation predictions into decile bins, plot mean predicted probability against actual observed click rate (reliability diagram), and track overall sum(predicted) / sum(clicked) calibration ratio plus Expected Calibration Error (ECE) (the impression-weighted average absolute gap between predicted and observed CTR across bins). If a random forest or boosted tree is miscalibrated, fit Platt scaling (a 2-parameter logistic curve on raw logits, safer on smaller validation slices) or isotonic regression (a flexible non-decreasing step function, stronger when you have tens of thousands of validation examples) on a separate held-out time slice, and re-verify calibration across key slices like mobile vs web and new vs returning users.
  • Suppose a boosted tree improves offline ROC AUC and log loss, but live A/B test click rates do not move—what could explain the gap? First, check for training-serving skew (features computed cleanly in offline data warehouses arriving stale, null, or differently normalized in real-time serving). Second, offline logs suffer from selection and position bias—the offline dataset only contains impressions the old ranker chose to surface, whereas online users react to new candidates pushed into top slots. Third, global ROC AUC weights rank swaps between Slot #50 and Slot #100 equally with swaps between Slot #1 and Slot #2, even though users rarely scroll to #50; inspect offline NDCG@5, live predicted / observed calibration logs, and latency degradation (slower feed loads directly depress clicks).
  • How can you encode high-cardinality IDs such as community or creator identifiers without memorizing rare categories? One-hot encoding hundreds of thousands of IDs starves tree splits and blows up memory, while raw target encoding memorizes rare IDs that had 1 click in 1 impression (100% CTR). For tree models, compute out-of-fold empirical Bayes target encoding strictly from past timestamps: blend each category's historical click rate k / n toward the global prior p_bar as (k + m * p_bar) / (n + m) (where smoothing weight m, say 20, shrinks low-count IDs safely toward the global average). For linear or neural models, use feature hashing (HashingVectorizer) or learned low-dimensional ID embedding tables with frequency cutoffs mapping rare/unseen IDs to an <UNK> bucket.

Follow-up questions

Similar questions

More Reddit interview questions

All 36 Reddit questions →