Skip to content

Data Scientist interview questions

100 real questions with model answers and explanations for Middle candidates.

See a Data Scientist resume example

Practice with flashcards

Spaced repetition · Hunter Pass

Questions

boostingensembles

Random forest emphasizes robustness, while gradient boosting usually emphasizes maximum tabular accuracy.

  • Random forest trains deep trees independently on bootstrapped rows and random feature subsets, then averages them to reduce variance.
  • Gradient boosting adds shallow trees sequentially to reduce the current loss, lowering bias but increasing sensitivity to learning rate, tree count, and noise.
  • I use boosting as the main performance candidate and random forest as a strong baseline or when I need little tuning, parallel training, and stable importance estimates.

Why interviewers ask this: The variance-reduction versus bias-reduction framing, not just parallel versus sequential, is what distinguishes understanding from memorized taxonomy.

boosting

I reduce XGBoost overfitting by controlling step size, tree capacity, randomness, and explicit regularization.

  • Lower learning_rate, increase the tree count, and use early stopping on untouched validation data so many small updates replace a few aggressive ones.
  • Reduce max_depth or increase min_child_weight to prevent trees from memorizing rare patterns, then use subsample and colsample to decorrelate them.
  • Raise gamma for stricter split gains and lambda or alpha for leaf-weight penalties, while judging every change on data the model never trains on.

Why interviewers ask this: Grouping the knobs by mechanism, step size, tree capacity, randomness, penalties, shows the candidate tunes with a mental model rather than a copied grid.

boosting

XGBoost and LightGBM often reach similar tuned quality, but their growth strategy and scaling behavior differ.

  • LightGBM grows leaf-wise by splitting the leaf with the largest loss reduction, which is efficient but can create deep uneven branches that overfit small data.
  • Classic XGBoost grows level-wise and is more balanced, while LightGBM's histogram methods, sampling, and native categorical support make it faster on large datasets.
  • I favor LightGBM for millions of rows and rapid iteration, controlling num_leaves with max_depth, and otherwise choose by ecosystem and measured validation results.

Why interviewers ask this: Leaf-wise versus level-wise growth with its overfitting consequence is the substantive difference interviewers check, beyond it is faster.

boostingownership

Gradient boosting builds an additive model by performing gradient descent in function space.

  • It starts with a constant prediction and computes each sample's loss gradient with respect to the ensemble's current prediction.
  • The next tree fits those gradients, its contribution is multiplied by the learning rate, and the result is added to the ensemble before repeating.
  • With squared error the gradients are residuals, while the same machinery supports other differentiable objectives such as logistic, quantile, and ranking losses.

Why interviewers ask this: The gradient-descent-in-function-space formulation and why residuals are just the squared-loss special case separate real understanding from the folk explanation.

Default boosted-tree importance can reflect training-data bias rather than genuine predictive value.

  • Split-count and gain scores favor features with many split points, while correlated features divide credit arbitrarily between near-duplicates.
  • I rank features with permutation importance on held-out data and use grouped permutation when correlated variables should be evaluated together.
  • SHAP adds direction and per-sample attribution, but the decisive check is retraining without a suspicious feature and measuring the validation change.

Why interviewers ask this: Naming the split-cardinality bias and correlation credit-splitting, then reaching for held-out permutation, shows importance treated as measurement rather than decoration.

explainabilitycommunicationstakeholder-management

SHAP explains both the direction and size of feature contributions for individual predictions.

  • Each prediction is decomposed relative to a baseline, showing which features pushed a specific score up or down rather than only ranking them globally.
  • Aggregated SHAP values provide global views, dependence plots reveal changing effects and interactions, and explanation clusters expose distinct subpopulations.
  • With stakeholders I use case-level narratives and plausibility checks, while stating clearly that SHAP explains model behavior, not causal effects.

Why interviewers ask this: Per-prediction signed attribution plus the explains-the-model-not-the-world caveat shows SHAP used correctly rather than as an oracle.

