Machine Learning Fundamentals

This course teaches machine learning as a disciplined workflow: define the prediction problem, understand the data-generating process, prevent leakage, build a baseline, validate honestly, interpret errors and operate the model responsibly. Examples use Python 3.11+ and scikit-learn; external libraries are labelled explicitly.

Learning map and a reliable modelling habit

For every project, write the unit of prediction, prediction time, target definition, success metric, error costs and deployment context. Split data before learning transformations. Compare a simple baseline, use cross-validation appropriate to time or groups, keep the test set untouched, inspect errors by subgroup, and document limitations. A model score is evidence about a procedure under a data split; it is not a guarantee about future users.

  1. Frame: convert a business decision into a measurable supervised or unsupervised task.
  2. Audit: inspect schema, missingness, duplicates, target prevalence, temporal order and leakage.
  3. Build: create a pipeline, baseline and candidate models.
  4. Evaluate: choose metrics from consequences, quantify uncertainty and inspect failure cases.
  5. Operate: version data/model, validate inputs, monitor drift and define rollback.

Foundations, data and generalisation

1. What is machine learning?

Intuition: Machine learning learns a function from examples so it can make predictions or decisions on new data. The goal is generalisation, not memorising training rows.

Worked example: A model learns house price from size, location and age, then predicts a new house.

from sklearn.linear_model import LinearRegressionnmodel = LinearRegression()nprint("fit on examples, predict on new rows")

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Define the input, target, loss, data-generating process and what “good” means before choosing a model. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

Understanding Machine Learning Fundamentals helps learners identify suitable algorithms, prepare reliable datasets and build models that solve clearly defined problems.

2. Traditional programming versus machine learning

Intuition: Traditional programming supplies rules and data to produce outputs; ML supplies examples and an objective to infer rules.

Worked example: A tax calculator follows explicit rules; a spam model learns a boundary from labelled messages.

print("rules + data -> output")nprint("data + labels + objective -> model")

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: ML still needs explicit problem framing, validation and production rules around the model. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

3. AI, ML and deep learning differences

Intuition: AI is the broad goal of intelligent behaviour; ML is data-driven learning; deep learning uses multilayer neural networks.

Worked example: A rule-based expert system is AI without necessarily being ML; a convolutional network is deep ML.

print("AI ⊇ ML ⊇ deep learning")

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Do not use the terms as synonyms or claim deep learning is automatically best. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

4. Types of machine learning

Intuition: Supervised, unsupervised, semi-supervised and reinforcement learning differ by feedback and available labels.

Worked example: Classification uses labels, clustering does not, and reinforcement learning receives rewards from interaction.

learning_types = ["supervised", "unsupervised", "semi-supervised", "reinforcement"]nprint(learning_types)

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Choose from the data and decision setting, not from algorithm popularity. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

5. Supervised learning

Intuition: Supervised learning estimates y=f(X) from labelled pairs. Regression predicts numbers; classification predicts categories or probabilities.

Worked example: Email text with spam labels supports a classifier; historical demand supports regression.

from sklearn.model_selection import train_test_splitnX_train, X_test, y_train, y_test = train_test_split([[0], [1]], [0, 1], test_size=.5, random_state=1)

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: The split must represent deployment and prevent target leakage. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

6. Unsupervised learning

Intuition: Unsupervised learning finds structure without a target, such as clusters, latent components or anomalies.

Worked example: Group customers by behaviour before designing a campaign.

from sklearn.cluster import KMeansnlabels = KMeans(n_clusters=2, random_state=1, n_init=10).fit_predict([[0], [10]])nprint(labels)

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Clusters are model-dependent descriptions, not automatically real natural groups. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

7. Semi-supervised learning

Intuition: Semi-supervised methods use a small labelled set with many unlabelled examples, assuming unlabelled structure helps the task.

Worked example: Manually label 500 images and use 50,000 unlabelled images to improve representation.

from sklearn.semi_supervised import LabelSpreadingnmodel = LabelSpreading(kernel="knn")nprint("use -1 for unknown labels")

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Unlabelled data can reinforce wrong assumptions; evaluate only against trusted labels. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

8. Reinforcement learning

Intuition: An agent observes state, chooses actions, receives rewards and learns a policy to maximise discounted future return.

