Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Interview Questions»100 Machine Learning Interview Questions and Answers (Freshers to Experienced)
    Interview Questions

    100 Machine Learning Interview Questions and Answers (Freshers to Experienced)

    Anirudh KhuranaBy Anirudh Khurana25 November 2026No Comments87 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    100 machine learning interview questions by Code and Debug, with a neural network illustration
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Machine learning interviews in India now range from campus drives for data science trainees to ML engineer rounds at product companies and AI startups. Freshers get “what is overfitting?” and “precision vs recall”. Experienced candidates get questions on drift, deployment, XGBoost internals and, more and more, transformers, RAG and LLMs.

    This page has the 100 machine learning interview questions asked most often, with clear answers, grouped for freshers, intermediate and experienced candidates. 30 answers include a short Python example that was actually run, so the output you see is real. Four interactive tools let you see the bias-variance tradeoff, practise choosing metrics, watch gradient descent with different learning rates, and get a model suggestion for your problem. Prefer to study offline? Download all 100 questions as a free PDF.

    Free PDF
    All 100 machine learning interview questions with answers
    42 pages, ready to print or read offline. No sign-up needed.
    Download PDF

    What you will find on this page

    • 100 questions with answers in three levels: 40 for freshers, 35 intermediate, 25 for experienced candidates.
    • Core machine learning plus the new topics: about 85 questions on ML fundamentals, models, evaluation and production, and about 15 on neural networks, transformers, RAG and LLMs.
    • Four interactive tools: a bias-variance slider, a “pick the right metric” game, a gradient descent visualiser and an algorithm picker.
    • 30 Python examples with real output, mostly with scikit-learn.
    • Study tools: filters by level and topic, search, and a “Done” button on every question that remembers your progress.
    • A free 42-page PDF and a 10-question quiz at the end.

    Helpful to know first (each opens our own guide):

    AI and ML roadmapThe full learning path, if you are starting out. Python interview questionsThe language every example here uses. Confusion matrix guideThe metrics behind a dozen of these questions.
    Study tools

    Study these 100 questions your way

    Filter the machine learning interview questions by level or topic, or search them. Press “Mark as done” under each question you have finished; your progress is saved in this browser.

    Showing
    100 / 100
    Done
    0 / 100
    Download PDF (42 pages)

    No questions match these filters. Try another topic or clear the search.

    How to prepare for a machine learning interview

    • Explain every concept with an example. “Overfitting is when the model memorises noise” is fine, but “my degree-12 polynomial had near-zero training error and huge test error” is what convinces an interviewer.
    • Know the classic comparisons: bias vs variance, precision vs recall, L1 vs L2, bagging vs boosting, k-means vs KNN, ROC vs PR curve, generative vs discriminative.
    • Be able to code the basics. Train and evaluate a model with scikit-learn, write gradient descent and k-means in NumPy, and build a Pipeline without leakage.
    • Prepare one project story in depth: the problem, the data, the metric and why, the baseline, what you tried, what failed and how it would run in production.
    • For experienced and GenAI roles, revise drift and monitoring, deployment, gradient boosting internals, transformers, RAG and how to evaluate LLM outputs.

    Learn the key ideas by doing

    Four ideas come up in almost every machine learning interview, often as follow-up questions: why a model overfits, which metric to use, how the learning rate affects training, and which algorithm to pick. These tools let you see each one. Spend ten minutes with them before you read the questions below.

    Bias-variance slider: from underfitting to overfitting

    A polynomial is fitted to 18 noisy points from a sine wave. Drag the degree to make the model more or less complex, and watch the training and test errors. Turn on “Show other samples” to see why complex models have high variance.

    Try it

    Bias-variance tradeoff

    Loading the chart…

    Start at degree 1, then move to 3 or 4, then to 12. The bottom chart is the curve from question 8: training error keeps falling as complexity grows, while test error falls and then rises again.

    Pick the right metric: a scenario game

    Interviewers rarely ask “what is recall?” on its own. They describe a business problem and ask which metric you would use. Eight scenarios, one answer each.

    Game

    Which metric would you choose?

    8 scenarios, about three minutes.

    Gradient descent and the learning rate

    The contour chart shows a loss surface shaped like an oval valley, with the minimum at the green star. Gradient descent starts at the top left and takes 40 steps. Change the learning rate and watch the path and the loss curve.

    Try it

    Gradient descent visualiser

    Loading the chart…

    This is why learning rate is the first hyperparameter to tune for neural networks, and why optimisers like Adam, which adapt the step size for each parameter, are so popular.

    Which algorithm should I use?

    A common interview question is “how would you choose a model for this problem?”. Answer a few questions and see a sensible starting point, with the reasons an interviewer expects to hear.

    Try it

    Algorithm picker

    A rule of thumb to start from, not a law. Always compare against a simple baseline.

    What do you want to do?
    What kind of data?
    How much labelled data?
    Must you explain every prediction (for example to a regulator)?
    What do you expect the groups to look like?

    Machine learning interview questions for freshers

    These 40 basic machine learning interview questions cover what campus placements and first data science interviews ask: types of learning, overfitting and the bias-variance tradeoff, data preparation, the core algorithms, evaluation metrics, clustering, gradient descent and the basics of neural networks.

    Q1FreshersBasics

    1. What is machine learning?

    Machine learning is a way of building software that learns patterns from data instead of following rules a programmer wrote by hand. You show the model many examples, it adjusts its internal numbers (parameters) to fit them, and then it makes predictions on new data it has never seen.

    A spam filter is the classic example. Writing rules for every kind of spam is impossible, but if you give a model thousands of emails labelled “spam” or “not spam”, it learns which words and patterns matter. Tom Mitchell’s textbook definition is often quoted in interviews: a program learns from experience E on task T, measured by performance P, if its performance on T improves with E.

    Q2FreshersBasics

    2. What is the difference between AI, machine learning, deep learning and generative AI?

    TermWhat it meansExample
    Artificial intelligence (AI)The broad goal of making machines do tasks that need human intelligenceChess engines, chatbots, self-driving cars
    Machine learning (ML)A part of AI where systems learn patterns from dataSpam filters, loan approval, price prediction
    Deep learning (DL)A part of ML that uses neural networks with many layersFace recognition, speech to text
    Generative AIDeep learning models that create new text, images, audio or codeChatGPT, Claude, image generators

    Each one sits inside the one before it: all deep learning is machine learning, and all machine learning is AI, but not the other way round. Our AI and ML roadmap shows how they connect as a learning path.

    Q3FreshersBasics

    3. What are the main types of machine learning?

    • Supervised learning: the training data has the correct answers (labels). The model learns to map inputs to outputs. Examples: predicting house prices, detecting spam.
    • Unsupervised learning: no labels. The model finds structure on its own, such as groups of similar customers or a compressed version of the data.
    • Reinforcement learning: an agent takes actions in an environment and learns from rewards and penalties. Examples: game-playing agents, robot control.

    Two in-between types also come up: semi-supervised learning uses a few labelled examples plus many unlabelled ones, and self-supervised learning creates labels from the data itself, such as predicting the next word. Large language models are trained mostly with self-supervised learning.

    Q4FreshersBasics

    4. What is the difference between supervised and unsupervised learning?

    PointSupervisedUnsupervised
    LabelsNeeded for every training exampleNot needed
    GoalPredict a known targetFind hidden structure or groups
    Typical tasksClassification, regressionClustering, dimensionality reduction, anomaly detection
    AlgorithmsLinear and logistic regression, decision trees, SVM, random forestK-means, DBSCAN, hierarchical clustering, PCA
    How you evaluateCompare predictions with true labelsHarder; use measures like silhouette score or business judgement

    A simple way to remember it: if you know what the right answer looks like for past data, it is supervised.

    Q5FreshersBasics

    5. What is the difference between classification and regression?

    Both are supervised learning. Classification predicts a category: spam or not spam, which digit is in an image, whether a loan will default. Regression predicts a continuous number: a house price, tomorrow’s temperature, a delivery time.

    The difference also changes how you measure success. Classification uses accuracy, precision, recall and F1; regression uses MAE, RMSE and R². Note that logistic regression is a classification algorithm despite its name, because it outputs a probability that is turned into a class.

    Q6FreshersBasics

    6. What are features, labels and training data?

    Features (also called inputs, predictors or independent variables) are the pieces of information the model uses, such as a flat’s size, location and floor. The label (target or dependent variable) is what you want to predict, such as its rent. Training data is the set of past examples that have both features and labels.

    In code, features are usually a 2D array or DataFrame called X, with one row per example and one column per feature, and labels are a 1D array called y.

    Q7FreshersBasics

    7. Why do we split data into training, validation and test sets?

    A model must be judged on data it has not seen, otherwise a model that simply memorised the training data would look perfect. So the data is split:

    • Training set (often 60 to 80%): the model learns from it.
    • Validation set: used to compare models and tune hyperparameters. Cross-validation can replace a fixed validation set.
    • Test set (often 10 to 20%): touched only once, at the very end, to estimate real-world performance.
    from sklearn.datasets import load_iris
    from sklearn.model_selection import train_test_split
    
    X, y = load_iris(return_X_y=True)
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.2, stratify=y, random_state=42)
    
    print("Train:", X_train.shape, "| Test:", X_test.shape)
    print("Class counts in test:", [int((y_test == c).sum()) for c in range(3)])

    Output:

    Train: (120, 4) | Test: (30, 4)
    Class counts in test: [10, 10, 10]

    Using stratify=y keeps the class proportions the same in both parts, which matters for small or imbalanced datasets. If you keep checking the test set while tuning, it stops being an honest estimate.

    Q8FreshersBasics

    8. What are overfitting and underfitting?

    Overfitting means the model has learned the training data too closely, including its noise. It scores very well on training data and badly on new data. Underfitting means the model is too simple to capture the real pattern, so it does badly on both.

    Here a polynomial is fitted to 15 noisy points from a sine curve. Degree 1 (a straight line) underfits, degree 3 is about right, and degree 12 overfits: its training error is the lowest, but its test error explodes.

    import numpy as np
    from sklearn.linear_model import LinearRegression
    from sklearn.metrics import mean_squared_error
    from sklearn.pipeline import make_pipeline
    from sklearn.preprocessing import PolynomialFeatures
    
    rng = np.random.default_rng(1)
    x = rng.uniform(0, 1, 15).reshape(-1, 1)
    y = np.sin(2 * np.pi * x).ravel() + rng.normal(0, 0.2, 15)
    x_test = rng.uniform(0, 1, 200).reshape(-1, 1)
    y_test = np.sin(2 * np.pi * x_test).ravel() + rng.normal(0, 0.2, 200)
    
    for degree in [1, 3, 12]:
        model = make_pipeline(PolynomialFeatures(degree), LinearRegression()).fit(x, y)
        print(f"degree {degree:2d}: train MSE={mean_squared_error(y, model.predict(x)):.3f}  "
              f"test MSE={mean_squared_error(y_test, model.predict(x_test)):.3f}")

    Output:

    degree  1: train MSE=0.298  test MSE=0.251
    degree  3: train MSE=0.016  test MSE=0.060
    degree 12: train MSE=0.007  test MSE=3.418

    The bias-variance slider further up this page lets you see the same thing visually.

    Q9FreshersBasics

    9. What is the bias-variance tradeoff?

    Bias is error from wrong or overly simple assumptions: a straight line can never fit a curve, however much data you give it. Variance is error from being too sensitive to the particular training data: a very flexible model changes a lot if you train it on a slightly different sample.

    Simple models have high bias and low variance (they underfit). Complex models have low bias and high variance (they overfit). Expected test error is roughly bias² + variance + irreducible noise, so the best model sits in the middle, where the total is lowest. More data lowers variance, which is why complex models need a lot of it.

    Q10FreshersBasics

    10. How can you prevent overfitting?

    • Get more training data, or use data augmentation for images and text.
    • Use a simpler model or fewer features.
    • Add regularisation (L1, L2, dropout for neural networks).
    • Use cross-validation to choose hyperparameters honestly.
    • Limit model complexity: max_depth for trees, fewer layers or units for neural networks.
    • Stop training early when the validation score stops improving.
    • Use ensembles such as random forests, which average out the variance of single models.

    In an interview, mention that you first detect overfitting by comparing training and validation scores. A large gap is the signal.

    Q11FreshersData & features

    11. What is feature engineering?

    Feature engineering is creating, transforming or selecting input features so the model can learn more easily. Good features often matter more than the choice of algorithm.

    • Extracting parts of a date: day of week, month, is_weekend, is_festival_season.
    • Ratios and differences: price per square foot, debt-to-income ratio.
    • Aggregates: a customer’s average order value over the last 30 days.
    • Text features: word counts, TF-IDF, embeddings.
    • Encoding categories, scaling numbers and handling missing values (the next few questions).
    Q12FreshersData & features

    12. How do you handle missing values?

    First find out why values are missing, because that decides the fix. Then choose:

    • Drop rows or columns, if very few rows are affected or a column is mostly empty.
    • Impute with the mean or median (numbers) or the most frequent value (categories).
    • Model-based imputation, such as KNN imputation or iterative imputation.
    • Add a “was missing” indicator column, because missingness itself can carry information.
    • Use models that handle missing values natively, such as gradient boosting libraries.
    import numpy as np
    import pandas as pd
    from sklearn.impute import SimpleImputer
    
    df = pd.DataFrame({"age": [25, np.nan, 40, 35, np.nan],
                       "city": ["Surat", "Pune", np.nan, "Pune", "Pune"]})
    
    num = SimpleImputer(strategy="median").fit_transform(df[["age"]])
    cat = SimpleImputer(strategy="most_frequent").fit_transform(df[["city"]])
    print("age: ", num.ravel())
    print("city:", cat.ravel())

    Output:

    age:  [25. 35. 40. 35. 35.]
    city: ['Surat' 'Pune' 'Pune' 'Pune' 'Pune']

    Fit the imputer on the training data only and reuse it on the test data, otherwise information leaks from the test set. A scikit-learn Pipeline (question 64) does this for you.

    Q13FreshersData & features

    13. What is the difference between normalisation and standardisation?

    Normalisation (min-max scaling) squeezes values into a fixed range, usually 0 to 1: (x − min) / (max − min). Standardisation (z-score) rescales values to mean 0 and standard deviation 1: (x − mean) / std.

    import numpy as np
    from sklearn.preprocessing import MinMaxScaler, StandardScaler
    
    salary = np.array([[20000], [35000], [50000], [120000]])
    
    print("Min-max:     ", MinMaxScaler().fit_transform(salary).ravel().round(3))
    print("Standardised:", StandardScaler().fit_transform(salary).ravel().round(3))

    Output:

    Min-max:      [0.   0.15 0.3  1.  ]
    Standardised: [-0.946 -0.555 -0.163  1.664]

    Standardisation is the usual default and copes better with outliers; one extreme salary squashes all other min-max values towards 0. Min-max is handy when you need a bounded range, such as pixel values. Scaling matters for distance-based and gradient-based models (KNN, k-means, SVM, linear models, neural networks) but not for tree-based models.

    Q14FreshersData & features

    14. How do you encode categorical variables?

    Models need numbers, so text categories must be encoded:

    • One-hot encoding: one 0/1 column per category. Safe for categories with no order, like city.
    • Ordinal (label) encoding: one integer per category. Use it only when the categories have a real order, like S, M, L, or with tree models.
    • Target encoding: replace each category with the average target for it. Useful for many categories, but it must be done inside cross-validation to avoid leakage.
    import pandas as pd
    from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder
    
    df = pd.DataFrame({"city": ["Surat", "Pune", "Delhi", "Pune"],
                       "size": ["S", "L", "M", "S"]})
    
    onehot = OneHotEncoder(sparse_output=False).fit(df[["city"]])
    print(onehot.get_feature_names_out())
    print(onehot.transform(df[["city"]]))
    
    ordinal = OrdinalEncoder(categories=[["S", "M", "L"]])
    print("size:", ordinal.fit_transform(df[["size"]]).ravel())

    Output:

    ['city_Delhi' 'city_Pune' 'city_Surat']
    [[0. 0. 1.]
     [0. 1. 0.]
     [1. 0. 0.]
     [0. 1. 0.]]
    size: [0. 2. 1. 0.]

    Giving cities the numbers 0, 1 and 2 with a linear model would wrongly tell it that Delhi < Pune < Surat. That is why one-hot encoding is the default for unordered categories.

    Q15FreshersData & features

    15. What is data leakage?

    Data leakage happens when information that would not be available at prediction time sneaks into training. The model looks great in testing and fails in real use. Common causes:

    • A feature that is created after the outcome, such as “refund issued” when predicting fraud.
    • Scaling, imputing or selecting features on the whole dataset before splitting.
    • Duplicate or near-duplicate rows in both train and test.
    • Random splits on time series, so the model trains on the future.

    Here the labels are pure coin flips, so no model can beat 50%. Selecting features on all the data first gives a fake 85%:

    import numpy as np
    from sklearn.feature_selection import SelectKBest, f_classif
    from sklearn.linear_model import LogisticRegression
    from sklearn.model_selection import cross_val_score
    from sklearn.pipeline import make_pipeline
    
    rng = np.random.default_rng(0)
    X = rng.normal(size=(100, 5000))        # pure noise features
    y = rng.integers(0, 2, 100)             # random labels: nothing to learn
    
    # WRONG: pick the "best" features using all the data, then cross-validate
    X_sel = SelectKBest(f_classif, k=20).fit_transform(X, y)
    leaky = cross_val_score(LogisticRegression(max_iter=1000), X_sel, y, cv=5).mean()
    
    # RIGHT: feature selection happens inside each training fold
    pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
    honest = cross_val_score(pipe, X, y, cv=5).mean()
    
    print(f"Leaky accuracy:  {leaky:.2f}")
    print(f"Honest accuracy: {honest:.2f}")

    Output:

    Leaky accuracy:  0.85
    Honest accuracy: 0.48
    Q16FreshersData & features

    16. What are outliers and how do you handle them?

    Outliers are values far away from the rest of the data, such as a salary of ₹5 crore in a dataset of students’ first jobs. Detect them with box plots, the IQR rule (below Q1 − 1.5 × IQR or above Q3 + 1.5 × IQR), z-scores above about 3, or models like Isolation Forest.

    Then decide whether each one is an error or a real but rare value. Fix or remove errors. Keep real ones but reduce their effect: cap them (winsorising), apply a log transform, use robust models (trees, median-based methods) or robust losses (MAE, Huber). Never drop outliers blindly; in fraud detection the outliers are often the whole point.

    Q17FreshersData & features

    17. What is the curse of dimensionality?

    As the number of features grows, the space the data lives in grows so fast that the data becomes very sparse. You would need exponentially more data to cover it. Distances also become less meaningful, because in high dimensions the nearest and furthest points are almost the same distance away.

    This hurts distance-based models like KNN and k-means the most, and raises the risk of overfitting for everything. Fixes are feature selection, dimensionality reduction (PCA), regularisation, or simply collecting more data.

    Q18FreshersRegression

    18. How does linear regression work, and what are its assumptions?

    Linear regression predicts a number as a weighted sum of the features plus a constant: ŷ = w₁x₁ + w₂x₂ + … + b. Training finds the weights that minimise the mean squared error between predictions and actual values, either with a closed-form solution (ordinary least squares) or with gradient descent.

    The classic assumptions are: a linear relationship between features and target, independent errors, constant error variance (homoscedasticity), normally distributed errors (mainly for confidence intervals), and little multicollinearity between features. Our linear regression guide shows each one visually.

    Q19FreshersRegression

    19. What is the difference between MAE, MSE and RMSE?

    • MAE (mean absolute error): the average size of the errors. Easy to explain and treats all errors equally.
    • MSE (mean squared error): the average of squared errors. Big errors count much more. Its unit is squared, which is hard to read.
    • RMSE: the square root of MSE, back in the original unit, still punishing big errors.
    import numpy as np
    from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
    
    y_true = np.array([50, 60, 70, 80, 90])     # actual flat prices (lakh)
    y_pred = np.array([52, 58, 75, 78, 70])     # one big miss on the last flat
    
    print("MAE: ", mean_absolute_error(y_true, y_pred))
    print("MSE: ", mean_squared_error(y_true, y_pred))
    print("RMSE:", round(np.sqrt(mean_squared_error(y_true, y_pred)), 2))
    print("R2:  ", round(r2_score(y_true, y_pred), 3))

    Output:

    MAE:  6.2
    MSE:  87.4
    RMSE: 9.35
    R2:   0.563

    One flat is off by ₹20 lakh. MAE says the typical miss is 6.2 lakh, while RMSE (9.35) is pulled up by that single large miss. Choose RMSE when big errors are especially costly, and MAE when you want a measure that outliers do not dominate.

    Q20FreshersRegression

    20. What is R² (the coefficient of determination)?

    R² tells you what share of the variation in the target your model explains, compared with always predicting the average. R² = 1 − (sum of squared errors of the model / sum of squared errors of the mean). 1 is perfect, 0 means no better than predicting the mean, and it can be negative for a model worse than that. In the example above, R² is 0.563.

    Plain R² never goes down when you add features, even useless ones. Adjusted R² corrects for the number of features, so it is better for comparing models with different feature counts.

    Q21FreshersClassification

    21. How does logistic regression work, and why not use linear regression for classification?

    Logistic regression computes a weighted sum of the features, just like linear regression, and then passes it through the sigmoid function to get a probability between 0 and 1. If the probability is above a threshold (usually 0.5), it predicts the positive class. It is trained by minimising log loss, not MSE.

    import numpy as np
    from sklearn.linear_model import LogisticRegression
    
    hours = np.array([[1], [2], [3], [4], [5], [6], [7], [8]])
    passed = np.array([0, 0, 0, 1, 0, 1, 1, 1])
    
    model = LogisticRegression().fit(hours, passed)
    for h in [2, 4.5, 7]:
        print(f"{h} hours -> P(pass) = {model.predict_proba([[h]])[0, 1]:.3f}")

    Output:

    2 hours -> P(pass) = 0.103
    4.5 hours -> P(pass) = 0.500
    7 hours -> P(pass) = 0.897

    Linear regression is a poor fit for classification because its output is not limited to 0 to 1, so it cannot be read as a probability, and a few extreme points can shift the line and move the decision boundary badly. Our logistic regression guide walks through this with interactive charts.

    Q22FreshersClassification

    22. What is the sigmoid function?

    The sigmoid (logistic) function is σ(z) = 1 / (1 + e−z). It turns any real number into a value between 0 and 1: large positive inputs go close to 1, large negative inputs go close to 0, and 0 maps to exactly 0.5.

    That makes it ideal for turning a score into a probability in logistic regression and in the output layer of binary neural networks. Its derivative is simple, σ(z) × (1 − σ(z)), which is useful in backpropagation. Its weakness is that it flattens at both ends, so gradients become tiny there (question 70).

    Q23FreshersClassification

    23. How does the KNN algorithm work, and how do you choose K?

    K-nearest neighbours stores the training data and, for a new point, finds the K closest training points (usually by Euclidean distance). For classification it takes a majority vote of their labels; for regression it averages their values. It has no real training step, so it is called a lazy learner.

    Small K (like 1) follows the noise and overfits; large K smooths too much and underfits. Choose K with cross-validation, use an odd K for two classes to avoid ties, and always scale features first.

    from sklearn.datasets import load_breast_cancer
    from sklearn.model_selection import cross_val_score
    from sklearn.neighbors import KNeighborsClassifier
    from sklearn.pipeline import make_pipeline
    from sklearn.preprocessing import StandardScaler
    
    X, y = load_breast_cancer(return_X_y=True)
    for k in [1, 3, 5, 11, 21, 51]:
        model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=k))
        print(f"K={k:2d}  CV accuracy={cross_val_score(model, X, y, cv=5).mean():.3f}")

    Output:

    K= 1  CV accuracy=0.954
    K= 3  CV accuracy=0.960
    K= 5  CV accuracy=0.965
    K=11  CV accuracy=0.965
    K=21  CV accuracy=0.956
    K=51  CV accuracy=0.951

    Here K = 5 and K = 11 do best. KNN is easy to understand but slow to predict on large datasets and weak in high dimensions. Do not confuse it with k-means clustering, where K means the number of clusters.

    Q24FreshersClassification

    24. What is Naive Bayes, and why is it called naive?

    Naive Bayes is a classifier based on Bayes’ theorem: P(class | features) ∝ P(features | class) × P(class). It is called naive because it assumes every feature is independent of the others once you know the class. In spam filtering, that means it treats “free” and “prize” as unrelated words, which is not true, but the model still works surprisingly well.

    from sklearn.feature_extraction.text import CountVectorizer
    from sklearn.naive_bayes import MultinomialNB
    
    texts = ["win a free prize now", "free cash offer win", "meeting at 5 pm",
             "project report due tomorrow", "claim your free prize", "lunch tomorrow?"]
    labels = [1, 1, 0, 0, 1, 0]                  # 1 = spam
    
    vec = CountVectorizer()
    model = MultinomialNB().fit(vec.fit_transform(texts), labels)
    
    new = ["free prize for you", "report meeting tomorrow"]
    print(model.predict(vec.transform(new)))
    print(model.predict_proba(vec.transform(new)).round(3))

    Output:

    [1 0]
    [[0.095 0.905]
     [0.944 0.056]]

    Variants: Gaussian NB for continuous features, Multinomial NB for word counts, Bernoulli NB for yes/no features. It is very fast, needs little data and is a strong baseline for text. Its probability estimates are often poorly calibrated (question 83).

    Q25FreshersTrees & ensembles

    25. How does a decision tree work?

    A decision tree predicts by asking a series of yes or no questions about the features, such as “income ≤ ₹36,500?”. At each node it tries every feature and threshold and picks the split that makes the child nodes purest, measured with Gini impurity or entropy for classification and squared error for regression. It repeats this until a stopping rule is met, and each leaf holds the prediction.

    Trees are easy to explain and need no scaling, but they overfit easily, so you limit max_depth or prune them. You can grow one step by step in our interactive decision tree guide.

    Q26FreshersTrees & ensembles

    26. What are Gini impurity and entropy?

    Both measure how mixed the classes in a node are. Gini impurity = 1 − Σ pᵢ², the chance of mislabelling a random point if you guess using the node’s class mix. Entropy = −Σ pᵢ log₂ pᵢ, the uncertainty in the node. Both are 0 for a pure node; for two classes Gini peaks at 0.5 and entropy at 1.

    The tree picks the split with the largest drop in impurity; with entropy this drop is called information gain. Gini and entropy choose the same split in most cases. Gini is the scikit-learn default and is slightly faster because it needs no logarithm.

    Q27FreshersClassification

    27. What is a support vector machine (SVM)?

    An SVM finds the boundary that separates two classes with the widest possible gap, called the margin. Only the points closest to the boundary, the support vectors, decide where it goes. The C parameter controls how many points may sit inside the margin or on the wrong side: small C gives a wide, tolerant margin, large C a narrow, strict one.

    With the kernel trick (question 59), an SVM can draw curved boundaries without ever computing new features. SVMs work well on small to medium datasets with many features, but need scaled features and get slow on very large data. Try it in our SVM playground.

    Q28FreshersModel evaluation

    28. What is a confusion matrix?

    A confusion matrix is a table that compares predicted classes with actual classes. For two classes it has four cells: true positives (TP), false positives (FP), false negatives (FN) and true negatives (TN). Every classification metric, from accuracy to F1, is built from these four numbers.

    from sklearn.metrics import (confusion_matrix, accuracy_score,
                                 precision_score, recall_score, f1_score)
    
    # 10 patients: 1 = has the disease
    y_true = [1, 1, 1, 1, 0, 0, 0, 0, 0, 0]
    y_pred = [1, 1, 1, 0, 1, 0, 0, 0, 0, 0]
    
    print(confusion_matrix(y_true, y_pred))      # rows: actual 0, 1
    print("Accuracy: ", accuracy_score(y_true, y_pred))
    print("Precision:", precision_score(y_true, y_pred))
    print("Recall:   ", recall_score(y_true, y_pred))
    print("F1:       ", f1_score(y_true, y_pred))

    Output:

    [[5 1]
     [1 3]]
    Accuracy:  0.8
    Precision: 0.75
    Recall:    0.75
    F1:        0.75

    scikit-learn puts actual classes in rows and predicted classes in columns, with class 0 first, so the layout is [[TN, FP], [FN, TP]]. Here: 5 true negatives, 1 false positive, 1 false negative, 3 true positives. Our interactive confusion matrix guide covers every metric built from it.

    Q29FreshersModel evaluation

    29. Why can accuracy be misleading?

    Accuracy is the share of correct predictions. On imbalanced data it can look excellent while the model is useless. If 99% of transactions are genuine, a model that always says “not fraud” scores 99% accuracy and catches no fraud at all:

    import numpy as np
    from sklearn.dummy import DummyClassifier
    from sklearn.metrics import accuracy_score, recall_score
    
    y = np.array([0] * 990 + [1] * 10)          # 1% fraud
    X = np.zeros((1000, 1))
    
    lazy = DummyClassifier(strategy="most_frequent").fit(X, y)
    pred = lazy.predict(X)
    print("Accuracy:", accuracy_score(y, pred))
    print("Fraud caught (recall):", recall_score(y, pred))

    Output:

    Accuracy: 0.99
    Fraud caught (recall): 0.0

    For imbalanced problems, report precision, recall, F1, PR AUC or a confusion matrix instead, and always compare against a simple baseline like this one.

    Q30FreshersModel evaluation

    30. What is the difference between precision and recall?

    Precision = TP / (TP + FP): of everything the model flagged as positive, how much really was positive. Recall (sensitivity) = TP / (TP + FN): of all the real positives, how many the model found.

    • Favour recall when missing a positive is costly: cancer screening, fraud detection.
    • Favour precision when false alarms are costly: spam filtering (you do not want real email in spam), recommending a risky medical procedure.

    They usually trade off: lowering the decision threshold raises recall and lowers precision (question 48). The “Pick the right metric” game above lets you practise this choice.

    Q31FreshersModel evaluation

    31. What is the F1 score?

    The F1 score is the harmonic mean of precision and recall: F1 = 2 × P × R / (P + R). It ranges from 0 to 1 and is high only when both precision and recall are high. With precision 0.9 and recall 0.1 the simple average is 0.5, but F1 is only 0.18, which reflects how poor the model really is.

    Use F1 when you care about both kinds of error and the classes are imbalanced. If one matters more, use the F-beta score: β > 1 weights recall more, β < 1 weights precision more.

    Q32FreshersModel evaluation

    32. What are the ROC curve and AUC?

    The ROC curve plots the true positive rate (recall) against the false positive rate for every possible threshold. AUC is the area under that curve. It equals the probability that the model gives a random positive example a higher score than a random negative one: 0.5 is random guessing and 1.0 is perfect.

    AUC is useful because it does not depend on one chosen threshold. On heavily imbalanced data, though, it can look too optimistic, and the precision-recall curve is more honest (question 47).

    Q33FreshersModel evaluation

    33. What is cross-validation?

    In k-fold cross-validation the data is split into k equal parts (folds). The model is trained k times, each time on k − 1 folds and tested on the remaining one, and the k scores are averaged. Every data point is used for testing exactly once.

    from sklearn.datasets import load_wine
    from sklearn.model_selection import cross_val_score, StratifiedKFold
    from sklearn.tree import DecisionTreeClassifier
    
    X, y = load_wine(return_X_y=True)
    cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
    scores = cross_val_score(DecisionTreeClassifier(random_state=0), X, y, cv=cv)
    
    print("Fold scores:", scores.round(3))
    print(f"Mean: {scores.mean():.3f}  Std: {scores.std():.3f}")

    Output:

    Fold scores: [0.917 0.833 0.972 0.971 0.943]
    Mean: 0.927  Std: 0.051

    It gives a more reliable estimate than a single split and shows how stable the model is: here scores range from 0.83 to 0.97 depending on the fold. Five or ten folds is typical. Use stratified folds for classification and time-based folds for time series (question 65). Reference: scikit-learn cross-validation guide.

    Q34FreshersUnsupervised

    34. What is clustering, and how does k-means work?

    Clustering is grouping similar data points without labels. K-means is the most common method:

    1. Choose K, the number of clusters.
    2. Place K starting centroids (k-means++ spreads them out).
    3. Assign every point to its nearest centroid.
    4. Move each centroid to the mean of its points.
    5. Repeat steps 3 and 4 until nothing changes.

    It minimises the within-cluster sum of squares (inertia). It is fast but assumes round clusters of similar size, needs scaled features and only finds a local minimum, so it is run several times. Watch it step by step in our k-means clustering playground.

    Q35FreshersUnsupervised

    35. How do you choose the number of clusters K in k-means?

    Two standard methods: the elbow method plots inertia against K and looks for the bend where adding clusters stops helping much, and the silhouette score measures how close each point is to its own cluster compared with the next nearest one, so you pick the K with the highest average.

    from sklearn.cluster import KMeans
    from sklearn.datasets import make_blobs
    from sklearn.metrics import silhouette_score
    
    X, _ = make_blobs(n_samples=500, centers=4, random_state=7)
    for k in range(2, 8):
        km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X)
        print(f"K={k}  inertia={km.inertia_:8.0f}  silhouette={silhouette_score(X, km.labels_):.3f}")

    Output:

    K=2  inertia=   15172  silhouette=0.588
    K=3  inertia=    4313  silhouette=0.763
    K=4  inertia=     920  silhouette=0.811
    K=5  inertia=     818  silhouette=0.693
    K=6  inertia=     731  silhouette=0.578
    K=7  inertia=     651  silhouette=0.472

    Inertia drops sharply until K = 4 and then flattens, and the silhouette score peaks at K = 4, so both agree on four clusters. In real projects, also check whether the clusters are useful for the business.

    Q36FreshersUnsupervised

    36. What is PCA (principal component analysis)?

    PCA is a dimensionality reduction technique. It finds new axes, called principal components, that are combinations of the original features. The first component points in the direction where the data varies most, the second in the next-most direction at right angles to the first, and so on. Keeping only the first few components keeps most of the information with far fewer features.

    import numpy as np
    from sklearn.datasets import load_digits
    from sklearn.decomposition import PCA
    
    X, _ = load_digits(return_X_y=True)           # 64 features (8x8 pixels)
    pca = PCA().fit(X)
    cum = np.cumsum(pca.explained_variance_ratio_)
    
    print("First 5 components explain:", cum[4].round(3))
    print("Components for 90% variance:", int(np.argmax(cum >= 0.90)) + 1)
    print("Components for 95% variance:", int(np.argmax(cum >= 0.95)) + 1)

    Output:

    First 5 components explain: 0.545
    Components for 90% variance: 21
    Components for 95% variance: 29

    The 64 pixel features of the digits dataset can be cut to 21 components while keeping 90% of the variance. PCA is used to speed up models, reduce noise and plot high-dimensional data in 2D. Scale features before PCA, and remember that the new components are harder to interpret than the original features.

    Q37FreshersOptimisation

    37. What is gradient descent?

    Gradient descent is the method most models use to learn. It starts with some parameter values, computes the gradient of the loss (the direction in which the loss rises fastest), and takes a small step the opposite way. It repeats this until the loss stops falling. The size of each step is the learning rate.

    import numpy as np
    
    # Fit y = w*x + b with plain gradient descent
    rng = np.random.default_rng(0)
    x = rng.uniform(0, 10, 100)
    y = 3 * x + 5 + rng.normal(0, 1, 100)
    
    w, b, lr = 0.0, 0.0, 0.01
    for step in range(2001):
        pred = w * x + b
        dw = 2 * np.mean((pred - y) * x)       # gradient of MSE with respect to w
        db = 2 * np.mean(pred - y)             # gradient of MSE with respect to b
        w, b = w - lr * dw, b - lr * db
        if step % 500 == 0:
            print(f"step {step:4d}  MSE={np.mean((pred - y) ** 2):8.3f}  w={w:.3f}  b={b:.3f}")

    Output:

    step    0  MSE= 539.563  w=2.892  b=0.427
    step  500  MSE=   0.987  w=3.050  b=4.545
    step 1000  MSE=   0.941  w=2.993  b=4.948
    step 1500  MSE=   0.940  w=2.988  b=4.988
    step 2000  MSE=   0.940  w=2.987  b=4.992

    The true line is y = 3x + 5, and gradient descent finds w ≈ 2.99 and b ≈ 4.99. If the learning rate is too small, training is slow; if it is too large, the loss jumps around or blows up. The gradient descent tool on this page shows all three cases.

    Q38FreshersOptimisation

    38. What is the difference between a parameter and a hyperparameter?

    Parameters are learned from the data during training: the weights of a linear model, the split thresholds of a tree, the weights of a neural network. Hyperparameters are set by you before training and control how learning happens: the learning rate, K in KNN, max_depth of a tree, C in an SVM, the number of layers in a network.

    Hyperparameters are chosen by trying different values and comparing validation scores, usually with grid search, random search or Bayesian optimisation (question 44).

    Q39FreshersDeep learning

    39. What is a neural network?

    A neural network is a model made of layers of simple units called neurons. Each neuron takes inputs, multiplies them by weights, adds a bias and passes the result through an activation function. An input layer receives the features, one or more hidden layers learn intermediate patterns, and an output layer gives the prediction.

    With enough neurons and non-linear activations, a network can approximate almost any function. It learns its weights with backpropagation and gradient descent. Networks with many hidden layers are called deep neural networks, which is where the term deep learning comes from.

    Q40FreshersDeep learning

    40. What is an activation function, and what are the common ones?

    An activation function adds non-linearity to a neuron. Without it, stacking layers would still give a single linear model, however deep the network.

    FunctionOutputWhere it is used
    ReLU: max(0, x)0 to ∞Default for hidden layers; fast and avoids vanishing gradients for positive inputs
    Sigmoid0 to 1Output layer for binary classification
    Tanh−1 to 1Hidden layers in older networks and some RNNs
    SoftmaxProbabilities that sum to 1Output layer for multiclass classification
    GELU, Leaky ReLUSmooth or slightly negativeTransformers (GELU); avoiding “dead” ReLU units (Leaky ReLU)

    Intermediate machine learning interview questions

    These 35 questions are for candidates with a year or two of hands-on work: regularisation and tuning, imbalanced data, threshold choice, ensembles, feature importance, pipelines, time series validation and the deep learning concepts that come up in ML engineer interviews.

    Q41IntermediateOptimisation

    41. What is the difference between batch, stochastic and mini-batch gradient descent?

    TypeData used for each updateProsCons
    BatchThe whole training setSmooth, stable stepsSlow and memory-heavy on big data
    Stochastic (SGD)One exampleVery fast updates; noise can help escape poor local minimaNoisy, zig-zagging path
    Mini-batchA small batch, such as 32 to 512 examplesBalance of speed and stability; fits GPUs wellBatch size is one more hyperparameter

    Mini-batch is what almost everyone uses for neural networks, and people often just call it SGD. Optimisers like Momentum, RMSProp and Adam build on it by adapting the step size for each parameter.

    Q42IntermediateOptimisation

    42. What is the difference between L1 and L2 regularisation?

    Regularisation adds a penalty on the size of the weights to the loss, so the model prefers simpler solutions. L2 (Ridge) adds λ Σ w², which shrinks all weights smoothly towards zero but rarely makes them exactly zero. L1 (Lasso) adds λ Σ |w|, which pushes some weights to exactly zero, so it also selects features.

    import numpy as np
    from sklearn.datasets import make_regression
    from sklearn.linear_model import Lasso, LinearRegression, Ridge
    
    X, y = make_regression(n_samples=200, n_features=20, n_informative=5, noise=10, random_state=0)
    
    for name, model in [("Linear", LinearRegression()), ("Ridge (L2)", Ridge(alpha=10)),
                        ("Lasso (L1)", Lasso(alpha=5))]:
        coef = model.fit(X, y).coef_
        print(f"{name:11s} zero coefs: {np.sum(np.abs(coef) < 1e-6):2d}   "
              f"largest |coef|: {np.abs(coef).max():.1f}")

    Output:

    Linear      zero coefs:  0   largest |coef|: 83.8
    Ridge (L2)  zero coefs:  0   largest |coef|: 79.0
    Lasso (L1)  zero coefs: 15   largest |coef|: 77.8

    The data has 20 features but only 5 useful ones. Lasso set 15 coefficients to zero, while Ridge kept all of them. Use L1 when you expect few useful features or want a simpler model, and L2 when many features each contribute a little or features are correlated. In scikit-learn the strength is alpha for Ridge and Lasso, and C = 1/λ for logistic regression and SVM.

    Q43IntermediateOptimisation

    43. What is Elastic Net, and when would you use it?

    Elastic Net combines the L1 and L2 penalties: α × (r × Σ|w| + (1 − r)/2 × Σw²), where l1_ratio (r) sets the mix. It keeps Lasso’s ability to zero out features while behaving better when features are correlated. Lasso tends to pick one feature from a correlated group at random, whereas Elastic Net tends to keep or drop the group together.

    Use it when you have many correlated features, or more features than rows, and tune both alpha and l1_ratio with cross-validation (ElasticNetCV does this directly).

    Q44IntermediateModel evaluation

    44. How do you tune hyperparameters?

    • Grid search: tries every combination from lists you give. Thorough, but the cost multiplies with each new hyperparameter.
    • Random search: tries a fixed number of random combinations. Usually finds a good result faster, because only a few hyperparameters really matter.
    • Bayesian optimisation (Optuna, Hyperopt): uses past results to pick promising combinations next. Best when each training run is expensive.
    from sklearn.datasets import load_breast_cancer
    from sklearn.model_selection import GridSearchCV
    from sklearn.pipeline import make_pipeline
    from sklearn.preprocessing import StandardScaler
    from sklearn.svm import SVC
    
    X, y = load_breast_cancer(return_X_y=True)
    pipe = make_pipeline(StandardScaler(), SVC())
    grid = GridSearchCV(pipe, {"svc__C": [0.1, 1, 10, 100],
                               "svc__gamma": [0.001, 0.01, 0.1]}, cv=5)
    grid.fit(X, y)
    
    print("Best params:", grid.best_params_)
    print("Best CV accuracy:", round(grid.best_score_, 3))
    print("Combinations tried:", len(grid.cv_results_["params"]))

    Output:

    Best params: {'svc__C': 10, 'svc__gamma': 0.01}
    Best CV accuracy: 0.979
    Combinations tried: 12

    Always tune with cross-validation on the training data only, and put preprocessing inside a pipeline so it is refitted in every fold. Note the svc__C naming: the step name, two underscores, then the parameter.

    Q45IntermediateModel evaluation

    45. What is stratified k-fold cross-validation, and when do you need it?

    Stratified k-fold makes sure every fold has roughly the same class proportions as the full dataset. With plain k-fold on imbalanced data, a fold might end up with very few or even no positive examples, which makes its score meaningless and the overall estimate noisy.

    Use it for any classification problem, especially imbalanced ones; scikit-learn uses it by default when you pass an integer cv to a classifier. Do not use it for time series (use TimeSeriesSplit) or when rows are grouped, such as several rows per patient (use GroupKFold so one patient never appears in both train and test).

    Q46IntermediateModel evaluation

    46. How do you handle imbalanced data?

    • Use the right metrics: recall, precision, F1, PR AUC, not accuracy.
    • Give the rare class more weight: class_weight="balanced" in most scikit-learn models, scale_pos_weight in XGBoost.
    • Resample: oversample the minority class (randomly or with SMOTE) or undersample the majority, on the training data only.
    • Tune the decision threshold instead of using 0.5.
    • Collect more examples of the rare class if you can, or treat it as anomaly detection when positives are extremely rare.
    from sklearn.datasets import make_classification
    from sklearn.linear_model import LogisticRegression
    from sklearn.metrics import precision_score, recall_score
    from sklearn.model_selection import train_test_split
    
    X, y = make_classification(n_samples=10000, weights=[0.98], flip_y=0.01, random_state=3)
    X_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, random_state=3)
    
    for cw in [None, "balanced"]:
        pred = LogisticRegression(class_weight=cw, max_iter=1000).fit(X_tr, y_tr).predict(X_te)
        print(f"class_weight={str(cw):8s}  recall={recall_score(y_te, pred):.2f}  "
              f"precision={precision_score(y_te, pred):.2f}")

    Output:

    class_weight=None      recall=0.08  precision=0.33
    class_weight=balanced  recall=0.73  precision=0.12

    With 2% positives, the default model caught only 8% of them. Class weights raised recall to 73%, at the cost of more false alarms. Which balance is right depends on the cost of each kind of mistake.

    Q47IntermediateModel evaluation

    47. When should you use a precision-recall curve instead of a ROC curve?

    Use the precision-recall (PR) curve when the positive class is rare and you mostly care about it, as in fraud, disease or defect detection. ROC uses the false positive rate, whose denominator is the huge number of negatives, so even thousands of false alarms barely move it. Precision shows those false alarms directly.

    from sklearn.datasets import make_classification
    from sklearn.linear_model import LogisticRegression
    from sklearn.metrics import roc_auc_score, average_precision_score
    from sklearn.model_selection import train_test_split
    
    X, y = make_classification(n_samples=5000, weights=[0.95], random_state=1)
    X_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, random_state=1)
    
    proba = LogisticRegression(max_iter=1000).fit(X_tr, y_tr).predict_proba(X_te)[:, 1]
    print("ROC AUC:          ", round(roc_auc_score(y_te, proba), 3))
    print("PR AUC (avg prec):", round(average_precision_score(y_te, proba), 3))
    print("Positive rate:    ", round(y_te.mean(), 3))

    Output:

    ROC AUC:           0.926
    PR AUC (avg prec): 0.621
    Positive rate:     0.054

    With about 5% positives, ROC AUC is a comfortable 0.93, but PR AUC is only 0.62. The model is good at ranking, but many of its alerts would still be false. A random model has PR AUC equal to the positive rate (0.054 here), so always compare against that baseline.

    Q48IntermediateModel evaluation

    48. How do you choose the classification threshold?

    Most classifiers output a probability, and 0.5 is only a default. Choose the threshold from the cost of each error: for cancer screening, missing a malignant tumour is far worse than an extra biopsy, so you lower the threshold to raise recall.

    from sklearn.datasets import load_breast_cancer
    from sklearn.linear_model import LogisticRegression
    from sklearn.metrics import precision_score, recall_score
    from sklearn.model_selection import train_test_split
    from sklearn.pipeline import make_pipeline
    from sklearn.preprocessing import StandardScaler
    
    X, y = load_breast_cancer(return_X_y=True)
    y = 1 - y                                  # make 1 = malignant (the class we must catch)
    X_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, random_state=0)
    proba = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_tr, y_tr).predict_proba(X_te)[:, 1]
    
    for t in [0.5, 0.3, 0.1]:
        pred = (proba >= t).astype(int)
        print(f"threshold={t}  recall={recall_score(y_te, pred):.3f}  precision={precision_score(y_te, pred):.3f}")

    Output:

    threshold=0.5  recall=0.962  precision=1.000
    threshold=0.3  recall=0.962  precision=0.895
    threshold=0.1  recall=1.000  precision=0.828

    Lowering the threshold to 0.1 catches every malignant case (recall 1.0), at the cost of precision dropping to 0.83. Pick the threshold on validation data, using a cost formula, a minimum recall target, or the point that maximises F1. Never pick it on the test set.

    Q49IntermediateClassification

    49. What is log loss (cross-entropy)?

    Log loss measures how good predicted probabilities are, not just the final class. For one example with true label y and predicted probability p, it is −[y log p + (1 − y) log(1 − p)]. A confident correct prediction gives a loss near 0, and a confident wrong one gives a very large loss: predicting 0.01 for a true positive costs 4.6, while 0.4 costs 0.92.

    It is the loss that logistic regression and classification neural networks minimise, and it comes straight from maximum likelihood (question 68). For more than two classes it becomes categorical cross-entropy: −Σ yₖ log pₖ.

    Q50IntermediateClassification

    50. How do models handle multiclass classification, and what are macro, micro and weighted averages?

    Some models handle many classes natively: trees, Naive Bayes, KNN, and softmax regression or neural networks. Binary models are extended with one-vs-rest (one model per class against all others) or one-vs-one (one model per pair of classes, used by SVC).

    • Macro average: compute the metric for each class and take the plain average. Every class counts equally, so small classes matter.
    • Weighted average: like macro, but weighted by each class’s size.
    • Micro average: pool all TP, FP and FN first. For single-label problems, micro F1 equals accuracy.

    Report macro F1 when rare classes matter as much as common ones.

    Q51IntermediateTrees & ensembles

    51. What is the difference between bagging and boosting?

    BaggingBoosting
    How models are trainedIn parallel, each on a bootstrap sample (random sample with replacement)One after another, each fixing the errors of the previous ones
    Main effectReduces varianceReduces bias (and variance, when tuned)
    Base modelsUsually deep, low-bias treesUsually shallow trees
    Overfitting riskLowHigher; needs a learning rate and early stopping
    ExamplesRandom forest, bagged treesAdaBoost, gradient boosting, XGBoost, LightGBM, CatBoost

    On tabular data, a well-tuned gradient boosting model usually beats a random forest, while the random forest needs much less tuning.

    Q52IntermediateTrees & ensembles

    52. How does a random forest work?

    A random forest trains many decision trees, each on a bootstrap sample of the rows, and at every split each tree considers only a random subset of the features (max_features). Classification takes a majority vote; regression takes the average. The two kinds of randomness make the trees different from each other, so their errors partly cancel out.

    from sklearn.datasets import load_breast_cancer
    from sklearn.ensemble import RandomForestClassifier
    from sklearn.model_selection import train_test_split
    from sklearn.tree import DecisionTreeClassifier
    
    X, y = load_breast_cancer(return_X_y=True)
    X_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, random_state=0)
    
    tree = DecisionTreeClassifier(random_state=0).fit(X_tr, y_tr)
    rf = RandomForestClassifier(n_estimators=300, oob_score=True, random_state=0).fit(X_tr, y_tr)
    
    print("Single tree test accuracy:  ", round(tree.score(X_te, y_te), 3))
    print("Random forest test accuracy:", round(rf.score(X_te, y_te), 3))
    print("Random forest OOB score:    ", round(rf.oob_score_, 3))

    Output:

    Single tree test accuracy:   0.902
    Random forest test accuracy: 0.944
    Random forest OOB score:     0.962

    Each tree leaves out about 37% of the rows from its bootstrap sample. Predicting each row with only the trees that did not see it gives the out-of-bag (OOB) score, a free validation estimate. Main hyperparameters: n_estimators, max_features, max_depth, min_samples_leaf.

    Q53IntermediateTrees & ensembles

    53. How does gradient boosting work, and what are its key hyperparameters?

    Gradient boosting builds trees one after another. It starts with a simple prediction (such as the average), then each new shallow tree is trained to predict the gradient of the loss, which for squared error is just the residuals of the current model. The new tree’s output, multiplied by a small learning rate, is added to the model. Step by step the ensemble corrects its own mistakes.

    • learning_rate: how much each tree contributes. Smaller is usually better but needs more trees.
    • n_estimators: number of trees; choose it with early stopping (question 85).
    • max_depth (often 3 to 8): how complex each tree is.
    • subsample and column sampling: add randomness and reduce overfitting.
    • Regularisation terms in XGBoost: lambda, alpha, gamma, min_child_weight.
    Q54IntermediateTrees & ensembles

    54. How does AdaBoost work?

    AdaBoost (adaptive boosting) trains a sequence of weak learners, usually one-split trees called stumps. After each round it increases the weights of the examples that were misclassified, so the next learner focuses on the hard cases. Each learner also gets a vote weight based on its accuracy, and the final prediction is the weighted vote of all of them.

    It was the first practical boosting algorithm. Gradient boosting generalises the idea to any differentiable loss. Because AdaBoost keeps raising the weight of misclassified points, it is sensitive to noisy labels and outliers.

    Q55IntermediateData & features

    55. How do you measure feature importance?

    • Coefficients of linear models, on scaled features.
    • Impurity-based importance (feature_importances_) in trees: fast, but biased towards features with many unique values and computed on training data.
    • Permutation importance: shuffle one feature in the validation set and measure how much the score drops. Model-agnostic and more reliable.
    • SHAP values: how much each feature pushed each individual prediction up or down (question 88).
    import numpy as np
    from sklearn.datasets import load_diabetes
    from sklearn.ensemble import RandomForestRegressor
    from sklearn.inspection import permutation_importance
    from sklearn.model_selection import train_test_split
    
    data = load_diabetes()
    X_tr, X_te, y_tr, y_te = train_test_split(data.data, data.target, random_state=0)
    rf = RandomForestRegressor(random_state=0).fit(X_tr, y_tr)
    
    result = permutation_importance(rf, X_te, y_te, n_repeats=10, random_state=0)
    for i in np.argsort(result.importances_mean)[::-1][:4]:
        print(f"{data.feature_names[i]:4s} drop in R2 when shuffled: {result.importances_mean[i]:.3f}")

    Output:

    bmi  drop in R2 when shuffled: 0.114
    s5   drop in R2 when shuffled: 0.094
    bp   drop in R2 when shuffled: 0.043
    age  drop in R2 when shuffled: 0.018

    Shuffling BMI drops R² by 0.11, so the model relies on it most. If two features are strongly correlated, permutation importance can underrate both, because the model can still use the other one. Reference: scikit-learn permutation importance.

    Q56IntermediateData & features

    56. What are the main feature selection methods?

    • Filter methods: score each feature on its own, without a model: correlation, chi-square, mutual information, ANOVA F-test. Fast, but they ignore interactions.
    • Wrapper methods: try subsets of features with a model and keep the best: forward selection, backward elimination, recursive feature elimination (RFE). Accurate but slow.
    • Embedded methods: selection happens during training: Lasso, tree-based importance, SelectFromModel.

    Fewer features means faster training, less overfitting and simpler explanations. Whatever the method, do the selection inside cross-validation, or you get the leakage shown in question 15.

    Q57IntermediateRegression

    57. What is multicollinearity, and why does it matter?

    Multicollinearity means two or more features are strongly correlated, such as flat size in square feet and number of rooms. Predictions may still be fine, but the individual coefficients of a linear model become unstable: they can swing wildly or even change sign with small changes in the data, so you cannot trust them for explanation.

    Detect it with a correlation matrix or the variance inflation factor (VIF); a VIF above about 5 to 10 is a warning. Fix it by dropping or combining correlated features, using PCA, or using Ridge regression, which handles correlated features gracefully.

    Q58IntermediateTrees & ensembles

    58. What is pruning in decision trees?

    Pruning makes a decision tree smaller so it generalises better. Pre-pruning stops growth early with limits such as max_depth, min_samples_split, min_samples_leaf or max_leaf_nodes. Post-pruning grows the full tree and then removes branches that do not earn their place; scikit-learn uses cost complexity pruning with ccp_alpha.

    Tune either kind with cross-validation. The decision tree guide shows a fully grown tree with 18 leaves losing to a pruned one with 11.

    Q59IntermediateClassification

    59. What is the kernel trick, and what do C and gamma do in an SVM?

    The kernel trick lets an SVM act as if the data had been mapped into a higher-dimensional space where it becomes linearly separable, without ever computing that mapping. It only needs a kernel function that returns the dot product in that space. Common kernels: linear, polynomial and RBF (Gaussian).

    C controls how strongly misclassified points are punished: large C fits the training data tightly and can overfit, while small C gives a wider, smoother margin. gamma (for RBF) controls how far one point’s influence reaches: large gamma gives very wiggly boundaries, small gamma very smooth ones. Tune them together on a log scale.

    Q60IntermediateUnsupervised

    60. When would you use DBSCAN instead of k-means?

    DBSCAN groups points that are packed closely together (at least min_samples points within distance eps) and marks points in sparse areas as noise. Choose it when:

    • clusters have irregular shapes, such as moons or rings, which k-means cuts with straight lines;
    • you do not know the number of clusters;
    • you want outliers flagged instead of forced into a cluster.

    Its weaknesses: it struggles when clusters have very different densities, and eps is hard to choose in high dimensions. HDBSCAN fixes much of this.

    Q61IntermediateUnsupervised

    61. How does hierarchical clustering work?

    Agglomerative hierarchical clustering starts with every point as its own cluster and repeatedly merges the two closest clusters until only one is left. The full history of merges is drawn as a tree called a dendrogram, and you choose the number of clusters by cutting the tree at a certain height.

    The linkage decides what “closest” means: single (nearest points), complete (furthest points), average, or Ward (smallest increase in variance, the usual default). It needs no K up front and shows the structure at every level, but it uses O(n²) memory, so it suits small to medium datasets.

    Q62IntermediateUnsupervised

    62. How does PCA work, and how do you choose the number of components?

    PCA centres (and usually scales) the data, computes the covariance matrix, and finds its eigenvectors and eigenvalues. The eigenvectors are the principal components, the directions of the new axes, and each eigenvalue tells how much variance that direction holds. In practice it is computed with singular value decomposition (SVD), which is faster and more stable.

    To choose how many components to keep, plot the cumulative explained variance and keep enough for 90 to 95% (question 36 needed 21 of 64 for 90%), look for an elbow in the scree plot, or tune the number of components as a hyperparameter of the model that uses them.

    Q63IntermediateUnsupervised

    63. How are t-SNE and UMAP different from PCA?

    PCA is linear and keeps the large-scale structure, such as overall spread. t-SNE and UMAP are non-linear methods built mainly for visualisation: they keep neighbourhoods, so points that are close in the original space stay close in 2D, and clusters show up clearly.

    • Distances between clusters and cluster sizes in a t-SNE plot do not mean much.
    • t-SNE is slow on large data and has no simple way to transform new points; UMAP is faster and can.
    • Use PCA for preprocessing and compression; use t-SNE or UMAP to look at embeddings or clusters.
    Q64IntermediateData & features

    64. What is a scikit-learn Pipeline, and why should you use one?

    A Pipeline chains preprocessing steps and a model into a single object with one fit and one predict. A ColumnTransformer applies different steps to different columns.

    import pandas as pd
    from sklearn.compose import ColumnTransformer
    from sklearn.impute import SimpleImputer
    from sklearn.linear_model import LogisticRegression
    from sklearn.pipeline import Pipeline
    from sklearn.preprocessing import OneHotEncoder, StandardScaler
    
    df = pd.DataFrame({"age": [22, 35, None, 51, 46, 29], "city": ["Surat", "Pune", "Pune", None, "Delhi", "Surat"],
                       "income": [3.2, 8.5, 6.1, 12.0, 9.4, 4.0], "bought": [0, 1, 0, 1, 1, 0]})
    X, y = df.drop(columns="bought"), df["bought"]
    
    prep = ColumnTransformer([
        ("num", Pipeline([("impute", SimpleImputer(strategy="median")), ("scale", StandardScaler())]), ["age", "income"]),
        ("cat", Pipeline([("impute", SimpleImputer(strategy="most_frequent")),
                          ("onehot", OneHotEncoder(handle_unknown="ignore"))]), ["city"]),
    ])
    model = Pipeline([("prep", prep), ("clf", LogisticRegression())]).fit(X, y)
    
    new = pd.DataFrame({"age": [40], "city": ["Mumbai"], "income": [10.0]})   # unseen city
    print("Prediction:", model.predict(new), "| P(buy):", model.predict_proba(new)[0, 1].round(3))

    Output:

    Prediction: [1] | P(buy): 0.741
    • It prevents leakage: during cross-validation, imputers and scalers are fitted only on the training folds.
    • The exact same steps run in training and in production, so there is no training-serving skew.
    • It handles unseen values safely, like the new city “Mumbai” above, thanks to handle_unknown="ignore".
    • You can tune preprocessing and model hyperparameters together with GridSearchCV.
    Q65IntermediateModel evaluation

    65. How do you validate a model on time series data?

    Never shuffle time series data before splitting. A random split lets the model train on the future and test on the past, which is leakage, and the score will look far better than it will be in production. Train on the past and test on the period right after it.

    import numpy as np
    from sklearn.model_selection import TimeSeriesSplit
    
    days = np.arange(12)                          # 12 days of data, in time order
    for i, (train, test) in enumerate(TimeSeriesSplit(n_splits=3).split(days), 1):
        print(f"Fold {i}: train days {train.min()}-{train.max()}, test days {test.min()}-{test.max()}")

    Output:

    Fold 1: train days 0-2, test days 3-5
    Fold 2: train days 0-5, test days 6-8
    Fold 3: train days 0-8, test days 9-11

    TimeSeriesSplit does this with an expanding window. Also make sure features only use information available at prediction time, for example lag features and rolling averages that stop at the day before.

    Q66IntermediateRegression

    66. How do you check whether a regression model is good beyond its score?

    Look at the residuals (actual minus predicted). Plot them against the predictions: a random cloud around zero is good. Patterns mean problems:

    • A curve means the relationship is not linear; add features or use a non-linear model.
    • A funnel shape (spread growing with the prediction) is heteroscedasticity; try a log transform of the target or a model that handles it.
    • Residuals that follow each other over time mean the errors are autocorrelated, often missing time features.
    • A few huge residuals point to outliers or data errors.

    Also compare against a simple baseline, such as predicting the mean or last week’s value. A model has to beat it to be worth using.

    Q67IntermediateClassification

    67. What is the difference between generative and discriminative models?

    A discriminative model learns the boundary between classes directly, P(y | x). Examples: logistic regression, SVM, decision trees, most neural network classifiers. A generative model learns how the data of each class is produced, P(x | y) and P(y), or the joint P(x, y), and uses Bayes’ rule to classify. Examples: Naive Bayes, Gaussian mixture models, hidden Markov models.

    Discriminative models usually classify more accurately when there is plenty of data. Generative models can work with less data, handle missing features and can generate new samples. Today’s generative AI models, such as large language models, are generative models of text.

    Q68IntermediateOptimisation

    68. What is maximum likelihood estimation, and how does it relate to loss functions?

    Maximum likelihood estimation (MLE) chooses the parameters that make the observed data most probable under the model. Taking the negative log of the likelihood turns a product into a sum and a maximisation into a minimisation, which gives the familiar loss functions:

    • If you assume Gaussian noise around a linear prediction, MLE gives mean squared error, so ordinary least squares is MLE.
    • If you assume the label follows a Bernoulli distribution with probability σ(wx + b), MLE gives log loss, which is logistic regression.
    • Adding a prior on the weights gives MAP estimation; a Gaussian prior is L2 regularisation, a Laplace prior is L1.
    Q69IntermediateDeep learning

    69. How does backpropagation work?

    Backpropagation computes the gradient of the loss with respect to every weight in a network. In the forward pass, inputs flow through the layers to produce a prediction and a loss. In the backward pass, the chain rule is applied from the output back to the input: each layer receives the gradient from the layer after it, multiplies by its own local derivative, and passes the result back. Gradient descent then updates every weight.

    import numpy as np
    
    # One neuron: y_hat = sigmoid(w*x + b), loss = (y_hat - y)^2
    x, y = 2.0, 1.0
    w, b = 0.5, 0.0
    
    z = w * x + b
    y_hat = 1 / (1 + np.exp(-z))
    loss = (y_hat - y) ** 2
    
    # Chain rule, from the loss back to the weights
    dloss_dyhat = 2 * (y_hat - y)
    dyhat_dz = y_hat * (1 - y_hat)
    dz_dw, dz_db = x, 1.0
    dw = dloss_dyhat * dyhat_dz * dz_dw
    db = dloss_dyhat * dyhat_dz * dz_db
    
    print(f"prediction={y_hat:.4f}  loss={loss:.4f}")
    print(f"dLoss/dw={dw:.4f}  dLoss/db={db:.4f}")
    w -= 0.5 * dw; b -= 0.5 * db
    print(f"after one step: prediction={1 / (1 + np.exp(-(w * x + b))):.4f}")

    Output:

    prediction=0.7311  loss=0.0723
    dLoss/dw=-0.2115  dLoss/db=-0.1058
    after one step: prediction=0.7798

    For one neuron the chain is dLoss/dw = dLoss/dŷ × dŷ/dz × dz/dw. After a single update the prediction moves from 0.731 towards the target of 1. Frameworks like PyTorch and TensorFlow do this automatically (autograd), but interviewers like to see that you can do it by hand.

    Q70IntermediateDeep learning

    70. What are vanishing and exploding gradients?

    In deep networks the gradient is a product of many layer derivatives. If those are mostly smaller than 1, the gradient shrinks towards zero as it travels back, so the early layers barely learn: vanishing gradients. Sigmoid and tanh cause this because their slopes are tiny for large inputs. If the factors are larger than 1, the gradient grows huge and training blows up: exploding gradients, common in RNNs.

    • ReLU-family activations instead of sigmoid in hidden layers.
    • Careful weight initialisation (He for ReLU, Xavier/Glorot for tanh).
    • Batch normalisation or layer normalisation.
    • Residual (skip) connections, as in ResNets and transformers.
    • Gradient clipping for exploding gradients; LSTM or GRU cells instead of plain RNNs.
    Q71IntermediateDeep learning

    71. What are dropout and batch normalisation?

    Dropout randomly switches off a fraction of neurons (for example 20 to 50%) in each training step, so the network cannot rely on any single neuron and learns more robust features. It acts like training many smaller networks and averaging them. Dropout is turned off at inference time.

    Batch normalisation normalises each layer’s inputs to mean 0 and variance 1 within the mini-batch, then applies a learned scale and shift. It makes training faster and more stable, allows higher learning rates and adds a little regularisation. At inference it uses running averages collected during training. Transformers use layer normalisation instead, which normalises across features for each example and does not depend on batch size.

    Q72IntermediateDeep learning

    72. What is a convolutional neural network (CNN)?

    A CNN is a neural network designed for grid-like data such as images. Instead of connecting every pixel to every neuron, a convolutional layer slides small filters (for example 3×3) across the image. Each filter learns to detect a pattern, like an edge or a texture, anywhere in the image. Pooling layers shrink the feature maps, and fully connected layers at the end make the prediction.

    Because the same filter is reused everywhere (weight sharing), CNNs need far fewer parameters than fully connected networks and handle shifted objects well. Early layers learn edges, later layers learn shapes and objects. Uses: image classification, object detection, medical imaging, and some audio and text tasks.

    Q73IntermediateDeep learning

    73. What are RNNs and LSTMs?

    A recurrent neural network (RNN) processes a sequence one step at a time and keeps a hidden state that carries information from earlier steps. That suits text, speech and time series. Plain RNNs struggle with long sequences because of vanishing gradients, so they forget early information.

    An LSTM (long short-term memory) adds a cell state and three gates (forget, input and output) that learn what to keep, add and output, so it can remember information over much longer spans. A GRU is a simpler variant with two gates. For most language tasks, transformers (question 91) have replaced RNNs because they process all positions in parallel and handle long-range context better.

    Q74IntermediateDeep learning

    74. What are word embeddings?

    Word embeddings represent each word as a dense vector of numbers, often 100 to 1,000 values, learned so that words used in similar contexts get similar vectors. Unlike one-hot vectors, they capture meaning: “king” and “queen” are close, and directions in the space can capture relationships, as in the famous king − man + woman ≈ queen.

    Word2Vec and GloVe give each word one fixed vector. Modern models such as BERT and GPT produce contextual embeddings, where “bank” in “river bank” and “bank loan” gets different vectors. Sentence and document embeddings power semantic search and RAG systems (question 95).

    Q75IntermediateDeep learning

    75. What is transfer learning?

    Transfer learning reuses a model trained on a large dataset as the starting point for a new, related task. An image model trained on ImageNet already knows edges, textures and shapes, so you can replace its last layer and train only that on a few thousand images of, say, plant diseases. You can also fine-tune some or all of the earlier layers with a small learning rate.

    It needs much less data and compute, and it usually gives better accuracy than training from scratch. It is the standard approach in computer vision and NLP: fine-tuning BERT for classification and adapting large language models (question 94) are both transfer learning.

    Machine learning interview questions for experienced candidates

    These 25 questions are for senior data scientists and ML engineers: production problems, drift and monitoring, deployment, boosting internals, explainability and fairness, plus transformers, LLM training, RAG and fine-tuning.

    Q76ExperiencedML in production

    76. How do you approach an end-to-end machine learning project?

    1. Frame the problem: what decision will the model support, what does success look like in business terms, and is ML even needed? Agree on a metric and a baseline.
    2. Get and understand the data: sources, labels, quality, leakage risks, and how the data will be available at prediction time.
    3. Build a simple baseline (a rule, or logistic regression) to know what “good” means.
    4. Iterate: features, models and tuning, judged with honest validation that matches how the model will be used (time-based splits, grouped splits).
    5. Analyse errors: look at where the model fails, by segment, not just at the overall score.
    6. Deploy with a reproducible pipeline, then monitor data, predictions and business metrics, and plan retraining.

    Interviewers listen for the first and last steps most, because that is where real projects usually fail.

    Q77ExperiencedML in production

    77. Your model scored well offline but performs badly in production. What could be wrong?

    • Data leakage in training: a feature that is not really available at prediction time, or preprocessing fitted on all the data.
    • Training-serving skew: features computed differently in the batch training code and the live service, different units, or different handling of missing values.
    • Wrong validation: a random split on time-ordered or grouped data, so the offline score was too optimistic.
    • Data or concept drift since training (next question).
    • Feedback loops: the model’s own decisions change the data it later sees, for example a fraud model blocking transactions so their labels are never observed.
    • Bugs: wrong model version, stale features, a different threshold.

    Debug by logging the exact features the live model receives and comparing them with the training data for the same entities.

    Q78ExperiencedML in production

    78. What is the difference between data drift and concept drift, and how do you monitor them?

    Data drift (covariate shift) means the distribution of the inputs changes: a new marketing campaign brings in younger users. Concept drift means the relationship between inputs and the target changes: after a policy change, the same customer profile now defaults at a different rate. Concept drift is worse, because the model’s learned rules are now wrong.

    • Monitor input feature distributions against training: population stability index (PSI), KL divergence, Kolmogorov-Smirnov tests.
    • Monitor the distribution of predictions and the share of each predicted class.
    • When labels arrive (often with a delay), track the real metrics over time and by segment.
    • Set alerts, and retrain on a schedule or when drift crosses a limit, then validate before replacing the old model.
    Q79ExperiencedML in production

    79. How do you deploy a machine learning model?

    The first choice is between batch and online prediction. Batch scoring runs on a schedule and stores the results, which is simple and cheap and works for things like daily churn scores or nightly recommendations. Online serving exposes the model behind an API (FastAPI, TorchServe, a managed endpoint) for real-time requests such as fraud checks, where latency matters.

    • Package the whole pipeline (preprocessing and model) with fixed library versions, usually in a Docker container.
    • Track model versions, training data and metrics in a model registry (MLflow and similar tools).
    • Release safely: shadow mode (score live traffic without acting on it), canary rollout or an A/B test.
    • Log inputs and predictions for monitoring and future retraining, and keep a way to roll back.
    Q80ExperiencedML in production

    80. How do you A/B test a new model, and why can offline and online metrics disagree?

    Randomly split live users or requests between the current model (control) and the new one (treatment), decide the primary business metric and the sample size in advance, run long enough to cover weekly patterns, and check for a statistically significant difference. Also watch guardrail metrics such as latency, complaints and revenue.

    Offline metrics like AUC or RMSE measure prediction quality on past data. Online metrics measure what the business cares about, such as clicks, conversions or losses, and they include effects that offline data cannot show: user behaviour changing in response to the model, position bias in recommendations, and the new model’s effect on future data. That is why a better offline model sometimes loses online.

    Q81ExperiencedML in production

    81. How do you train a model when the data does not fit in memory?

    • Start by sampling: a well-chosen sample of a few million rows is often enough to choose features and models.
    • Use efficient types: smaller numeric types, categoricals, and columnar formats like Parquet.
    • Process in chunks, and use models that learn incrementally with partial_fit (SGDClassifier, MiniBatchKMeans, naive Bayes).
    • Use libraries built for big data: LightGBM and XGBoost with external memory, Dask, or Spark MLlib on a cluster.
    • For deep learning, stream mini-batches from disk with data loaders and use several GPUs if needed.
    • Push aggregations to the database or data warehouse with SQL, so only the features come back.
    Q82ExperiencedML in production

    82. How do recommendation systems work?

    Content-based filtering recommends items similar to what a user liked, using item features such as genre or product category. Collaborative filtering uses behaviour: users who liked the same things in the past will like similar things in future. Matrix factorisation learns a vector for every user and every item so that their dot product predicts the rating or click. Most real systems are hybrids, often in two stages: fast candidate generation (for example with embeddings and nearest-neighbour search), then a ranking model on the shortlist.

    Topics interviewers probe: the cold-start problem for new users and items (fall back to content features or popularity), implicit feedback (clicks, watch time) versus explicit ratings, and ranking metrics like precision@k, recall@k, MAP and NDCG.

    Q83ExperiencedModel evaluation

    83. What is probability calibration, and why does it matter?

    A model is well calibrated if, among all the cases where it predicts 70%, about 70% really are positive. Many models rank cases well but give poorly calibrated probabilities: Naive Bayes is usually overconfident, SVMs do not output probabilities at all, and boosted trees can be skewed. Calibration matters whenever the probability itself is used, such as expected loss = probability × amount, or comparing risk across models.

    from sklearn.calibration import CalibratedClassifierCV
    from sklearn.datasets import make_classification
    from sklearn.metrics import brier_score_loss
    from sklearn.model_selection import train_test_split
    from sklearn.naive_bayes import GaussianNB
    
    X, y = make_classification(n_samples=20000, n_features=20, n_informative=4,
                               n_redundant=10, random_state=0)
    X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.5, random_state=0)
    
    raw = GaussianNB().fit(X_tr, y_tr)
    cal = CalibratedClassifierCV(GaussianNB(), method="isotonic", cv=5).fit(X_tr, y_tr)
    
    print("Brier score, raw Naive Bayes:", round(brier_score_loss(y_te, raw.predict_proba(X_te)[:, 1]), 4))
    print("Brier score, calibrated:     ", round(brier_score_loss(y_te, cal.predict_proba(X_te)[:, 1]), 4))

    Output:

    Brier score, raw Naive Bayes: 0.1852
    Brier score, calibrated:      0.1578

    Fix it with Platt scaling (a logistic fit on the scores) or isotonic regression on held-out data, using CalibratedClassifierCV. Check it with a reliability curve (CalibrationDisplay) and the Brier score, which fell from 0.185 to 0.158 here. Lower is better.

    Q84ExperiencedBasics

    84. Explain the bias-variance decomposition.

    For squared error, the expected test error at a point x, averaged over many possible training sets, splits into three parts:

    E[(y − f̂(x))²] = Bias[f̂(x)]² + Var[f̂(x)] + σ²

    • Bias²: how far the average prediction across training sets is from the truth. It comes from the model’s assumptions.
    • Variance: how much the prediction changes from one training set to another. It comes from sensitivity to the sample.
    • σ²: irreducible noise in the labels, which no model can remove.

    Bagging lowers variance by averaging, boosting mainly lowers bias, and regularisation trades a little bias for less variance. Very large neural networks show “double descent”, where test error falls again past the point of fitting the training data perfectly, so the classic U-shaped curve is a guide rather than a law.

    Q85ExperiencedTrees & ensembles

    85. How do the learning rate and early stopping work together in gradient boosting?

    Each new tree adds learning_rate × its prediction. A large learning rate fits the training data fast but overshoots and overfits after few trees; a small one takes many more trees but generalises better. Early stopping keeps adding trees only while the score on a validation set keeps improving, so you do not have to guess n_estimators.

    from sklearn.datasets import make_classification
    from sklearn.ensemble import GradientBoostingClassifier
    from sklearn.model_selection import train_test_split
    
    X, y = make_classification(n_samples=3000, n_features=20, flip_y=0.1, random_state=0)
    X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)
    
    for lr in [1.0, 0.1]:
        gb = GradientBoostingClassifier(learning_rate=lr, n_estimators=1000, n_iter_no_change=20,
                                        validation_fraction=0.2, random_state=0).fit(X_tr, y_tr)
        print(f"learning_rate={lr}: stopped at {gb.n_estimators_} trees, "
              f"test accuracy {gb.score(X_te, y_te):.3f}")

    Output:

    learning_rate=1.0: stopped at 21 trees, test accuracy 0.904
    learning_rate=0.1: stopped at 54 trees, test accuracy 0.936

    With learning rate 1.0, training stopped after 21 trees at 90.4% test accuracy; with 0.1 it used 54 trees and reached 93.6%. A common recipe is a small learning rate (0.01 to 0.1), a high tree limit, and early stopping on a validation set.

    Q86ExperiencedTrees & ensembles

    86. What makes XGBoost different from classic gradient boosting?

    • Regularised objective: it adds penalties on the number of leaves (gamma) and the leaf weights (lambda, alpha), which reduces overfitting.
    • Second-order optimisation: it uses both the gradient and the Hessian (curvature) of the loss to choose splits and leaf values, which is more accurate per tree.
    • Sparsity-aware splits: each split learns a default direction for missing values.
    • Speed: histogram-based split finding, parallel tree building, cache-aware data layout, GPU support and out-of-core training.
    • Row and column subsampling, and built-in cross-validation and early stopping.
    Q87ExperiencedTrees & ensembles

    87. How do LightGBM, XGBoost and CatBoost compare?

    XGBoostLightGBMCatBoost
    Tree growthLevel by level (depth-wise) by defaultLeaf by leaf: grows the best leaf firstSymmetric (oblivious) trees
    Speed on large dataFastUsually fastestSlower to train, fast to predict
    Categorical featuresNeeds encoding (native support is newer)Native supportBest native support, with ordered target statistics
    Overfitting riskMediumHigher on small data; limit num_leavesLower; good defaults
    Good choice whenYou want a mature, widely used defaultData is very largeMany categorical features, little tuning time

    All three are close in accuracy after tuning. In practice, try whichever fits your data, and spend the saved time on features.

    Q88ExperiencedData & features

    88. How do SHAP and LIME explain a model’s predictions?

    SHAP (SHapley Additive exPlanations) uses Shapley values from game theory: each feature gets a share of the difference between this prediction and the average prediction, and the shares add up exactly to that difference. TreeSHAP computes them exactly and quickly for tree models. You get local explanations (“why was this loan rejected?”) and global ones (average absolute SHAP per feature).

    LIME builds a simple, interpretable model, usually a linear one, around a single prediction by perturbing the input and watching how the output changes. It is model-agnostic and fast, but its explanations can change from run to run and depend on how the neighbourhood is defined. SHAP is more consistent and is the usual choice today; both explain the model, not the real world, so correlated features can still mislead.

    Q89ExperiencedML in production

    89. How do you find and reduce bias (unfairness) in a model?

    Models learn whatever patterns are in the data, including historical discrimination, and proxy features (such as pin code standing in for community or income) can bring it back even after you drop sensitive columns.

    • Measure: compare metrics across groups: selection rate (demographic parity), true positive rate (equal opportunity), false positive rate, and calibration by group.
    • Before training: fix sampling and labelling problems, reweight under-represented groups, remove clear proxies.
    • During training: fairness constraints or regularisation (for example with Fairlearn).
    • After training: group-specific thresholds where the law and policy allow.
    • Document the choices, because some fairness definitions cannot all be satisfied at once.
    Q90ExperiencedModel evaluation

    90. How do you choose the right metric for a business problem?

    Start from the decision the model supports and the cost of each kind of mistake, not from the most familiar metric. For a fraud model, a missed fraud might cost ₹20,000 and a false alarm ₹200 of review time. Then you can write the expected cost for each threshold and pick the cheapest one, instead of optimising accuracy or AUC.

    • Ranking problems (which leads to call first): precision@k, recall@k, NDCG.
    • Probability-based decisions: log loss, Brier score, calibration.
    • Regression with big costly errors: RMSE; with outliers: MAE; for relative errors: MAPE (careful near zero).
    • Keep one primary metric and a few guardrail metrics, such as latency or false positive rate.
    Q91ExperiencedGenAI & LLMs

    91. What is a transformer, and why did it replace RNNs?

    A transformer is a neural network architecture built around self-attention (next question) instead of recurrence. Each layer lets every token look at every other token directly, then passes the result through a small feed-forward network, with residual connections and layer normalisation around both. Positional encodings add word-order information, since attention by itself ignores order.

    • It processes all tokens in parallel, so it trains much faster on GPUs than an RNN, which must go step by step.
    • Any two tokens are one step apart, so long-range dependencies are easy to learn.
    • It scales very well with data and compute, which made large language models possible.

    Encoder-only transformers (BERT) are used for understanding tasks like classification, decoder-only ones (GPT, Claude, Llama) for text generation, and encoder-decoder ones (T5) for translation and summarisation. The original paper is “Attention Is All You Need” (2017).

    Q92ExperiencedGenAI & LLMs

    92. How does self-attention work?

    Each token’s embedding is multiplied by three learned matrices to get a query (what am I looking for?), a key (what do I contain?) and a value (what do I pass on?). The attention weights are softmax(QKᵀ / √d), and each token’s output is the weighted sum of all the values. Dividing by √d keeps the dot products from growing so large that softmax saturates.

    import numpy as np
    
    def softmax(z):
        e = np.exp(z - z.max(axis=-1, keepdims=True))
        return e / e.sum(axis=-1, keepdims=True)
    
    rng = np.random.default_rng(0)
    x = rng.normal(size=(3, 4))                  # 3 tokens, each a 4-number embedding
    Wq, Wk, Wv = (rng.normal(size=(4, 4)) for _ in range(3))
    
    Q, K, V = x @ Wq, x @ Wk, x @ Wv
    weights = softmax(Q @ K.T / np.sqrt(K.shape[1]))   # how much each token looks at the others
    output = weights @ V
    
    print("Attention weights (each row sums to 1):")
    print(weights.round(3))
    print("Output shape:", output.shape)

    Output:

    Attention weights (each row sums to 1):
    [[0.384 0.3   0.315]
     [0.321 0.206 0.473]
     [0.053 0.008 0.939]]
    Output shape: (3, 4)

    Each row shows how much one token attends to each of the three tokens, and each row sums to 1. Multi-head attention runs several of these in parallel with different matrices, so different heads can track different relationships. In decoder models a causal mask stops a token from looking at future tokens. The cost grows with the square of the sequence length, which is why long context windows are expensive.

    Q93ExperiencedGenAI & LLMs

    93. How are large language models trained?

    1. Pre-training: a decoder-only transformer learns to predict the next token over a huge text corpus. This self-supervised step is where most knowledge and ability come from, and it costs the most compute.
    2. Supervised fine-tuning (SFT): the model is trained on curated examples of prompts and good responses, so it learns to follow instructions and hold a conversation.
    3. Preference tuning: humans (or a model) compare responses, and the model is trained to prefer the better ones, with RLHF (a reward model plus reinforcement learning such as PPO) or simpler methods like DPO. This improves helpfulness and safety.

    Inference is autoregressive: the model generates one token at a time, each time feeding its own output back in, using a sampling strategy (question 97). Techniques like quantisation and KV caching make this cheaper and faster.

    Q94ExperiencedGenAI & LLMs

    94. When would you use prompt engineering, RAG or fine-tuning?

    ApproachWhat it changesUse it when
    Prompt engineeringOnly the input: instructions, examples (few-shot), output formatAlways start here; cheap and fast to iterate
    RAG (retrieval-augmented generation)Adds relevant documents to the prompt at query timeThe model needs private, large or frequently changing knowledge, and answers must cite sources
    Fine-tuningThe model’s weights, using your examplesYou need a consistent style or format, a narrow task done cheaply by a smaller model, or behaviour prompts cannot get

    A common mistake is fine-tuning to add knowledge. Facts learned that way are hard to update and easy to hallucinate, so RAG is usually better for knowledge, and fine-tuning for behaviour. Many production systems combine all three.

    Q95ExperiencedGenAI & LLMs

    95. How does a RAG pipeline work, and what are embeddings and vector databases for?

    1. Ingest: split documents into chunks (for example a few hundred tokens with some overlap).
    2. Embed: turn each chunk into a vector with an embedding model, so chunks with similar meaning get similar vectors.
    3. Store the vectors in a vector database or index (FAISS, pgvector, Pinecone, Chroma) that supports fast approximate nearest-neighbour search.
    4. Retrieve: embed the user’s question and fetch the most similar chunks, often combined with keyword search (hybrid) and a re-ranking model.
    5. Generate: put the retrieved chunks into the prompt and ask the LLM to answer only from them, with citations.

    Most RAG failures are retrieval failures, so evaluate retrieval on its own (recall@k for known question and document pairs) as well as the final answers.

    Q96ExperiencedGenAI & LLMs

    96. What is hallucination, and how do you evaluate LLM outputs?

    A hallucination is fluent, confident output that is false or not supported by the given sources, such as an invented citation or a wrong figure. It happens because the model generates likely-sounding text, not checked facts.

    • Reduce it: ground answers with RAG, tell the model to say “I don’t know” when the context lacks the answer, ask for citations, lower the temperature for factual tasks, and use structured outputs.
    • Evaluate: build a test set of real questions with reference answers; measure faithfulness to sources, answer correctness and relevance; use human review plus “LLM as a judge” scoring with a clear rubric, checked against human labels.
    • Track these metrics over time, like any other model, because prompts, models and documents change.
    Q97ExperiencedGenAI & LLMs

    97. What are tokens, temperature and top-p in LLMs?

    Tokens are the pieces of text a model reads and writes: whole words, parts of words or punctuation, produced by a tokenizer such as BPE. Context limits, speed and API pricing are all counted in tokens. For the next token, the model outputs a score (logit) for every token in its vocabulary.

    import numpy as np
    
    logits = np.array([2.0, 1.0, 0.5, -1.0])      # model scores for 4 possible next words
    words = ["Surat", "Mumbai", "Pune", "Paris"]
    
    for T in [0.5, 1.0, 2.0]:
        p = np.exp(logits / T) / np.exp(logits / T).sum()
        print(f"T={T}: " + ", ".join(f"{w} {q:.2f}" for w, q in zip(words, p)))

    Output:

    T=0.5: Surat 0.84, Mumbai 0.11, Pune 0.04, Paris 0.00
    T=1.0: Surat 0.61, Mumbai 0.22, Pune 0.14, Paris 0.03
    T=2.0: Surat 0.43, Mumbai 0.26, Pune 0.21, Paris 0.10

    Temperature divides the logits before softmax: below 1 makes the top choice more likely (more predictable output), above 1 flattens the distribution (more varied, more random). Top-p (nucleus sampling) samples only from the smallest set of tokens whose probabilities add up to p, such as 0.9, and top-k keeps only the k most likely tokens. Use low temperature for extraction and code, and higher for brainstorming.

    Q98ExperiencedGenAI & LLMs

    98. What are LoRA and parameter-efficient fine-tuning?

    Fully fine-tuning a model with billions of parameters needs a lot of GPU memory and stores a full copy per task. Parameter-efficient fine-tuning (PEFT) freezes the original weights and trains only a small number of new ones.

    LoRA (low-rank adaptation) adds two small matrices A and B next to selected weight matrices, so the update is ΔW = BA with a low rank r (such as 8 or 16). Often well under 1% of the parameters are trained, and the result is close to full fine-tuning. QLoRA also loads the frozen base model in 4-bit precision, so large models can be fine-tuned on a single GPU. The small adapters can be swapped per task or merged into the base weights for serving.

    Q99ExperiencedData & features

    99. How do you handle categorical features with thousands of categories?

    One-hot encoding a feature like user ID, product ID or pin code creates thousands of sparse columns. Better options:

    • Target encoding: replace each category with a smoothed average of the target for it. It must be computed out of fold (inside cross-validation), or each row’s own label leaks into its feature. scikit-learn’s TargetEncoder does the cross-fitting for you.
    • Frequency or count encoding, and grouping rare categories into “other”.
    • Hashing categories into a fixed number of buckets.
    • Learned embeddings in a neural network.
    • Models with native categorical handling: CatBoost and LightGBM.

    Also plan for categories that appear only after deployment, and make sure the encoding has a sensible default for them.

    Q100ExperiencedML in production

    100. How would you design a fraud detection system for card transactions?

    • Requirements: a decision within about 100 milliseconds per transaction, extremely imbalanced labels (well under 1% fraud), labels that arrive late (chargebacks take weeks), and fraudsters who adapt.
    • Features: transaction amount and merchant category, plus velocity features computed in real time from a feature store (number of transactions in the last hour, distance from the last location, amount compared with the card’s usual spending), device and IP signals.
    • Model: gradient-boosted trees as the main model, with business rules for known patterns, plus an anomaly detector for new kinds of fraud. Train with time-based validation.
    • Decision: calibrated probabilities feed a cost-based policy: approve, ask for OTP verification, send to manual review, or block.
    • Evaluate and monitor: PR AUC and recall at a fixed false positive rate, money saved, customer friction, drift, and retraining as new labels arrive. Watch for the feedback loop where blocked transactions never get labels.

    In design questions, interviewers care more about this structure and the trade-offs you name than about the exact algorithm.

    Machine learning quiz: test yourself

    Ten multiple-choice questions from across this page. Eight or more right means you are in good shape for a machine learning interview.

    Quiz

    10 machine learning MCQs

    About three minutes.

    Download all 100 machine learning interview questions as a PDF

    The PDF has the same 100 machine learning interview questions and answers, with every code example and its output, in a clean 42-page printable format with a clickable table of contents. Use it to revise offline, on your phone, or on paper before the interview. It is free, with no sign-up.

    Free PDF

    100 Machine Learning Interview Questions and Answers

    42 pages · Freshers, intermediate and experienced · 30 Python examples

    Download PDF

    Frequently asked questions

    What machine learning questions are asked in interviews for freshers?

    Freshers are most often asked about the types of machine learning, overfitting and underfitting, the bias-variance tradeoff, train and test splits, how linear regression, logistic regression, decision trees, KNN and k-means work, and evaluation metrics such as precision, recall, F1 and ROC AUC. Questions 1 to 40 on this page cover them.

    How should I prepare for a machine learning interview?

    Revise the core concepts with your own examples, practise coding a model end to end in scikit-learn, know the common comparisons (precision vs recall, L1 vs L2, bagging vs boosting), and prepare one project you can explain in depth, including the metric you chose and why. For experienced roles, also revise deployment, monitoring and LLM topics.

    Are deep learning and LLM questions asked in machine learning interviews?

    Yes, increasingly. Most ML interviews still focus on core machine learning, but expect a few questions on neural networks, backpropagation and, for many roles today, transformers, RAG, fine-tuning and evaluating LLM outputs. Questions 39, 40, 69 to 75 and 91 to 98 cover these.

    Which algorithms should I know for a data science interview?

    Linear and logistic regression, decision trees, random forests, gradient boosting (XGBoost or LightGBM), KNN, Naive Bayes, SVM, k-means and PCA. For each, know how it works, its main hyperparameters, when to use it and its weaknesses.

    Do I need to know the maths for a machine learning interview?

    You need the intuition and a few key formulas: gradient descent, the loss functions (MSE and log loss), precision, recall and F1, Gini impurity and entropy, and the bias-variance idea. Research and senior roles may go deeper into linear algebra, probability and optimisation.

    Can I download these machine learning interview questions as a PDF?

    Yes. All 100 questions and answers, with every code example and its output, are in a free 42-page PDF. Use the Download PDF button at the top of this page; no sign-up is needed.

    Next steps

    Work through one level at a time and press “Mark as done” on each of the machine learning interview questions once you can answer it out loud without looking. Then go deeper with our interactive guides to linear regression, logistic regression, decision trees, SVM, k-means clustering and the confusion matrix. For the coding round, revise with our 100 Python interview questions and 100 SQL interview questions. All the best for your interview.

    Machine Learning
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleK-Means Clustering in Machine Learning: An Interactive Guide (with Python)
    Anirudh Khurana
    • Website

    Anirudh Khurana is the founder of Code and Debug, an Indian EdTech platform that helps students and working professionals crack coding interviews and move into data and AI roles. He teaches DSA, Python, SQL, data engineering and machine learning through live bootcamps and his YouTube channel, Code and Debug, which has over 50,000 subscribers. Every guide on this blog is written or reviewed by him and tested with real code.

    Related Posts

    AI & Machine Learning

    K-Means Clustering in Machine Learning: An Interactive Guide (with Python)

    20 November 2026
    AI & Machine Learning

    Decision Tree in Machine Learning: An Interactive Guide (with Python)

    18 November 2026
    AI & Machine Learning

    Support Vector Machine (SVM) in Machine Learning: An Interactive Guide

    16 November 2026
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • AI & Machine Learning (8)
    • Data Structures & Algorithms (241)
      • Beginner (82)
      • Expert (52)
      • Intermediate (106)
    • Interview Questions (6)
    • Pandas (1)
    • Python (1)
    • Resume (1)
    • SQL (1)
    Recent Posts

    100 Machine Learning Interview Questions and Answers (Freshers to Experienced)

    25 November 2026

    K-Means Clustering in Machine Learning: An Interactive Guide (with Python)

    20 November 2026

    Decision Tree in Machine Learning: An Interactive Guide (with Python)

    18 November 2026

    Support Vector Machine (SVM) in Machine Learning: An Interactive Guide

    16 November 2026

    100 OOPs Interview Questions and Answers (Freshers to Experienced)

    16 November 2026
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.