Skip to content

Machine Learning Engineer interview questions

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

See a Machine Learning Engineer resume example

Practice with flashcards

Spaced repetition · Hunter Pass

Questions

bias-variancedispersion

For squared error, expected prediction error can be viewed as bias squared, variance, and irreducible noise.

  • Bias measures systematic error from assumptions that are too restrictive, such as fitting a linear model to a strongly nonlinear relationship.
  • Variance measures how much the fitted model would change if it were trained on another sample from the same population.
  • Increasing model flexibility often lowers bias but raises variance, so validation estimates the balance that generalizes best.
  • Irreducible noise comes from randomness or missing information and cannot be removed by choosing a more complex model.

Why interviewers ask this: The interviewer is checking whether you can connect model complexity to the components of out-of-sample error.

learning-theory

Empirical risk is average loss on observed samples, while expected risk is average loss over the unknown data distribution.

  • Training directly minimizes empirical risk because the true population distribution is unavailable.
  • A flexible model can drive empirical risk down without reducing expected risk if it fits sample-specific noise.
  • Validation data estimates expected risk on unseen observations drawn under similar conditions.
  • Regularization and capacity control restrict the solutions considered during empirical risk minimization.

Why interviewers ask this: A strong answer explains why minimizing training loss alone does not guarantee generalization.

optimization

L1 and L2 add different weight penalties to the data loss, changing which parameter solutions the optimizer prefers.

  • L1 adds the sum of absolute coefficients and has a sharp corner at zero, so some coefficients can become exactly zero.
  • L2 adds the sum of squared coefficients and continuously shrinks large weights without usually eliminating them.
  • The regularization strength trades training fit for lower complexity and is selected on validation data.
  • Features should usually be scaled first because the penalty acts directly on coefficient magnitude.

Why interviewers ask this: The interviewer expects more than definitions, including the geometry, scaling requirement, and effect on fitted weights.

regularization

Elastic net combines L1 sparsity with L2 stability and is useful when many predictors are correlated.

  • Pure L1 may select one feature from a correlated group and discard the others unpredictably.
  • The L2 component encourages correlated predictors to enter or leave the model more smoothly as a group.
  • The L1 component can still remove weak features and produce a compact model.
  • Both total penalty strength and the L1-to-L2 ratio require validation-based tuning.

Why interviewers ask this: A strong answer connects elastic net to correlated features rather than describing it only as a formula.

regularization

Early stopping limits effective model capacity by ending optimization before the model fits training noise.

  • Training loss may keep falling after validation loss starts rising, which signals deteriorating generalization.
  • The best checkpoint is selected by a validation metric with a patience window to avoid reacting to random fluctuations.
  • It is especially common for boosting and neural networks whose capacity grows with additional iterations.
  • The validation set used for stopping is part of model selection and must not also serve as the final test set.

Why interviewers ask this: The interviewer checks whether you understand both the regularization effect and the evaluation discipline around early stopping.

neural-nets

Dropout randomly masks activations during training so the network cannot depend too heavily on specific paths.

  • Each training step samples a different thinned network, which discourages fragile co-adaptations between units.
  • At inference, all units are used with scaling handled so expected activation magnitudes remain consistent.
  • A higher dropout rate increases regularization but can cause underfitting when too much signal is removed.
  • Dropout is less universally helpful in architectures that already use strong normalization, data augmentation, or large datasets.

Why interviewers ask this: A strong answer covers training and inference behavior as well as the capacity tradeoff.

neural-netsnormalizationbatch

Batch normalization standardizes intermediate activations using batch statistics and then learns a scale and shift.

  • It can smooth optimization and permit larger learning rates by keeping activation distributions better conditioned.
  • Training uses statistics from each mini-batch, while inference uses accumulated running statistics.
  • Very small or nonrepresentative batches can make those estimates noisy and reduce effectiveness.
  • Its stochastic batch statistics can add some regularization, but normalization is primarily an optimization aid.

Why interviewers ask this: The interviewer checks whether you distinguish batch normalization's mechanics at training and inference from simplified claims about covariate shift.

calibration

A calibrated classifier assigns probabilities that match observed outcome frequencies.

  • Among predictions near 0.8, roughly 80 percent should be positive when calibration is good.
  • Ranking metrics such as ROC-AUC can be strong even when predicted probabilities are poorly calibrated.
  • Reliability diagrams and the Brier score help assess calibration across probability ranges.
  • Platt scaling or isotonic regression can recalibrate scores using held-out data.

Why interviewers ask this: A strong answer separates probability quality from ranking quality and names valid evaluation methods.

classificationthresholding