Worked example: A delivery agent balances travel time, fuel and successful delivery rewards.

print("return = r0 + gamma*r1 + gamma**2*r2")

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Exploration, reward design, delayed feedback and safe deployment are central; it is not ordinary supervised prediction. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

9. Machine-learning workflow

Intuition: A reliable workflow frames the problem, audits data, splits early, builds a baseline, trains, validates, evaluates, deploys and monitors.

Worked example: A churn project needs a prediction timestamp and a label window before feature engineering.

steps = ["frame", "audit", "split", "baseline", "train", "validate", "test", "deploy", "monitor"]nprint(" -> ".join(steps))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: The untouched test set is for final evidence, not repeated model selection. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

10. Dataset structure and features

Intuition: Rows represent samples; columns represent features or metadata. Features must be available at prediction time and have a defined type and grain.

Worked example: One row per customer-week differs from one row per transaction; mixing grains creates leakage and incorrect evaluation.

import pandas as pdndf = pd.DataFrame({"age": [20, 30], "city": ["Delhi", "Pune"]})nprint(df.dtypes)

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Document units, keys, timestamps, missingness and the unit of prediction. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

11. Target variables

Intuition: The target is the outcome the model learns. Define its horizon, label construction, censoring and cost of errors.

Worked example: “Churn in next 30 days” is a different target from “ever churned”.

y = [0, 1, 0]nprint("binary target:", y)

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: A noisy or post-outcome target makes a high score misleading. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

12. Training, validation and test datasets

Intuition: Training fits parameters, validation selects models and settings, and test estimates final generalisation. Time or group splits may be safer than random splits.

Worked example: For future sales, train on earlier dates and test on later dates.

from sklearn.model_selection import train_test_splitnX_train, X_test = train_test_split([[1], [2], [3], [4]], test_size=.25, random_state=42)

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Never fit preprocessing, tune thresholds or inspect test performance before the final decision. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

13. Data preprocessing

Intuition: Preprocessing converts raw inputs into stable model inputs: types, missing values, categories, scale, text and dates.

Worked example: Parse dates, extract weekday, impute training medians and encode categories inside a pipeline.

from sklearn.compose import ColumnTransformernprint("fit transformations on training data only")

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Keep preprocessing reproducible and apply exactly the same transformations at inference. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

14. Missing-value treatment

Intuition: Missingness may mean unknown, not applicable or a process failure. Impute, add indicators, drop rows or use models that handle missing values based on the mechanism and decision.

Worked example: Median-impute income and add an “income_missing” indicator when absence is informative.

from sklearn.impute import SimpleImputernimputer = SimpleImputer(strategy="median")nprint(imputer.fit_transform([[1], [None], [3]]))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Compute imputation values inside cross-validation to avoid leakage. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

15. Encoding categorical variables

Intuition: One-hot encoding creates binary columns; ordinal encoding is appropriate only when order is meaningful; target encoding needs strict out-of-fold protection.

Worked example: City names should not be encoded 1,2,3 as though the numbers have distance.

from sklearn.preprocessing import OneHotEncodernencoder = OneHotEncoder(handle_unknown="ignore")nprint(encoder.fit_transform([["Delhi"], ["Pune"]]).toarray())

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Unknown categories and high cardinality require an explicit strategy. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

16. Feature scaling

Intuition: Scaling puts features on comparable magnitudes and matters for distance- and gradient-based algorithms, but usually not for trees.

Worked example: Without scaling, income measured in thousands can dominate age in KNN.

from sklearn.preprocessing import StandardScalernprint(StandardScaler().fit_transform([[1, 10], [2, 20]]))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Fit the scaler only on training data; inspect outliers before relying on mean/standard deviation. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

17. Normalization and standardization

Intuition: Standardization maps x to (x−mean)/SD; min-max normalization maps to a range such as [0,1]. “Normalization” can also mean row-wise vector norm, so state your meaning.

Worked example: SVM and KNN often benefit from standardization; min-max is useful when bounded inputs are expected.

from sklearn.preprocessing import MinMaxScalernprint(MinMaxScaler().fit_transform([[0], [10]]))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Scaling does not make a skewed distribution normal and does not remove outliers. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

18. Outlier handling