SVM remains effective for small or medium, high-dimensional datasets when its geometric requirements are respected.

  • A linear SVM is especially strong for sparse text with thousands of TF-IDF features, while kernels can model nonlinear boundaries through implicit mappings.
  • Feature scaling is mandatory because margins and RBF distances are geometric, and one large-scale feature can otherwise dominate the model.
  • Kernel SVMs scale poorly beyond a few hundred thousand samples, probabilities need calibration, and C and gamma must be tuned together.

Why interviewers ask this: Knowing where SVMs still win, high-dimensional small data, and the hard scaling requirement shows practical breadth beyond the boosting-for-everything reflex.

clustering

Meaningless k-means segments usually indicate violated geometry assumptions or an unsuitable feature space.

  • K-means assumes roughly spherical clusters of similar size and density under Euclidean distance, and it always returns k groups even if no clusters exist.
  • I verify scaling, inspect PCA or UMAP projections, and compare silhouette scores across k values while allowing for the possibility of one continuous cloud.
  • If the groups lack business meaning, I rebuild features around relevant behaviors before tuning k, because a different k cannot repair irrelevant inputs.

Why interviewers ask this: Recognizing that k-means always returns clusters, and questioning the feature space before the algorithm, is the diagnostic maturity being probed.

clustering

DBSCAN gains flexible cluster shapes and explicit noise handling, but depends heavily on meaningful local density.

  • It groups points having at least min_samples neighbors within eps, finds arbitrary shapes, requires no preset k, and leaves sparse points as noise.
  • One eps cannot represent clusters with very different densities, distance concentration breaks density in high dimensions, and eps itself needs diagnostics such as a k-distance elbow.
  • I use DBSCAN for low-dimensional spatial or noise-heavy data, and prefer k-means or Gaussian mixtures for scalable blob-like clusters, often after dimensionality reduction.

Why interviewers ask this: The single-eps-versus-varying-density failure and distance concentration in high dimensions show DBSCAN known from use, not from its promise of no k needed.

regularization

L1 creates sparse models, while L2 usually provides smoother and more stable shrinkage.

  • L1 has a constant penalty gradient and a diamond-shaped constraint with corners on the axes, so small coefficients can become exactly zero.
  • L1 suits feature selection and sparse interpretation, whereas L2 spreads weight across correlated features and is often the safer predictive default.
  • Elastic net combines both for correlated groups when sparsity matters, with standardized features and penalty strength selected by cross-validation.

Why interviewers ask this: The geometric corners-on-axes intuition plus the correlated-features behavior difference shows regularization understood, not just recited as sparsity versus shrinkage.

boostingregression

Logistic regression can beat boosting when data, representation, or operational requirements favor a linear model.

  • It performs well on small datasets and wide sparse inputs such as text or heavy one-hot encoding, where boosting may overfit.
  • It is easy to deploy, offers an auditable formula, and often gives better calibrated probabilities without post-processing, making it a necessary baseline.
  • Its raw coefficients are log-odds, require scaling for comparison, become unstable with correlated features, and describe association rather than causation.

Why interviewers ask this: Naming calibration and sparse-wide data as linear wins, plus the log-odds and correlation instability traps, shows the classical tool respected and read correctly.

Tree and linear models need different preprocessing because they represent relationships differently.

  • Trees split by order-preserving thresholds, so scaling, normalization, and monotonic log transforms do not change their splits and are usually wasted for XGBoost.
  • Linear and distance-based models need scaling, often benefit from log transforms for skew, and require explicit bins, splines, or interactions for nonlinear structure.
  • For trees I focus on categorical encoding, missing-value semantics, and domain features such as ratios that would otherwise require many splits.

Why interviewers ask this: Knowing invariance to monotonic transforms and redirecting effort toward ratios and encodings shows preprocessing matched to model mechanics rather than ritual.

knn