A classification threshold should reflect error costs, class prevalence, and the operational objective rather than defaulting to 0.5.

  • Lowering the threshold usually raises recall while increasing false positives.
  • Raising it usually improves precision while missing more true positives.
  • The threshold must be chosen on validation data with a metric or cost function tied to the intended decision.
  • Probability calibration matters when the threshold represents an explicit risk or expected-value boundary.

Why interviewers ask this: The interviewer evaluates whether you can turn probability scores into decisions using explicit tradeoffs.

decision-making

Both are proper scoring rules that reward accurate probabilities, but they penalize errors differently.

  • Log loss uses the negative log probability of the true class and heavily punishes confident incorrect predictions.
  • The Brier score is mean squared error between predicted probabilities and binary outcomes.
  • Both assess information that accuracy discards when it reduces probabilities to hard labels.
  • Scores should be compared against a prevalence-based baseline and interpreted with class balance in mind.

Why interviewers ask this: A strong answer explains why probability metrics provide a different signal from thresholded classification metrics.

evaluation

A precision-recall curve is often more informative when the positive class is rare and positive performance is the main concern.

  • ROC uses false positive rate, whose denominator includes many negatives and can make performance look strong under severe imbalance.
  • Precision directly reflects how many predicted positives are correct, so it exposes false-positive burden.
  • Recall shows how much of the positive class is recovered as the threshold changes.
  • PR-AUC depends on prevalence, so comparisons require datasets with comparable class distributions.

Why interviewers ask this: The interviewer checks whether you understand how class prevalence changes metric interpretation.

monitoring

Macro, micro, and weighted averages combine per-class results with different priorities.

  • Macro averaging gives every class equal weight, so rare-class performance has the same influence as common-class performance.
  • Micro averaging pools all decisions before computing the metric, which emphasizes frequent classes.
  • Weighted averaging takes the per-class metric weighted by class support and can hide weak minority classes.
  • The appropriate average depends on whether each class, each example, or observed prevalence should drive the result.

Why interviewers ask this: A strong answer can select an averaging method based on the meaning of the product objective.

cross-validationestimationvalidation

The number of folds and dependence between splits determine much of a cross-validation estimate's bias, variance, and cost.

  • More folds train on a larger fraction of data, reducing pessimistic bias but increasing compute.
  • Fold scores are correlated because their training sets overlap, so their standard deviation is not a simple confidence interval.
  • Repeated cross-validation reveals sensitivity to random partitioning but does not fix a mismatched splitting strategy.
  • Grouped, temporal, or stratified structure matters more than choosing a conventional value of k.

Why interviewers ask this: The interviewer expects you to reason about what cross-validation estimates, not just recite the k-fold procedure.

cross-validationvalidation

Nested cross-validation separates hyperparameter selection from performance estimation when data is limited.

  • The inner loop tunes hyperparameters using only the outer training portion.
  • The outer loop evaluates the entire selection procedure on data untouched by the inner loop.
  • Reporting the best inner score is optimistically biased because many configurations were compared.
  • Nested validation costs substantially more compute but gives a cleaner estimate before final retraining.

Why interviewers ask this: A strong answer identifies model-selection bias and explains how the two validation loops prevent it.

cross-validationvalidation

Grouped cross-validation is required when observations from the same entity are dependent and must stay in one fold.

  • Rows from one user, patient, device, or document source can share patterns that a model could memorize.
  • Random row splitting leaks those entity-specific patterns into both training and validation data.
  • GroupKFold keeps each group entirely on one side of a split while rotating held-out groups.
  • Stratified group methods may be needed when both group isolation and class balance matter.

Why interviewers ask this: The interviewer checks whether you recognize dependence between rows that invalidates ordinary random splitting.

cross-validationvalidation

Walk-forward validation preserves time order by training on the past and evaluating on a later interval.

  • Expanding windows keep all earlier observations, while rolling windows keep a fixed amount of recent history.
  • Multiple cutoffs reveal whether quality changes across different market, seasonal, or behavioral periods.
  • Any feature, target, and preprocessing statistic must be available as of each historical prediction time.
  • Random folds are inappropriate when future observations can reveal information about earlier ones.

Why interviewers ask this: A strong answer connects temporal validation mechanics to point-in-time data availability.

leakagevalidation

Preprocessing leaks information when a transformation learns from validation rows before those rows are evaluated.

  • Scaling on the full dataset exposes validation means and variances to the training process.
  • Imputation, feature selection, PCA, and target encoding can leak for the same reason.
  • Each transformation must be fitted inside the training portion of every fold and only applied to its validation portion.
  • A scikit-learn Pipeline enforces this order when passed to cross-validation or search utilities.

Why interviewers ask this: The interviewer checks whether you treat preprocessing as learned model state rather than a harmless preliminary step.

missing-data