Intuition: Outliers may be errors, rare valid cases or the signal. Investigate provenance before clipping, transforming, robust scaling or removal.

Worked example: A negative age is invalid; a high transaction may be a genuine fraud event.

from sklearn.preprocessing import RobustScalernprint(RobustScaler().fit_transform([[1], [2], [100]]))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Deleting observations after inspecting the target can bias evaluation. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

19. Feature engineering

Intuition: Feature engineering encodes domain knowledge into predictive variables, such as recency, ratios, lags, interactions and date parts.

Worked example: For orders, recency and rolling 30-day count may predict churn better than raw order rows.

import pandas as pdndates = pd.to_datetime(["2026-01-01", "2026-01-03"])nprint(dates.dayofweek.tolist())

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Features must be computed using only information available at prediction time. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

20. Feature selection

Intuition: Selection removes irrelevant or redundant variables using domain rules, filters, wrappers or embedded model penalties.

Worked example: Select features on training folds, not by correlating every column with the full target.

from sklearn.feature_selection import SelectKBest, f_regressionnprint("selection belongs inside the fitted workflow")

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Selection can reduce variance and cost but may remove weakly useful interacting features. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

21. Data leakage

Intuition: Leakage occurs when information unavailable at prediction time influences training or validation, producing an unrealistically high score.

Worked example: Using a “refund completed” field to predict whether an order will be refunded leaks the future.

print("split first; fit every learned transform inside the split")

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Audit timestamps, joins, aggregates, target construction and duplicate entities. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

22. Bias and variance

Intuition: Bias is systematic error from an overly restrictive model; variance is sensitivity to the training sample. Generalisation balances both.

Worked example: A straight line may have high bias for a curved relationship; a deep tree may have high variance.

print("validation error = bias component + variance component + noise")

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Bias–variance is a diagnostic lens, not a command to always increase complexity. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

23. Underfitting and overfitting

Intuition: Underfitting misses real structure; overfitting memorises noise. Compare training and validation performance and inspect learning curves.

Worked example: A depth-1 tree can underfit; an unrestricted tree can overfit.

from sklearn.tree import DecisionTreeRegressornprint(DecisionTreeRegressor(max_depth=2).get_params()["max_depth"])

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: A small training error is not evidence of deployment quality. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

24. Regularization

Intuition: Regularization adds a complexity penalty to the objective. L2 shrinks coefficients; L1 can set coefficients to zero.

Worked example: Minimise loss + λΣβⱼ² for Ridge or loss + λΣ|βⱼ| for Lasso.

from sklearn.linear_model import Ridgenprint(Ridge(alpha=1.0).get_params()["alpha"])

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Tune strength inside cross-validation and scale features before penalising coefficients. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

25. Cross-validation

Intuition: K-fold cross-validation trains on K−1 folds and validates on the remaining fold, rotating the holdout to estimate model variability.

Worked example: Stratified folds preserve class proportions; GroupKFold prevents the same user appearing in train and validation.

from sklearn.model_selection import cross_val_score, KFoldnprint(KFold(n_splits=5, shuffle=True, random_state=42))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Use time-aware or grouped CV when independence is false. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

26. Hyperparameter tuning

Intuition: Hyperparameters are chosen before fitting, such as tree depth, regularization strength or neighbour count; parameters are learned from data.

Worked example: Select max_depth using validation or nested CV, not the test set.

from sklearn.model_selection import RandomizedSearchCVnprint("search space must reflect compute and domain constraints")

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Tune a meaningful metric and report search budget and selection variance. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

27. Grid search and random search

Intuition: Grid search evaluates a Cartesian set; random search samples configurations and often explores important dimensions more efficiently.

Worked example: Random search is useful when only a few hyperparameters strongly affect performance.

from sklearn.model_selection import GridSearchCVnprint("GridSearchCV and RandomizedSearchCV both refit a selected estimator")

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Parallel jobs can exhaust memory; keep a reproducible seed and log configurations. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

Regression models and evaluation

28. Simple linear regression

Intuition: Linear regression predicts y=β₀+β₁x+ε by minimising squared residuals. β₁ is the expected change in y per x unit under the model.

Worked example: A slope of 2 predicts two more units of demand for one more advertising unit, within the observed range.