K-nearest-neighbors fails in high dimensions because geometric proximity stops carrying useful contrast.

  • Distances concentrate, so the relative gap between nearest and farthest neighbors shrinks and the nearest point is barely more meaningful than a random one.
  • High-dimensional volume also makes a fixed dataset sparse, while irrelevant dimensions disproportionately dilute signal in the distance metric.
  • For kNN, clustering, and RBF methods I reduce dimensions, learn embeddings or a metric, or switch to models such as trees that implicitly select useful features.

Why interviewers ask this: Distance concentration as the mechanism, extended to kernels and clustering, shows the curse of dimensionality understood as geometry rather than slogan.

A model is miscalibrated when its predicted probabilities do not match observed event frequencies.

  • If only 60 percent of cases scored 0.9 are positive, a reliability diagram exposes the gap from the expected 90 percent.
  • Forest averaging often avoids extremes, boosting can become overconfident, and class-imbalance resampling changes the base rate embedded in scores.
  • I calibrate on held-out data with Platt scaling for smooth corrections or isotonic regression with more data, especially when probabilities drive value, risk, or threshold decisions.

Why interviewers ask this: Reliability diagrams, the model-specific causes of distortion, and knowing when calibration matters at all show probability outputs treated as measurements.

algorithms

Stacking is worthwhile only when diverse strong models add enough quality to justify operational complexity.

  • Different algorithms, feature views, or training subsets can decorrelate errors, letting a meta-model gain roughly one to three percent over the best base model.
  • That gain may decide a competition, but in production it must cover multiplied latency, serving cost, and maintenance versus one tuned boosting model with better features.
  • Meta-features must be out-of-fold predictions from rows unseen by each base model, or leakage teaches the meta-model to trust overfit scores.

Why interviewers ask this: Out-of-fold meta-features as the correctness condition and the honest production-cost calculus separate practitioners from leaderboard chasers.

A ten-thousand-level categorical feature needs compact encoding with explicit protection against leakage and rare levels.

  • One-hot encoding creates ten thousand sparse columns, wastes memory, and leaves too little data for many tree splits.
  • Better choices are native categorical handling in LightGBM or CatBoost, out-of-fold smoothed target encoding, or leak-free hashing and frequency encoding as simpler fallbacks.
  • I prefer native support, otherwise group the rare tail into an other bucket and use smoothed out-of-fold target statistics so categories cannot memorize labels.

Why interviewers ask this: Out-of-fold computation with smoothing as the target-encoding safety rules shows the candidate has been burned by the standard leak, or learned from those who were.

missing-datasoft-skills

Missing-value handling should match the model and preserve informative absence without leaking collection artifacts.

  • XGBoost and LightGBM can receive NaN directly and learn a default split direction, often using the missingness pattern better than imputation.
  • Linear models and neural networks need explicit imputation, such as medians for skewed numbers or a separate categorical value, plus a binary missing indicator.
  • Missingness can be predictive when nonresponse or sensor silence carries meaning, but collection decisions linked to the outcome can create leakage that disappears in deployment.

Why interviewers ask this: Trees-take-NaN plus indicator columns for imputing models, and the informative-versus-leaky missingness distinction, shows missing data treated as signal engineering.

outliersconcurrency

Outliers require different treatment by model family, and provenance should determine whether they are corrected or modeled.

  • Squared-loss regression, gradient updates, k-means centroids, and fitted scalers can be dominated or distorted by extreme observations.
  • Trees are robust to extreme feature magnitudes because splits use order, but extreme regression targets still distort leaf values under squared loss.
  • I fix or remove proven errors, model real extremes with MAE or Huber loss, log transforms, or RobustScaler, and cap values only when the business explicitly ignores the tail.

Why interviewers ask this: Separating feature-space from target-space robustness and provenance-first triage mirrors the practical decisions real datasets force.