MCAR, MAR, and MNAR describe what the probability of a missing value depends on.

  • MCAR means missingness is unrelated to observed or unobserved values, which is a strong and uncommon assumption.
  • MAR means missingness can be explained by other observed variables, making conditional imputation more defensible.
  • MNAR means missingness depends on the missing value itself or another unobserved cause.
  • No imputation method can fully resolve MNAR from the observed table alone without assumptions or additional data.

Why interviewers ask this: A strong answer connects missingness assumptions to the limits of imputation rather than listing acronyms.

feature-engineering

Target encoding replaces a category with a target statistic, producing compact signal but creating serious leakage risk.

  • Rare categories have noisy estimates, so smoothing toward the global mean reduces variance.
  • Training rows need out-of-fold or leave-one-out encodings so their own targets do not define their features.
  • Unseen categories require a fallback such as the global mean or a learned prior.
  • The encoding must be recomputed within every validation split and respect time order when data is temporal.

Why interviewers ask this: The interviewer evaluates whether you know how to gain signal from high cardinality without leaking labels.

feature-engineering

Interaction and polynomial features let a simple model represent relationships beyond independent linear effects.

  • An interaction term allows one feature's effect to depend on another feature's value.
  • Polynomial terms can approximate curved relationships while retaining a linear estimator in the expanded feature space.
  • Expansion grows dimensionality rapidly and can increase multicollinearity, variance, and computation.
  • Scaling, regularization, and domain-guided selection keep the expanded representation manageable.

Why interviewers ask this: A strong answer explains both the added expressive power and the resulting statistical cost.