from sklearn.linear_model import LinearRegressionnmodel = LinearRegression().fit([[1], [2], [3]], [2, 4, 5])nprint(model.coef_, model.predict([[4]]))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Linearity, independent errors and sensible residual variance support inference; prediction can still work under imperfect normality. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

29. Multiple linear regression

Intuition: Multiple regression estimates y=β₀+Σβⱼxⱼ and interprets each coefficient conditional on the included features.

Worked example: A coefficient is not automatically causal and can change with omitted variables or collinearity.

from sklearn.linear_model import LinearRegressionnmodel = LinearRegression().fit([[1, 2], [2, 1], [3, 4]], [3, 4, 7])nprint(model.coef_)

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Check interactions, scale, missingness, residuals and multicollinearity. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

30. Polynomial regression

Intuition: Polynomial regression adds powers or interactions of inputs while remaining linear in coefficients.

Worked example: A quadratic term can model curvature in demand without using a black-box tree.

from sklearn.preprocessing import PolynomialFeaturesnprint(PolynomialFeatures(degree=2, include_bias=False).fit_transform([[2, 3]]))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: High degree can explode variance; use a pipeline and validate degree. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

31. Ridge regression

Intuition: Ridge minimises squared error plus α||β||₂², shrinking correlated coefficients toward zero without usually eliminating them.

Worked example: It is a stable baseline for many correlated numeric features.

from sklearn.linear_model import Ridgenprint(Ridge(alpha=1.0).fit([[1, 2], [2, 3]], [2, 3]).predict([[3, 4]]))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Scale features and tune alpha; coefficients are less sparse than Lasso. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

32. Lasso regression

Intuition: Lasso adds α||β||₁ and can set coefficients exactly to zero, performing embedded selection.

Worked example: It can produce a compact linear model when many features may be irrelevant.

from sklearn.linear_model import Lassonprint(Lasso(alpha=.1).fit([[1, 2], [2, 3], [3, 4]], [1, 2, 3]).coef_)

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: With correlated predictors Lasso may select one arbitrarily; validate stability. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

33. Elastic Net

Intuition: Elastic Net combines L1 and L2 penalties, balancing sparsity and stability for correlated features.

Worked example: Use it when Lasso is unstable among correlated predictors but a sparse model remains useful.

from sklearn.linear_model import ElasticNetnprint(ElasticNet(alpha=.1, l1_ratio=.5).get_params())

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Tune alpha and l1_ratio jointly and standardize inputs. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

34. Regression metrics: MAE, MSE, RMSE and R-squared

Intuition: MAE averages |y−ŷ|, MSE averages squared error, RMSE is √MSE in target units, and R² compares residual variation with a mean baseline.

Worked example: RMSE penalises large misses more than MAE; R² can be negative on poor test predictions.

from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_scorenimport numpy as npny, p = [3, 5], [2, 6]nprint(mean_absolute_error(y,p), np.sqrt(mean_squared_error(y,p)), r2_score(y,p))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Choose metrics from error costs, scale, skew and baseline—not habit. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

Classification models and evaluation

35. Logistic regression

Intuition: Logistic regression models log odds as β₀+βᵀx and returns probabilities through the sigmoid function.

Worked example: A coefficient changes log odds; exp(β) is an odds ratio, not a percentage-point probability change.

from sklearn.linear_model import LogisticRegressionnmodel = LogisticRegression().fit([[0], [1], [2], [3]], [0, 0, 1, 1])nprint(model.predict_proba([[1.5]]))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Scale for regularized optimization, tune C and select a threshold for the business cost. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

36. K-nearest neighbors

Intuition: KNN predicts from the labels or values of the k closest training points according to a distance metric.

Worked example: A new point receives the majority class among nearby examples.

from sklearn.neighbors import KNeighborsClassifiernprint(KNeighborsClassifier(n_neighbors=3).fit([[0], [1], [10]], [0, 0, 1]).predict([[2]]))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Scale features, choose k with CV, and avoid it for huge high-dimensional datasets without a strategy. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

37. Decision trees

Intuition: A tree recursively chooses splits that reduce impurity or prediction loss, producing interpretable if-then regions.

Worked example: A split such as income < 50,000 can separate classes.