Multicollinearity mainly threatens coefficient interpretation, not predictive performance.

  • Correlated predictors make linear coefficients unstable, inflate standard errors, and can flip signs across samples, with VIF serving as a common diagnostic.
  • Prediction quality often changes little, and trees tolerate correlation, although their importance scores arbitrarily divide credit within the correlated group.
  • For inference I remove or combine variables or use ridge regularization; for prediction I may do nothing, and for interpretation I evaluate correlated features as groups.

Why interviewers ask this: Splitting the answer by goal, inference versus prediction versus interpretation, resolves the perennial confusion this topic generates in practice.

For a new tabular problem, I move from a trivial baseline to linear models and then to tuned gradient boosting.

  • A majority-class or mean predictor defines the floor, while logistic or linear regression reveals whether simple structure already explains most of the signal.
  • Boosting is the main performance candidate because it handles mixed scales, nonlinear thresholds, interactions, and missing values well on modest tabular datasets.
  • I prefer linear models for tiny data or strict interpretability, neural methods for text, images, or sequences, and require any complex model to beat the baseline honestly.

Why interviewers ask this: Baseline-up discipline with the inductive-bias explanation for boosting's tabular dominance shows model selection as reasoning rather than fashion.

Locked questions

  • 21

    Give the sneakiest data leakage cases you know, and how each would show up before production exposes it.

    leakage
  • 22

    Why must preprocessing be fit inside cross-validation folds, and what does sklearn's Pipeline mechanically guarantee?

    cross-validationvalidationci-cd
  • 23

    You build features from user behavior history for a churn model. What does point-in-time correctness mean here, and how do you enforce it?

    churn
  • 24

    Why remove features at all if boosting handles irrelevant ones reasonably well, and how do filter, wrapper, and embedded selection differ?

  • 25

    When does PCA genuinely help a modeling pipeline, when does it hurt, and why should t-SNE or UMAP stay out of the model?

    ci-cd
  • 26

    Describe target encoding done correctly: what makes the naive version leak, and what do out-of-fold computation and smoothing each fix?

  • 27

    Should you manually engineer interaction features for a gradient boosting model, given that trees can learn interactions themselves?

    boosting
  • 28

    StandardScaler, MinMaxScaler, RobustScaler: how do you choose, and for which models is the choice irrelevant?

  • 29

    You need text features in an otherwise tabular churn model, say support ticket contents. What are your options short of a deep model?

    churn
  • 30

    Your training features are computed in SQL overnight, but production scores in real time from application data. What breaks, and what is train-serve consistency?

    sqlconsistency
  • 31

    Your fraud model has 99.4 percent accuracy and the fraud team is furious. What happened, and how do you choose a metric that will not lie?

    monitoring
  • 32

    Precision, recall, and F1 all depend on the classification threshold. What does that mean operationally, and when is F1 the wrong summary?

    classificationevaluation
  • 33

    ROC-AUC versus PR-AUC: why does ROC-AUC look deceptively good on imbalanced problems, and which do you report when?

    evaluationimbalanced
  • 34

    How do you set the classification threshold for a deployed model when the business gives you real costs and capacity constraints?

    classificationdeploymentcapacity
  • 35

    Stratified k-fold, group k-fold, time series split: how do you pick the cross-validation scheme, and what question is CV actually answering?

    cross-validationvalidation
  • 36

    Cross-validation says 0.85, production says 0.70. Enumerate the plausible causes and how you would distinguish them.

    cross-validationvalidation
  • 37

    How do learning curves tell you whether to gather more data, add features, or simplify the model?

  • 38

    After eighty tuning iterations against the validation set, your score improved from 0.81 to 0.84. Why should you distrust that gain, and what protects against it?

    validationiteration
  • 39

    RMSE, MAE, MAPE: how does the choice change what your regression model learns, and where does each mislead?

    evaluation
  • 40

    Model A scores 0.742 in CV, model B scores 0.738. The team wants to ship A. What is wrong with that reasoning, and what would convince you the difference is real?

  • 41

    Why do you insist on a trivial baseline before any real modeling, and what do baselines look like across problem types?

  • 42

    You built a model ranking items for users. Why is AUC the wrong lens, and what do NDCG and MAP actually measure?

    evaluation
  • 43

    Your model's overall metric is strong, but you have not looked at segments. What can hide in the aggregate, and what is your segment evaluation routine?

    aggregationmonitoring
  • 44

    Offline evaluation improved 5 percent, the online A/B test shows nothing. What explains offline-online gaps, and how do you tighten the correlation?

    ab-testingcorrelation
  • 45

    Class weights versus oversampling versus undersampling for an imbalanced classifier: how do they differ mechanically, and what is your default?

    imbalanced
  • 46

    How does SMOTE work, and what are the failure modes that make many practitioners avoid it?

    imbalanced
  • 47

    Which metrics do you actually report for a heavily imbalanced problem, and why is a single scalar never enough?

    imbalancedmonitoring
  • 48

    You oversampled fraud to 30 percent in training, and now the model says a third of transactions are fraudulent. What happened, and how do you repair the probabilities?

    transactions
  • 49

    When does extreme imbalance justify reframing from supervised classification to anomaly detection, and what does that change?

    supervisedclassification
  • 50

    Sketch your approach to a fraud detection model end to end: what makes fraud harder than a standard classification tutorial?

    classification
  • 51

    Why does random search usually beat grid search at the same compute budget, and how do you set the search space?

    grid
  • 52

    How does Bayesian optimization with a tool like Optuna improve on random search, and what do pruning callbacks add?

    bayesianoptimizationcallbacks
  • 53

    You have budget to tune only three or four XGBoost or LightGBM hyperparameters. Which do you pick and why?

    boostinghyperparameters
  • 54

    Describe the full tuning-to-final-model workflow that avoids fooling yourself, from search to the artifact you ship.

    artifacts
  • 55

    How does early stopping work in gradient boosting, and what subtle mistakes does its evaluation set introduce?

    boostingownership
  • 56

    When does hyperparameter tuning stop paying, and where does that effort go instead?

    hyperparameters
  • 57

    You are launching a new ranking model and must prove it beats the incumbent in an A/B test. Walk me through the design decisions.

    ab-testingdesign
  • 58

    The PM asks how many users the model experiment needs. What inputs drive the answer, and what do you do when traffic cannot support it?

    experiments
  • 59

    A colleague checks the model experiment dashboard daily and wants to stop as soon as significance appears. Explain the problem and the legitimate alternatives.

    experiments
  • 60

    You report AUC 0.86 on the test set. The stakeholder asks how sure you are. How do you put honest uncertainty on model metrics?

    evaluationcommunicationmonitoring
  • 61

    Your experiment readout covers twelve metrics across eight segments. What is the multiple comparisons problem here, and how do you handle it without paralysis?

    experimentssoft-skillsmonitoring
  • 62

    Before reading any outcome metrics in your model experiment, what validity checks do you run on the experiment itself?

    experimentsmonitoring
  • 63

    Week one of the new recommendation model shows a strong engagement lift. Why might you distrust it, and how do you separate novelty from real effect?

    engagement
  • 64

    Product wants to know whether the loyalty program causes retention, but there was no experiment, only observational data. What makes this hard, and what would you actually do?

    experimentsretention
  • 65

    Marketing targets customers most likely to buy after receiving a discount. Why is a purchase-probability model the wrong tool, and what does uplift modeling change?

    upliftprobability
  • 66

    When does a Bayesian A/B analysis genuinely help compared to the frequentist version, and where do people abuse it?

    bayesian
  • 67

    When is a multi-armed bandit a better fit than a classic A/B test, and what do you give up?

    ab-testingbandits
  • 68

    Your model wins on the primary metric. Which guardrails should have been watching, and what happens when one degrades?

    guardrailsmonitoring
  • 69

    You test a pricing model in a marketplace and suspect treatment users affect control users. What is interference, and how does it change the design?

    pricingdesign
  • 70

    What goes into a pre-registered analysis plan for a model experiment, and what problem does writing it in advance solve?

    experiments
  • 71

    You need a text classifier for support tickets. Walk me through your escalation from baseline to transformer, with the decision points.

    nlpescalation
  • 72

    What are embeddings, and how would you use pretrained ones for a semantic similarity task without training anything?

    nlp
  • 73

    Why is transfer learning the default for image tasks, and what does the fine-tune-versus-feature-extract decision depend on?

  • 74

    Your image model performs great on the curated training set and poorly on real user uploads. What is happening, and what do augmentations actually buy you?

    train-test
  • 75

    Two annotators labeled your training data and disagree on 20 percent of items. What does this mean for your model and its evaluation?

    conflict
  • 76

    A stakeholder reads p equals 0.03 as a 97 percent chance the effect is real. Correct them, and state what a p-value actually is.

    hypothesis-testingcommunicationstakeholder-management
  • 77

    What does a 95 percent confidence interval actually mean, and what is the most common wrong interpretation?

    confidence-intervals
  • 78

    Define Type I and Type II errors in a fraud-alert context, and explain how you trade them off.

    hypothesis-testingalerting
  • 79

    Why does the Central Limit Theorem matter for the A/B tests and confidence intervals you build daily?

    confidence-intervalsclttesting
  • 80

    You compare average order value between two groups and the distribution is heavily right-skewed with outliers. Is a t-test still valid, and what are your options?

    distributionsoutliershypothesis-testing
  • 81

    When do you reach for a chi-square test, and what are its assumptions and limits?

    hypothesis-testing
  • 82

    Sales rose in regions where you increased ad spend. Why is that not proof the ads worked, and what is Simpson's paradox?

    paradoxes
  • 83

    With ten million users your test hits p less than 0.001 on a 0.05 percent conversion lift. Should you ship it?

  • 84

    You have numeric, categorical, and text columns feeding one model. How do you structure the preprocessing so it stays leak-free and deployable?

    schemadeployment
  • 85

    You need a preprocessing step sklearn does not ship. How do you build it so it plugs into a pipeline correctly?

    ci-cd
  • 86

    How do you tune a hyperparameter that lives inside a pipeline step, and why might you wrap the whole search in another CV loop?

    hyperparametersci-cd
  • 87

    Your deployed model's accuracy is slowly decaying. Distinguish data drift from concept drift and how you would tell which you have.

    mlopsdeploymentiac
  • 88

    What do you actually monitor for a model in production beyond its accuracy?

    monitoring
  • 89

    When do you serve predictions in nightly batches versus real time, and what changes between them?

    batch
  • 90

    How do you decide how often to retrain a model, and what triggers an off-schedule retrain?

  • 91

    You retrained the model and it looks better offline. How do you roll it out without risking production?

  • 92

    A model in production is making a decision you cannot explain, and you need to reproduce exactly how it was trained. What must have been versioned?

  • 93

    How do you explain a model's output to a non-technical executive who has to act on it?

    communication
  • 94

    A PM asks you to build a machine learning model for a problem you suspect does not need one. How do you handle it?

    mlsoft-skills
  • 95

    An analyst insists on adding a feature you believe leaks future information. The team is under deadline pressure. What do you do?

    estimation
  • 96

    A stakeholder says predict which customers will churn but gives no definition or timeframe. How do you turn that into a real project?

    churncommunicationstakeholder-management
  • 97

    Tell me about a model or project that did not work out, and what you took from it.

    story
  • 98

    You have a backlog of ten possible models and features but time for two. How do you prioritize?

    backlogprioritization
  • 99

    Midway through a project you discover the core dataset has serious quality problems. How do you proceed?

  • 100

    How do you work with data and ML engineers so a model actually ships and stays healthy, rather than dying in a notebook?