Skip to content

Cookies on Jobverse

We use cookies that are needed to sign you in and keep the site working. With your permission we’d also use an analytics cookie to count job views, and Google advertising cookies to show ads. The site works the same whatever you choose. Read the Cookie Policy.

Jobverse
Sign in

AI/ML Engineer Top 100 Interview Questions

100 AI/ML engineer interview questions with structured answers, comparison tables, flow diagrams, worked calculations and runnable code. Covers problem framing, classical algorithms, clustering, recommender systems, forecasting, text, evaluation, applied deep learning and MLOps, from fundamentals to system design.

100 questions

Questions 1-20 of 100

  1. Q1.What does an AI/ML engineer do across the lifecycle of a model?

    An AI/ML engineer turns a business problem into a working model in production and keeps it working: from framing the problem and preparing data, through training and evaluation, to deployment, monitoring and retraining.

    flowchart LR
      A["Frame the problem"] --> B["Collect and label data"]
      B --> C["Build features"]
      C --> D["Train and evaluate"]
      D --> E["Deploy and serve"]
      E --> F["Monitor"]
      F -->|drift or new data| B

    Responsibilities at each stage:

    • Framing: agree with stakeholders on the decision the model supports, the target to predict and how success is measured.
    • Data: build reliable pipelines, check quality, and design labeling where labels are missing.
    • Modeling: establish baselines, engineer features, train candidates and evaluate them honestly on held-out data.
    • Deployment: package the model with its preprocessing, and serve it in batch or in real time within latency and cost limits.
    • Monitoring: track data drift, prediction quality and business impact, and trigger retraining.
    • Governance: record data, code and model versions, document limitations, and check fairness and privacy.

    Compared with a data scientist, the role leans toward production engineering. Compared with a software engineer, it adds statistics, experimentation and data quality.

  2. Q2.How do you translate a business goal into a machine learning objective and metric?

    Start from the decision the business wants to improve, then define exactly what to predict, for whom, when, and how a better prediction changes an outcome you can measure.

    1. Name the decision: who acts on the prediction, and what do they do differently?
    2. Define the target: a precise, measurable label, such as "cancels within 30 days", not "is unhappy".
    3. Define the unit and timing: one prediction per customer per week, made with data available at that moment.
    4. Choose an offline metric that reflects how the prediction is used. If only the top 5% get an offer, measure precision in the top 5%, not overall accuracy.
    5. Choose the online metric: the business outcome, such as retention rate, measured in a controlled experiment.
    6. Set guardrails: metrics that must not get worse, such as offer costs or complaint rates.
    7. Set a baseline: the current rule or a simple model the new one must beat.

    The most common failure is a well-optimized model for the wrong target. Ten minutes spent agreeing on the label saves months of work on the wrong one.

    Example

    Framing "reduce customer churn" for a subscription business:

    1. Decision: the retention team calls 500 customers a week with a discount offer.
    2. Target: the subscription is canceled within 30 days of the prediction date.
    3. Unit: one score per active customer every Monday, using data up to Sunday night.
    4. Offline metric: precision among the 500 highest-scored customers, since only they are called.
    5. Online metric: the 60-day retention rate of called customers against a randomly held-out group of high-risk customers who were not called.
    6. Guardrail: discount cost per retained customer must stay below the customer's expected margin.
    7. Baseline: the current rule, which calls customers whose usage fell by half.
  3. Q3.What is the bias-variance trade-off?

    A model's expected error comes from three sources: bias from assumptions too simple to capture the pattern, variance from being too sensitive to the particular training sample, and noise that no model can remove. Making a model more flexible lowers bias but raises variance.

    • expected error = bias² + variance + irreducible noise
    High bias, underfittingHigh variance, overfitting
    High training errorLow training error
    High validation error, close to training errorValidation error much higher than training error
    Cause: model too simple, weak featuresCause: model too complex for the data size
    Fix: more features, a more flexible model, less regularizationFix: more data, regularization, a simpler model, ensembles

    Using it in practice:

    • Compare training and validation error to tell which problem you have before changing anything.
    • Regularization, depth limits and early stopping are dials that move a model along the trade-off.
    • Bagging mainly reduces variance; boosting mainly reduces bias.

    Very large neural networks can generalize well despite enormous capacity, so treat the trade-off as a diagnostic guide rather than a strict law.

  4. Q4.How does k-fold cross-validation work, and how do you choose k?

    K-fold cross-validation splits the data into k equal folds, trains k models each using k − 1 folds, and validates each on the remaining fold. Averaging the k scores gives a more reliable estimate than a single split, and the spread shows how stable it is.

    1. Shuffle the data, unless order matters, and split it into k folds.
    2. For each fold, train on the other folds and score on this one.
    3. Report the mean and standard deviation of the k scores.
    4. Retrain the final model on all the data once choices are made.

    How to choose k:

    • 5 or 10 is the usual choice, balancing estimate quality against training cost.
    • Small datasets benefit from larger k, since each model sees more training data.
    • Expensive models may only afford k = 3, or a single hold-out set for very large data.

    Rules that keep it honest:

    • Fit preprocessing, such as scaling or encoding, inside each fold, or information leaks into validation.
    • Use grouped folds when rows from one customer or patient must not be split.
    • Use time-ordered splits for forecasting.
    • Keep a separate test set untouched for the final estimate, because the cross-validation score was used to make choices.

    Example

    5-fold cross-validation on 1,000 rows:

    1. Each fold holds 200 rows. Each model trains on 800 rows and validates on 200, five times.
    2. Fold accuracies are 0.81, 0.84, 0.79, 0.83 and 0.82.
    3. The mean is (0.81 + 0.84 + 0.79 + 0.83 + 0.82) / 5 = 0.818, with a sample standard deviation of about 0.019.
    4. A competing model that scores 0.825 is within one standard deviation, so the difference is not convincing on its own.
    5. With 10 folds, each model would train on 900 rows, at twice the training cost.
  5. Q5.How do learning curves show whether more data will help?

    A learning curve plots training and validation scores against the amount of training data. The gap between the curves, and whether validation is still improving, tells you whether to collect more data, add model capacity or improve the features.

    Both scores low and closeLarge gap, validation still risingLarge gap, validation flatBoth high and converged
    High bias: underfittingHigh variance that more data can reduceOverfitting that more data barely helpsNear the limit for this data and features
    Add features or a more flexible model; more data will not help muchCollect more data, regularize, augmentRegularize or simplify; revisit featuresImprove features or labels, not the row count

    How to build one:

    1. Train on increasing subsets, such as 10%, 20% and so on up to 100% of the training data.
    2. Evaluate each on the same validation set, ideally averaging over several random subsets.
    3. Plot both curves and read the trend at the right-hand end.

    Learning curves turn "should we label 50,000 more examples?" from a guess into an estimate. A flat validation curve says the money is better spent elsewhere.

  6. Q6.What is the curse of dimensionality?

    The curse of dimensionality describes how data becomes sparse as the number of features grows: the volume of the feature space grows exponentially, so a fixed amount of data covers it ever more thinly and distances between points become less meaningful.

    Effects on machine learning:

    • Neighborhoods stop being local: to capture a fixed share of the data, a "neighborhood" must span most of each feature's range.
    • Distances concentrate: the nearest and farthest points end up at almost the same distance, which weakens nearest-neighbor methods and clustering.
    • More data is needed: the samples required to cover the space grow very fast with dimensions.
    • Overfitting gets easier: with many features and few rows, some feature will separate the training data by chance.

    How to counter it:

    1. Feature selection to remove irrelevant and redundant features.
    2. Dimensionality reduction, such as principal components or learned embeddings.
    3. Regularization that penalizes using many features.
    4. Models that cope well, such as tree ensembles and linear models with regularization, rather than raw distance-based methods.

    Real data usually lies near a much lower-dimensional structure. That is why high-dimensional problems are solvable at all.

    Example

    How large a neighborhood must be to contain 10% of uniformly spread data, measured as the share of each feature's range it must span:

    1. With 1 feature: 0.1^(1/1) = 0.10, so 10% of the range.
    2. With 2 features: 0.1^(1/2) ≈ 0.316, so about 32% of each range.
    3. With 10 features: 0.1^(1/10) ≈ 0.794, so about 79% of each range.
    4. With 100 features: 0.1^(1/100) ≈ 0.977, so nearly the whole range of every feature.

    In 100 dimensions, the "nearest 10%" of points is barely more local than the whole dataset, which is why plain nearest-neighbor methods degrade.

  7. Q7.How do generative and discriminative models differ?

    A discriminative model learns the boundary between classes directly, the probability of a label given the inputs. A generative model learns how the data itself is distributed, often for each class, so it can also generate new examples and compute how likely an input is.

    DiscriminativeGenerative
    Learns P(label given features)Learns P(features), often P(features given label) and P(label)
    Examples: logistic regression, tree ensembles, most classifiersExamples: probabilistic classifiers with independent features, mixture models, autoencoders that sample
    Usually more accurate with plenty of dataOften less accurate with plenty of data
    Can overfit small dataStrong assumptions can help on small data
    Handles missing inputs poorlyHandles missing inputs naturally
    Cannot create new samplesCan create new samples

    When to use which:

    • Use discriminative models for most prediction tasks with enough labeled data, since they focus all capacity on the decision.
    • Use generative models when you need to generate data, detect unusual inputs by their low likelihood, handle missing features, or learn from very little data with sensible assumptions.

    Modern generative models for images and text are generative in this same sense: they learn the distribution of the data well enough to sample from it.

  8. Q8.How do you decide between a simple interpretable model and a complex one?

    Start with the simplest model that could work, and move to a more complex one only when it gives a meaningful gain that is worth its costs in explainability, maintenance, latency and risk.

    Simple model, such as linear or a small treeComplex model, such as a large ensemble or deep network
    Directly readableNeeds explanation tools, still approximate
    Needs less dataNeeds more data
    Lower accuracy on complex patternsHigher accuracy ceiling
    Easy to spot wrong behaviorHard to debug
    Low latency and costHigher latency and cost
    Fits regulated lending, insurance and health wellMay need extra justification in regulated uses

    Questions that decide it:

    1. How much does the extra accuracy matter in business terms, such as fraud caught or revenue?
    2. Must decisions be explained to customers, regulators or doctors?
    3. How stable is the data? Simple models often degrade more gracefully when patterns shift.
    4. Who will maintain it, and how much monitoring can they support?

    A strong simple baseline also makes the complex model's gain measurable. If the complex model wins by 0.3% on a metric nobody acts on, ship the simple one.

  9. Q9.What assumptions does linear regression make, and what happens when they break?

    Linear regression assumes the target is a linear function of the features plus independent, evenly spread errors. Predictions can still be useful when assumptions bend, but coefficients, confidence intervals and p-values become unreliable.

    LinearityIndependent errorsConstant error variance
    Each feature's effect is a straight lineOne error says nothing about anotherErrors are equally spread at all levels
    If broken: systematic errors, poor fitIf broken: overconfident intervals, common in time seriesIf broken: unreliable intervals and tests
    Fix: transform features, add interactions, use a nonlinear modelFix: time series models, clustered errorsFix: transform the target, weighted regression
    Normally distributed errorsNo strong collinearity
    Needed for exact small-sample inferenceFeatures are not near-copies of each other
    If broken: intervals and p-values are offIf broken: unstable, uninterpretable coefficients
    Fix: larger samples, bootstrap intervalsFix: drop or combine features, regularize

    How to check:

    • Plot residuals against predictions: curves suggest non-linearity, and a funnel shape suggests changing variance.
    • Plot residuals over time to spot dependence.
    • Compute variance inflation factors for collinearity.

    Outliers and high-leverage points can also drag the line. Inspect the largest residuals before trusting any coefficient.

  10. Q10.How do you interpret the coefficients of a logistic regression model?

    Logistic regression is linear in the log-odds of the outcome. Each coefficient is the change in log-odds for a one-unit increase in its feature, holding the others fixed, and its exponential is an odds ratio.

    • log(p / (1 − p)) = b0 + b1·x1 + ... + bn·xn
    • odds ratio for feature i = e^bi

    How to read them:

    • A positive coefficient raises the odds of the outcome; a negative one lowers them.
    • An odds ratio of 2 doubles the odds per unit; 0.5 halves them.
    • The effect on probability is not constant: the same change in odds moves a 50% probability far more than a 2% one.

    Cautions:

    • Units matter: a coefficient per dollar looks tiny next to one per thousand dollars. Standardize features to compare their importance.
    • Correlated features split and destabilize coefficients, so interpret them only with low collinearity.
    • Regularization shrinks coefficients toward zero, which biases them for interpretation.
    • Coefficients show association, not causation, unless the data comes from a controlled experiment.

    Example

    A churn model has a coefficient of −0.69 for "on the annual plan" and −0.05 for "months as a customer":

    1. Annual plan: e^−0.69 ≈ 0.50, so annual-plan customers have about half the odds of churning.
    2. In probability terms: a monthly customer with a 20% churn probability has odds of 0.2 / 0.8 = 0.25. Halving gives about 0.125, which is a probability of 0.125 / 1.125 ≈ 11.1%.
    3. Tenure: e^−0.05 ≈ 0.951, so each extra month lowers churn odds by about 4.9%.
    4. A year of extra tenure multiplies the odds by 0.951^12 ≈ 0.55, a similar effect to switching to the annual plan.
  11. Q11.How does k-nearest neighbors make a prediction, and what are its weaknesses?

    K-nearest neighbors stores the training data and predicts a new point by finding the k closest training points: it takes a majority vote for classification or an average for regression. There is no training step; all the work happens at prediction time.

    Key points:

    • Distance matters: straight-line distance is common, so features must be scaled, or a feature measured in thousands dominates one measured in single digits.
    • k controls the trade-off: small k follows noise, which is high variance; large k blurs real boundaries, which is high bias. Choose it by cross-validation.
    • Weighted votes, where closer neighbors count more, often help.

    Weaknesses:

    • Slow predictions on large datasets, since each one compares against all stored points. Approximate neighbor indexes help.
    • Memory grows with the training data.
    • High dimensions make distances less meaningful.
    • Irrelevant features add noise to every distance.
    • Imbalanced classes let the majority class win votes.

    It remains a useful baseline and is natural for recommendations and similarity search, where "find similar items" is the goal itself.

    Example

    A small classifier showing how k changes a prediction near a stray training point:

    import math
    from collections import Counter
    
    TRAIN = [
        ((1.0, 1.2), "small"), ((1.4, 0.9), "small"), ((0.8, 1.0), "small"),
        ((4.0, 4.2), "large"), ((4.5, 3.8), "large"), ((3.9, 4.6), "large"),
        ((2.6, 2.4), "large"),
    ]
    
    
    def predict(point: tuple, k: int) -> str:
        ranked = sorted((math.dist(features, point), label) for features, label in TRAIN)
        votes = Counter(label for _, label in ranked[:k])
        return votes.most_common(1)[0][0]
    
    
    print(predict((2.2, 2.0), k=1))  # large
    print(predict((2.2, 2.0), k=3))  # small
    print(predict((3.0, 3.0), k=3))  # large

    With k = 1, the single "large" point at (2.6, 2.4) decides alone. With k = 3, two nearby "small" points outvote it, which is the smoothing that larger k buys.

  12. Q12.How does a probabilistic classifier that assumes independent features work?

    This classifier, often called the naive probabilistic classifier, scores each class by multiplying the class's prior probability by the probability of each observed feature given that class. It assumes the features are independent within a class, which is rarely true but makes training and prediction extremely cheap.

    • score(class) = P(class) × P(feature1 given class) × ... × P(featureN given class)
    • Pick the class with the highest score.

    Key details:

    • Training is counting: class frequencies and feature frequencies per class, in one pass over the data.
    • Add-one smoothing: add 1 to every count, so a word never seen with a class does not make its probability zero.
    • Use log probabilities: sum logs instead of multiplying many small numbers, which would underflow to zero.

    Strengths and weaknesses:

    • Fast, works well with little data and many features, and is a strong baseline for text classification.
    • Its probabilities are poorly calibrated, often too extreme, because the independence assumption counts correlated evidence twice.
    • Correlated features, such as repeated phrases, distort its scores.

    Example

    A spam filter trained on six short messages, with add-one smoothing:

    import math
    from collections import Counter
    
    TRAIN = [
        ("win money now", "spam"), ("win a free prize", "spam"), ("free money offer", "spam"),
        ("meeting moved to friday", "normal"), ("lunch on friday", "normal"), ("project meeting notes", "normal"),
    ]
    word_counts = {"spam": Counter(), "normal": Counter()}
    class_counts = Counter()
    for text, label in TRAIN:
        class_counts[label] += 1
        word_counts[label].update(text.split())
    vocabulary = {word for counts in word_counts.values() for word in counts}
    
    
    def log_score(text: str, label: str) -> float:
        total_words = sum(word_counts[label].values())
        score = math.log(class_counts[label] / len(TRAIN))
        for word in text.split():
            if word in vocabulary:  # words never seen in training are skipped
                score += math.log((word_counts[label][word] + 1) / (total_words + len(vocabulary)))
        return score
    
    
    def classify(text: str) -> tuple:
        scores = {label: log_score(text, label) for label in class_counts}
        top = max(scores.values())
        weights = {label: math.exp(s - top) for label, s in scores.items()}
        best = max(weights, key=weights.get)
        return best, round(weights[best] / sum(weights.values()), 3)
    
    
    print(classify("free money"))  # ('spam', 0.9)
    print(classify("friday meeting"))  # ('normal', 0.9)
    print(classify("free lunch on friday"))  # ('normal', 0.8)

    Each class has 10 training words and the vocabulary has 15, so "free" scores (2 + 1) / 25 for spam but only (0 + 1) / 25 for normal messages.

  13. Q13.How does a support vector machine choose its decision boundary?

    A support vector machine chooses the boundary that separates the classes with the widest possible margin, the gap between the boundary and the closest training points. Those closest points, the support vectors, alone determine the boundary.

    How it works:

    • Maximum margin: among all boundaries that separate the classes, pick the one farthest from both, which tends to generalize better.
    • Soft margin: real data overlaps, so some points may sit inside the margin or on the wrong side, at a penalty.
    • The C parameter sets that penalty. A large C fits the training data tightly with a narrow margin and risks overfitting; a small C allows more violations for a wider, smoother margin.
    • Hinge loss is the loss function this behavior comes from: points correctly classified beyond the margin cost nothing.
    • Kernels let the same method draw curved boundaries.

    Practical points:

    • Scale features, since the margin is measured in feature space distances.
    • It works well on small and medium datasets with many features, such as text.
    • Training becomes slow beyond tens of thousands of rows with nonlinear kernels.
    • Outputs are distances to the boundary, not probabilities. Calibrate them if probabilities are needed.
  14. Q14.What is the kernel trick, and when do you need it?

    The kernel trick lets a linear method, such as a support vector machine, learn nonlinear boundaries by computing similarities as if the data had been mapped into a much higher-dimensional space, without ever building that space explicitly.

    How it works:

    • Many algorithms use the data only through dot products between pairs of points.
    • A kernel function returns the dot product the points would have after some transformation, computed directly from the original features.
    • The model is linear in the transformed space, which corresponds to a curved boundary in the original one.

    Common kernels:

    • Linear: no transformation; best for high-dimensional sparse data such as text.
    • Polynomial: captures interactions between features up to a chosen degree.
    • Radial basis function: similarity that decays with distance; flexible and the usual default for nonlinear problems.

    When you need it: the classes are not linearly separable, the dataset is small to medium, and you want a strong, well-founded model without manual feature engineering.

    When to avoid it: large datasets, because the method compares every pair of points, so cost grows roughly with the square of the row count. Tree ensembles, neural networks or approximate kernel features scale better.

  15. Q15.How do you stop a decision tree from overfitting?

    An unconstrained tree keeps splitting until every leaf is pure, memorizing noise in the training data. Limit its growth while building it, prune it afterwards, or replace a single tree with an ensemble.

    Maximum depthMinimum samples per leafMinimum samples to split
    Caps the number of split levelsEach leaf must hold at least this many rowsA node needs this many rows before it splits
    Gives fewer, broader rulesNo leaves built on one or two examplesStops splitting small groups
    Maximum leaf nodesMinimum impurity decreaseCost-complexity pruning
    Caps the total number of leavesA split must improve purity by at least this muchRemoves branches whose gain does not justify their size
    Keeps the tree compactSkips splits with little valueSimplifies a fully grown tree

    How to tune:

    1. Choose these values by cross-validation, not by eye.
    2. Watch the gap between training and validation scores as you loosen each constraint.
    3. Prefer minimum samples per leaf and depth first; they are the most effective and easiest to explain.

    If one tree is still too unstable, use a random forest or gradient boosting, which keep the strengths of trees while reducing their variance.

  16. Q16.How does a random forest reduce variance, and what is out-of-bag error?

    A random forest averages many deep decision trees, each trained on a bootstrap sample of the rows and choosing each split from a random subset of features. Averaging trees whose errors are not strongly correlated cancels much of their individual variance.

    Why the randomness matters:

    • Bootstrap samples make each tree see a slightly different dataset.
    • Random feature subsets at each split stop every tree from choosing the same strong feature first, so trees become more different, and averaging helps more.
    • Each tree can stay deep and low-bias, because the average controls variance.

    Out-of-bag error:

    • Each bootstrap sample leaves out about a third of the rows.
    • For every row, predict using only the trees that did not train on it, and score those predictions.
    • This gives a validation estimate for free, without a separate hold-out set.

    Practical points:

    • More trees never increase overfitting; they only cost time. Add trees until the out-of-bag score stops improving.
    • Feature importances based on impurity favor features with many distinct values; prefer permutation importance.

    Example

    Why about a third of rows are out of bag:

    1. A bootstrap sample draws n rows with replacement, so the chance that a given row is never drawn is (1 − 1/n)^n.
    2. With n = 1,000, that is 0.999^1000 ≈ 0.368, close to its limit of about 0.368 for large n.
    3. With 300 trees, each row is out of bag for about 300 × 0.368 ≈ 110 trees.
    4. Its out-of-bag prediction is the vote of those 110 trees, which is plenty for a stable error estimate.
  17. Q17.How does gradient boosting build its trees?

    Gradient boosting builds trees one after another, each new tree trained to correct the errors of all the trees before it. Each tree's contribution is shrunk by a learning rate, so the model improves in many small, careful steps.

    1. Start with a simple prediction, such as the mean of the target for regression.
    2. Compute the errors the current model makes on each row. More generally, compute the gradient of the loss for each row; for squared error, that is just the residual.
    3. Fit a small tree to predict those errors from the features.
    4. Add the tree to the model, multiplied by the learning rate.
    5. Repeat until a set number of trees, or until validation error stops improving.
    flowchart LR
      A["Initial prediction"] --> B["Compute residuals"]
      B --> C["Fit small tree to residuals"]
      C --> D["Add tree times learning rate"]
      D --> E{"Validation still improving?"}
      E -->|yes| B
      E -->|no| F["Final model"]

    Why it works well: each tree focuses on what the model still gets wrong, so the ensemble steadily reduces bias. Small trees and a low learning rate keep each step from overfitting.

    Risks: it keeps fitting harder cases, including noise, so it needs early stopping on a validation set.

    Example

    Two rounds of gradient boosting on three house prices, in thousands: 250, 300 and 380, with a learning rate of 0.1:

    1. Start with the mean: (250 + 300 + 380) / 3 = 310 for every house.
    2. Residuals: −60, −10 and 70.
    3. The first tree puts house 1 in one leaf and houses 2 and 3 in another, predicting −60 and (−10 + 70) / 2 = 30.
    4. Update: 310 + 0.1 × (−60) = 304, and 310 + 0.1 × 30 = 313 for houses 2 and 3.
    5. New residuals: −54, −13 and 67. Each is a little smaller, and the next tree targets what remains.
  18. Q18.Which gradient boosting hyperparameters matter most, and how do they interact?

    The most important settings control how many trees are built, how much each one contributes, and how complex each tree is. They interact, so tune them together rather than one at a time.

    Learning rateNumber of treesTree depth or leavesMinimum samples per leaf
    How much each tree contributesHow many correction steps runHow complex each tree is and which interactions it capturesHow much data each leaf needs
    Typically 0.01 to 0.3Typically hundreds to thousandsTypically depth 3 to 10Depends on the data size
    Lower rates need more treesSet by early stopping, not by handDeeper trees overfit soonerLarger values smooth predictions
    Row subsamplingFeature subsamplingRegularization on leaf values
    Share of rows used per treeShare of features used per tree or splitPenalizes large leaf outputs
    Typically 0.5 to 1.0Typically 0.5 to 1.0Typically small positive values
    Adds randomness and reduces varianceDecorrelates trees and speeds trainingTames overly confident trees

    A practical tuning order:

    1. Fix a moderate learning rate, such as 0.1, and use early stopping to find the number of trees.
    2. Tune tree complexity: depth or leaves, and minimum samples per leaf.
    3. Tune subsampling and regularization.
    4. Lower the learning rate and let early stopping add trees, which usually gives a final small gain.
  19. Q19.How does stacking differ from simple averaging of models?

    Averaging combines several models' predictions with fixed weights, usually equal. Stacking trains a second-level model to learn how best to combine the first-level models' predictions, using predictions made on data those models did not train on.

    Simple averagingStacking
    Combines models with fixed, often equal, weightsLearns the combination with a meta-model
    Needs no extra trainingNeeds out-of-fold predictions plus a meta-model
    Low leakage riskHigh leakage risk if base predictions come from training data
    A solid, reliable gainSometimes a larger gain, sometimes none
    Simple to run in productionSeveral models plus a combiner to serve

    How stacking is done correctly:

    1. Generate out-of-fold predictions for every base model with cross-validation, so each prediction comes from a model that never saw that row.
    2. Train a simple meta-model, often a regularized linear model, on those predictions.
    3. At serving time, run every base model, then the meta-model.

    When to use which:

    • Averaging gives most of the benefit of ensembling when models are diverse and similarly good.
    • Stacking helps when models are good in different regions of the data.
    • In production, weigh the extra latency and maintenance against a gain that is often small.
  20. Q20.How do filter, wrapper and embedded feature selection methods differ?

    They differ in how features are judged. Filter methods score each feature with a statistic before modeling, wrapper methods search for the subset that gives the best model score, and embedded methods select features as part of training the model itself.

    FilterWrapperEmbedded
    Judges each feature with a statistic, such as correlation or mutual informationJudges feature subsets by model performanceSelection is built into model training
    Examples: correlation with the target, variance thresholdExamples: forward selection, backward eliminationExamples: absolute-value penalty, tree importances
    Low compute costHigh compute cost: many model fitsModerate compute cost
    Ignores feature interactionsCaptures feature interactionsPartly captures feature interactions
    Low overfitting riskHigh overfitting risk without careful validationModerate overfitting risk

    When to use which:

    • Filter methods for a quick first cut over thousands of features, such as dropping constant or near-duplicate ones.
    • Wrapper methods when the feature count is modest and the best subset really matters.
    • Embedded methods as the default in practice, through regularized linear models or tree ensembles.

    Do feature selection inside cross-validation. Selecting features on the full dataset and then validating leaks information and inflates scores.