from sklearn.tree import DecisionTreeClassifiernprint(DecisionTreeClassifier(max_depth=2, random_state=1).fit([[0], [1], [10]], [0, 0, 1]).predict([[2]]))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Trees need pruning or depth/leaf constraints; small data can make splits unstable. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

38. Random forests

Intuition: A random forest averages many bootstrapped trees with random feature subsets, reducing variance.

Worked example: Individual noisy trees can become a stronger stable ensemble.

from sklearn.ensemble import RandomForestClassifiernmodel = RandomForestClassifier(n_estimators=100, random_state=1)nprint(model.get_params()["n_estimators"])

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Tune trees, depth, leaf size and class weights; importance is not automatically causal. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

39. Naive Bayes

Intuition: Naive Bayes applies Bayes theorem while assuming conditional independence of features given the class.

Worked example: Word counts can work well for text despite correlated words because likelihood estimation is simple.

from sklearn.naive_bayes import GaussianNBnprint(GaussianNB().fit([[1, 0], [0, 1]], [0, 1]).predict([[1, 1]]))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Fast and effective for sparse text, but probability calibration and independence assumptions can be poor. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

40. Support Vector Machines

Intuition: SVMs find a maximum-margin boundary; kernels implicitly represent nonlinear features. C trades margin against training errors.

Worked example: A linear or RBF SVM can separate classes with a flexible boundary.

from sklearn.svm import SVCnprint(SVC(kernel="linear", probability=True).fit([[0], [1], [3]], [0, 0, 1]).predict([[2]]))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Scale inputs; kernel SVMs can be expensive and sensitive to C and gamma. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

41. Gradient boosting

Intuition: Boosting adds weak learners sequentially, each correcting residual errors from the current ensemble.

Worked example: Small shallow trees can form a strong nonlinear predictor.

from sklearn.ensemble import GradientBoostingClassifiernprint(GradientBoostingClassifier(n_estimators=50, learning_rate=.05, random_state=1).get_params()["learning_rate"])

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Learning rate, estimators and depth trade accuracy, time and overfitting. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

42. AdaBoost

Intuition: AdaBoost reweights misclassified observations so later weak learners focus on difficult examples.

Worked example: A sequence of shallow stumps can create a nonlinear classifier.

from sklearn.ensemble import AdaBoostClassifiernprint(AdaBoostClassifier(n_estimators=50, random_state=1).get_params()["n_estimators"])

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Noise and outliers can receive excessive weight; use robust validation. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

43. XGBoost and related boosting methods

Intuition: XGBoost is an external gradient-boosting library with regularization, efficient tree construction and practical missing-value handling; scikit-learn HistGradientBoosting and GradientBoosting are separate implementations.

Worked example: Use XGBoost when its external dependency, performance and deployment contract are acceptable.

from sklearn.ensemble import HistGradientBoostingClassifiernprint(HistGradientBoostingClassifier(max_iter=100).get_params()["max_iter"])n# XGBoost requires: from xgboost import XGBClassifier

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Do not claim XGBoost is part of scikit-learn. Pin versions, audit licenses and tune depth, learning rate, estimators and subsampling. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

44. Confusion matrix

Intuition: A confusion matrix counts true positives, false positives, true negatives and false negatives at a chosen classification threshold.

Worked example: A fraud system may tolerate false positives differently from missed fraud.

from sklearn.metrics import confusion_matrixnprint(confusion_matrix([0, 1, 1], [0, 1, 0]))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Always identify the positive class and threshold before interpreting cells. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

45. Accuracy, precision, recall and F1-score

Intuition: Accuracy is total correct; precision=TP/(TP+FP); recall=TP/(TP+FN); F1 is the harmonic mean of precision and recall.

Worked example: For disease screening, recall may matter more; for expensive manual review, precision may matter more.

from sklearn.metrics import classification_reportnprint(classification_report([0, 1, 1], [0, 1, 0]))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Accuracy can be useless on severe imbalance; report support and confidence intervals where possible. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

46. ROC curve and AUC

Intuition: ROC plots true-positive rate against false-positive rate across thresholds; AUC is ranking performance over thresholds.

Worked example: AUC=.85 suggests positive examples tend to score above negatives, not that any chosen threshold has .85 accuracy.