Locked questions

  • 21

    How do filter, wrapper, and embedded feature-selection methods differ?

    feature-engineering
  • 22

    How does PCA derive principal components?

    components
  • 23

    What is the curse of dimensionality?

    dimensionality
  • 24

    What assumptions matter when interpreting linear regression coefficients?

    regression
  • 25

    How do odds and the decision boundary arise in logistic regression?

    regression
  • 26

    How does a decision tree choose a split?

    trees
  • 27

    How do pre-pruning and post-pruning control decision-tree complexity?

    model-compressionalgorithms
  • 28

    Why does bagging reduce variance?

    dispersion
  • 29

    How do random forests decorrelate trees, and what is out-of-bag evaluation?

    ensembles
  • 30

    How is gradient boosting related to fitting residuals and loss gradients?

    boosting
  • 31

    What regularization mechanisms does XGBoost provide?

    boostingregularization
  • 32

    How does LightGBM's leaf-wise growth differ from level-wise tree growth?

    gradient-boosting
  • 33

    How do stacking and blending combine models without leakage?

    ensemblesleakage
  • 34

    Why does diversity matter in an ensemble?

    ensembles
  • 35

    How do the C and gamma parameters affect an RBF support vector machine?

    svm
  • 36

    What are the main tradeoffs of k-nearest neighbors?

    knn
  • 37

    How do Gaussian, multinomial, and Bernoulli naive Bayes differ?

    bayesian
  • 38

    What assumptions and limitations does k-means clustering have?

    clustering
  • 39

    How does a Gaussian mixture model differ from k-means?

    clustering
  • 40

    How does DBSCAN identify clusters, and what are its tradeoffs?

    clustering
  • 41

    How do scikit-learn Pipeline and ColumnTransformer support reliable feature processing?

    schemaconcurrencyci-cd
  • 42

    What contract should a fitted feature transformer satisfy?

    nlp
  • 43

    What are the conceptual differences between batch and streaming feature pipelines?

    streamingbatchci-cd
  • 44

    Why is point-in-time correctness essential when building training features?

    point-in-time
  • 45

    What should data and feature contracts define for an ML pipeline?

    ci-cd
  • 46

    What must be captured to make an ML experiment reproducible?

    reproducibilityexperiments
  • 47

    How does automatic differentiation compute gradients in PyTorch or TensorFlow?

    competitivepytorch
  • 48

    How do SGD with momentum and Adam differ?

    optimization
  • 49

    What causes vanishing or exploding gradients, and how do initialization and architecture help?

    architecture
  • 50

    How would you compare linear models, tree ensembles, and neural networks for tabular data?

    neural-netsensembles
  • 51

    A PyTorch model's training loss plateaus early and remains high. How would you debug it?

    pytorch
  • 52

    Training occasionally produces NaN loss after several thousand steps. How would you find the cause?

  • 53

    A model performs well on random validation but poorly on the latest month of data. How would you investigate?

    validation
  • 54

    After adding strong regularization, both training and validation quality fall. What would you do?

    regularizationvalidation
  • 55

    Validation loss is highly unstable between epochs even though training loss is smooth. How would you diagnose it?

    validation
  • 56

    How would you prevent point-in-time leakage when building features from a feature store?

    leakagepoint-in-timemlops
  • 57

    Labels arrive weeks late and are sometimes backfilled. How would you build reliable training data?

    backfill
  • 58

    You have millions of weak labels from heuristics and a small set of expert labels. How would you use them?

    weak-supervision
  • 59

    The business changes the definition of a positive label midway through the year. How would you handle existing models and datasets?

  • 60

    Your training data comes from users who opted into a feature, but the model will serve all users. What would you do?

  • 61

    An entity can appear through several accounts and devices. How would you check for leakage across splits?

    leakage
  • 62

    A fraud team can review only 500 alerts per day. How would you train and evaluate the model?

    decision-makingalerting
  • 63

    A risk model ranks cases well but its predicted probabilities are poorly calibrated. How would you address that?

    calibration
  • 64

    How would you choose offline metrics for a recommendation model that shows ten items?

    monitoring
  • 65

    Underpredicting delivery time is more costly than overpredicting it. How would you model and evaluate this?

    decision-making
  • 66

    A more accurate model is difficult to explain and misses the latency target. How would you choose between it and a simpler model?

    latency
  • 67

    For a new tabular classification problem, how would you decide between gradient boosting and a neural network?

    boostingneural-netsclassification
  • 68

    An ensemble improves AUC by 0.3 percentage points but triples serving cost. Would you deploy it?

    evaluationensemblesdeployment
  • 69

    How would you validate a demand-forecasting model before replacing the current one?

    validation
  • 70

    Overall validation performance is stable, but one customer segment degrades sharply. What would you do?

    validationperformance
  • 71

    Production feature distributions changed after a marketing campaign. How would you decide whether the model needs retraining?

    retrainingdistributions
  • 72

    A feature-drift alert fires, but model quality remains stable. How would you respond?

    alertingiac
  • 73

    Model quality drops, but monitored input distributions look unchanged. What would you investigate?

    distributionsmonitoring
  • 74

    How would you monitor a new model when ground-truth labels will not arrive for two months?

    monitoring
  • 75

    Delayed labels are joined to predictions, but the reported metric changes every time the dashboard refreshes. How would you fix it?

    monitoring
  • 76

    How would you decide between scheduled retraining and event-triggered retraining?

    retraining
  • 77

    What gates would you require before an automatically retrained model can replace production?

    retraining
  • 78

    An hourly feature pipeline is sometimes late, so the online model receives stale values. How would you handle it?

    ci-cd
  • 79

    The same model artifact scores differently in batch training code and the online service. How would you debug training-serving skew?

    batchmodel-servingartifacts
  • 80

    How would you verify consistency between offline and online feature-store values?

    consistency
  • 81

    An Airflow training DAG retries after writing half of its outputs. How would you prevent corrupted or duplicated artifacts?

    airflowartifacts
  • 82

    A Spark feature job is slow and some executors run out of memory while most finish quickly. How would you diagnose it?

    memoryspark
  • 83

    Kafka events used for online features can arrive late, out of order, or more than once. How would you make the features reliable?

    kafka
  • 84

    Prediction latency rises after a model release, but CPU utilization looks normal. How would you investigate?

    latency
  • 85

    After converting a PyTorch model to ONNX Runtime, a small share of predictions changes significantly. What would you do?

    serving-runtimespytorch
  • 86

    How would you design a canary release for a new real-time model?

    designdeployment-strategies
  • 87

    When would you use shadow deployment, and what would you measure?

    deployment
  • 88

    A new model requires a changed feature schema. How would you preserve rollback compatibility?

    schemarollback
  • 89

    How would you design an A/B test for a new ranking model?

    ab-testingdesign
  • 90

    An A/B test improves the primary metric overall but harms new users. What would you recommend?

    ab-testingmonitoring
  • 91

    An online lift is strong in the first week and disappears in the second. How would you analyze it?

    ab-testing
  • 92

    A candidate model wins offline but loses to the baseline online. How would you close the offline-online gap?

    offline-online
  • 93

    A recommender trains only on items shown by the previous model. How would you address the feedback loop?

    feedback
  • 94

    A risk model's decisions change the labels later used for retraining. How would you prevent a self-reinforcing bias?

    retraining
  • 95

    Production scores suddenly collapse to nearly one constant value. How would you handle the incident?

    incidents
  • 96

    A model makes a high-confidence prediction that a domain expert says is clearly wrong. How would you investigate?

  • 97

    Product wants to optimize click-through rate, while the trust team worries about harmful recommendations. How would you define success?

    optimization
  • 98

    You have one week to improve a model. How would you decide between collecting better data and tuning the model?

  • 99

    A teammate reports a large model improvement in a pull request. What would you review before approving it?

    code-review
  • 100

    Describe how you would run a postmortem after a model-quality incident.

    incidents