from sklearn.metrics import roc_auc_scorenprint(roc_auc_score([0, 1, 1], [.1, .7, .4]))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: ROC can look optimistic when negatives dominate; inspect precision-recall and operating-point costs. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

47. Precision-recall curve

Intuition: The precision-recall curve shows the trade-off for positive detection and is often more informative with rare positives.

Worked example: Use it for fraud, defects or disease screening where positive prevalence is low.

from sklearn.metrics import average_precision_scorenprint(average_precision_score([0, 1, 1], [.1, .7, .4]))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Compare against the positive prevalence baseline and report a chosen threshold. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

48. Imbalanced classification

Intuition: Class imbalance means one class is rare. Use stratification, class weights, threshold selection, suitable metrics and careful resampling.

Worked example: A 99% accurate model that never detects fraud is not useful.

from sklearn.linear_model import LogisticRegressionnmodel = LogisticRegression(class_weight="balanced")nprint(model.get_params()["class_weight"])

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Resample inside training folds only; inspect calibration and subgroup recall. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

Unsupervised learning and representation

49. K-means clustering

Intuition: K-means assigns points to k centroids by minimising within-cluster squared distance, alternating assignment and centroid updates.

Worked example: Customer points close to a centroid share a behaviour profile.

from sklearn.cluster import KMeansnmodel = KMeans(n_clusters=2, n_init=10, random_state=1).fit([[0, 0], [0, 1], [9, 9]])nprint(model.labels_)

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Scale features, choose k deliberately and remember clusters are spherical in the chosen space. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

50. Hierarchical clustering

Intuition: Agglomerative clustering starts with individual points and repeatedly merges groups according to linkage, producing a dendrogram.

Worked example: Single, complete, average and Ward linkage create different notions of closeness.

from sklearn.cluster import AgglomerativeClusteringnprint(AgglomerativeClustering(n_clusters=2).fit_predict([[0], [1], [10]]))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Scaling and linkage dominate results; it can be expensive for many observations. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

51. DBSCAN

Intuition: DBSCAN groups dense regions and labels sparse points as noise using epsilon radius and minimum samples.

Worked example: It can find irregular geographic clusters without specifying their count.

from sklearn.cluster import DBSCANnprint(DBSCAN(eps=1.5, min_samples=2).fit_predict([[0], [1], [10]]))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Choose eps from distance structure, scale features and expect trouble with varying densities. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

52. Cluster evaluation

Intuition: Internal scores such as silhouette compare cohesion and separation; external scores require trusted labels. Business usefulness and stability also matter.

Worked example: A high silhouette does not prove a segment is actionable or persistent.

from sklearn.metrics import silhouette_scorenlabels = [0, 0, 1]nprint(silhouette_score([[0], [1], [10]], labels))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Do not optimise a single score without checking size, stability and domain meaning. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

53. Principal Component Analysis

Intuition: PCA finds orthogonal directions of maximum variance. Components are linear combinations of centered features; explained variance quantifies retained spread.

Worked example: Two principal components can compress many correlated measurements before visualisation.

from sklearn.decomposition import PCAnprint(PCA(n_components=2).fit_transform([[1, 2], [2, 3], [3, 4]]))

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Scale features when units differ and remember PCA components are not automatically interpretable causes. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

54. Dimensionality reduction

Intuition: Dimensionality reduction compresses features for noise control, visualisation or faster learning. PCA is linear; nonlinear methods may preserve neighbourhoods differently.

Worked example: Use a fitted reducer inside a pipeline and compare downstream validation.

from sklearn.manifold import TSNEnprint("t-SNE is mainly exploratory; fit and interpret with care")

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Do not use a pretty 2-D plot as proof of separable production classes. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

Advanced foundations and operations

55. Ensemble learning

Intuition: Ensembles combine models to reduce variance, bias or both through bagging, boosting or stacking.

Worked example: Averaging diverse errors can improve generalisation over one estimator.

from sklearn.ensemble import VotingClassifiernprint("combine validated estimators, not correlated copies blindly")

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Complexity, latency and interpretability increase; compare against a simple baseline. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

56. Feature importance

Intuition: Importance can be impurity-based, permutation-based or coefficient-based. Each answers a different question and has biases.

Worked example: Permutation importance asks how validation performance changes when a feature is shuffled.

from sklearn.inspection import permutation_importancenprint("compute importance on held-out data")

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Correlated features can split or hide importance; importance is not causality. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

57. Model interpretability

Intuition: Global explanations describe average behaviour; local explanations describe one prediction. Partial dependence, ICE, permutation and SHAP have assumptions and failure modes.

Worked example: Explain why one loan received a risk score without exposing a misleading causal story.

print("interpret predictions with the same preprocessing used in production")

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Check explanation stability, subgroup behaviour and data leakage in the explainer. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

58. Class imbalance methods

Intuition: Beyond class weights, use carefully designed under/over-sampling, SMOTE, threshold tuning, focal objectives or anomaly framing.

Worked example: SMOTE synthesises minority points only within training folds.

from imblearn.over_sampling import SMOTEnprint("install imbalanced-learn separately; apply SMOTE inside a pipeline")

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Do not oversample validation or test data and do not assume synthetic points are plausible. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

59. Anomaly detection

Intuition: Anomaly detection identifies observations unlike a reference population using isolation, density or reconstruction ideas.

Worked example: Flag unusual transactions for review rather than declaring every flag fraud.

from sklearn.ensemble import IsolationForestnprint(IsolationForest(contamination="auto", random_state=1).get_params()["contamination"])

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Labels are often scarce; validate alert volume, precision, drift and review capacity. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

60. Model pipelines

Intuition: A pipeline chains preprocessing and estimator so fitting, cross-validation and inference use identical transformations.

Worked example: A ColumnTransformer can impute and one-hot encode before a classifier.

from sklearn.pipeline import Pipelinenfrom sklearn.preprocessing import StandardScalernfrom sklearn.linear_model import Ridgenpipe = Pipeline([("scale", StandardScaler()), ("model", Ridge())])nprint(pipe.steps)

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Pipelines are the default defence against preprocessing leakage. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

61. Reproducibility

Intuition: Reproducibility records code, data snapshot, dependency versions, random seeds, feature definitions, metrics and environment.

Worked example: A model cannot be responsibly compared if its split and package versions are unknown.

import sklearnnprint(sklearn.__version__)

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: A seed improves repeatability but does not guarantee bit-for-bit results across hardware or versions. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

62. Model deployment overview

Intuition: Deployment packages a validated model behind a batch job, library or service with input validation, versioning, latency and rollback.

Worked example: A nightly churn score may be safer and cheaper than a synchronous API.

print("validate schema -> transform -> predict -> log model version")

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Test training-serving skew, timeouts, authentication and failure behaviour. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

63. Model monitoring and drift

Intuition: Monitor data quality, feature distributions, prediction rates, calibration, performance when labels arrive, latency and business outcomes.

Worked example: A seasonal change is not automatically harmful drift; compare against expected calendar patterns.

print("monitor missingness, ranges, PSI/KS, metrics and segment performance")

Execution and interpretation: The code demonstrates the smallest useful implementation. Explain the input shape, fitted state, output units and what would happen on a new observation. For algorithms, identify the objective, distance or split rule, parameters learned from data and the evaluation metric.

Assumptions and use: Use this method when its data type, scale, sample size, computational budget and error costs fit the problem. Do not use it as a default when a simpler baseline, causal design or time-aware split is required. Check independence, leakage, missingness, representativeness and deployment-time availability.

Important parameters: Tune only through the validation design. Record random seeds, preprocessing, search space, metric, split strategy and fit time. Strengths and weaknesses: Compare accuracy, interpretability, stability, latency, memory and sensitivity to outliers or class imbalance rather than naming a universal winner.

Common mistake and practice solution: Monitoring without alert ownership and a retraining/rollback policy is not operational control. Change one input, run a small edge case, compare with a baseline and write a test that would catch a leakage or shape error.

Interview prompt

Explain the concept without jargon, state when it fails, trace the example, name one alternative and describe how you would validate it on production-like data.

Three end-to-end practical examples

Regression: house-price prediction

Define one row per house and a price measured at the listing timestamp. Split by time if the market changes. Fit preprocessing and a Ridge or tree ensemble inside a pipeline, compare against predicting the training median, report MAE and RMSE in currency, inspect large residuals and evaluate on a final held-out period. Do not use a post-sale field or future renovation cost as a feature.

from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_absolute_error

X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=42)
model = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
model.fit(X_train, y_train)
print(mean_absolute_error(y_test, model.predict(X_test)))

The metric is an estimate on this split, not a promise. Repeat with cross-validation and report the spread.

Classification: customer churn

Define churn and the prediction horizon, use a time-based split, encode categories and impute inside a pipeline, compare a majority baseline with logistic regression and a tree ensemble, and choose a threshold using the cost of outreach versus missed churn. Report precision, recall, PR-AUC, calibration and performance by customer segment.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=.2, random_state=42)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000))
model.fit(X_train, y_train)
print(classification_report(y_test, model.predict(X_test)))

The dataset is educational; production churn requires a valid temporal label and privacy review.

Clustering: customer segments

Choose one row per customer with a defined observation window, transform skewed spend, scale features, compare K-means and density methods, inspect segment sizes and stability, then describe segments without claiming they are causal types. Use silhouette as one diagnostic and validate whether segments change a decision.

from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

X, _ = load_iris(return_X_y=True)
X = StandardScaler().fit_transform(X)
labels = KMeans(n_clusters=3, n_init=20, random_state=42).fit_predict(X)
print(silhouette_score(X, labels))

Clustering has no target accuracy; stability, interpretability and actionability are essential.

Interview questions, exercises and algorithm-selection guide

These Machine Learning Fundamentals are important for technical interviews because candidates must explain algorithm selection, model performance, assumptions and limitations.

Interview questions

  1. Why split before preprocessing? Answer: learned imputation, scaling, selection and encoding statistics must not use validation/test information.
  2. Why can accuracy be misleading? Answer: class prevalence and error costs can make a majority classifier appear strong; inspect precision, recall, PR-AUC and threshold costs.
  3. When would you choose a linear model over boosting? Answer: when a transparent, fast, stable relationship is adequate or coefficients are required; compare validated performance and operating constraints.
  4. How do you detect leakage? Answer: reconstruct feature availability at prediction time, inspect timestamps and joins, compare suspiciously high scores, and use a strict pipeline/split.
  5. How do you explain a model? Answer: combine global behaviour, local examples, permutation or coefficient evidence, subgroup checks and limitations; never present importance as causation.

Exercises

  1. Create a baseline for a numeric target and report MAE.
  2. Build a preprocessing pipeline for numeric and categorical columns.
  3. Compare Ridge, Random Forest and HistGradientBoosting with cross-validation.
  4. Deliberately leak the target through a feature, measure the inflated score, then remove it.
  5. Use stratified CV on an imbalanced classifier and select a threshold for a stated cost.
  6. Compare K-means and DBSCAN after scaling and report cluster stability.
  7. Write a model card containing data, metric, limitations, fairness checks, version and rollback plan.
Problem and data Start with Consider next Watch for
Numeric target, tabular data Mean/median baseline, Linear/Ridge Random Forest or gradient boosting leakage, skew, residuals, extrapolation
Binary target, calibrated probability Logistic regression Random Forest or boosting threshold, imbalance, calibration
Small data, interpretable boundary Linear model or shallow tree SVM, regularised model scaling, variance, validation uncertainty
Unlabelled compact numeric data K-means or hierarchical DBSCAN, PCA scale, cluster stability, arbitrary k
Rare anomalies Rules plus Isolation Forest baseline density or domain model alert capacity, changing baseline, labels
Large nonlinear tabular data HistGradientBoosting XGBoost external library versioning, tuning, latency, explainability

Final checklist

  • Can I define the unit, target, prediction time and success metric?
  • Can I explain why the split matches deployment?
  • Can I put every learned transformation inside a pipeline?
  • Can I choose metrics from error costs and prevalence?
  • Can I compare a simple baseline with a tuned model?
  • Can I diagnose bias, variance, leakage, drift and subgroup failure?
  • Can I state one strength, weakness and alternative for each algorithm?
  • Can I reproduce, deploy, monitor and roll back the model?

References: scikit-learn User Guide, scikit-learn pipelines, model evaluation, XGBoost documentation, Fairlearn. Continue with the Statistics course and Data Science project ideas.