# Machine Learning Engineer roadmap

> Go from Python and maths to classical ML, deep learning, computer vision, NLP and MLOps, and ship models that work in production.

Canonical: https://www.internhack.in/roadmaps/tracks/machine-learning
Last updated: 2026-11-28

17 sections, 84 topics, about 565 hours.

A complete path for aspiring ML engineers and data scientists. You begin with Python, the scientific stack (NumPy, pandas, plotting, Jupyter) and the maths that models rest on: linear algebra, calculus, probability, statistics and optimization. Then you learn to prepare data without leakage, train and evaluate classical models from linear regression to gradient boosting, find structure with clustering and dimensionality reduction, and package everything in scikit-learn pipelines. The deep learning half covers neural network fundamentals, a framework of your choice (PyTorch recommended), computer vision, NLP with transformers and Hugging Face, and optional deep dives into generative models, recommenders, time series and reinforcement learning. You finish by shipping models the way industry does: experiment tracking, data versioning, Docker, serving, pipelines, monitoring and scaling, with fairness, explainability and privacy built in, then prove it all with Kaggle practice, paper reproductions, a portfolio and an end-to-end capstone.

## Outcomes

- Use Python, NumPy, pandas and plotting libraries fluently to explore and prepare real datasets
- Explain the linear algebra, calculus, probability and statistics behind common models
- Train, tune and evaluate classical models with leakage-safe splits, cross-validation and the right metrics
- Build, debug and train neural networks in PyTorch, including CNNs and fine-tuned transformers
- Apply transfer learning to computer vision and NLP problems with Hugging Face and pretrained backbones
- Ship models to production with experiment tracking, versioned data, Docker, APIs, pipelines and drift monitoring
- Audit models for fairness, explain their predictions and document them with model cards
- Present a portfolio of end-to-end projects and a capstone that hold up in ML interviews

## Prerequisites

- Basic programming in any language
- High school algebra; comfort learning more maths as you go
- A computer that can run Python (free cloud GPUs cover deep learning)

## Python and the Data Workbench

The language, environment and core libraries every ML practitioner uses daily before any model is trained.

### Python for Machine Learning

core · beginner · about 20 h · https://www.internhack.in/roadmaps/tracks/machine-learning/python-for-ml

The slice of Python that ML code actually leans on: data structures, functions, comprehensions, classes and reading other people's code.

Almost every ML library exposes a Python API, so fluency here pays off in every later topic. You do not need to be a software engineer yet, but you must be able to read and write short, clean scripts without fighting the syntax.

#### What to be comfortable with
- **Core types**: lists, dicts, tuples, sets, and when each is the right container.
- **Control flow and functions**: default and keyword arguments, `*args` / `**kwargs`, returning multiple values.
- **Comprehensions and generators**: `[f(x) for x in xs if cond]` is everywhere in data code.
- **Classes**: enough to read `class MyModel(nn.Module)` and understand `__init__`, methods and inheritance.
- **Modules and packages**: `import`, relative imports, and splitting a notebook into a reusable `.py` file.
- **Files and paths**: `pathlib`, reading CSV/JSON, context managers (`with open(...)`).

#### Pitfalls
Mutable default arguments (`def f(x=[])`), confusing copies with references when you modify lists, and writing everything as one giant notebook cell. Also avoid pure Python loops over millions of rows; that is what NumPy and pandas are for.

**Good enough to move on** when you can write a script that reads a CSV with the `csv` module, computes per-group averages with a dict, and prints a sorted summary, without looking up basic syntax.

Key concepts: Built-in data structures, Functions, args and kwargs, Comprehensions and generators, Classes and inheritance, Modules, packages and imports, pathlib and file I/O, Type hints and dataclasses.

Mini project: Write a command-line script that loads the Titanic CSV with the csv module, computes survival rate by passenger class and sex using plain dicts, and prints a sorted table.

Self-check: Why is `def add_item(item, bucket=[])` a bug, and how do you fix it?

Resources:
- [The Python Tutorial](https://docs.python.org/3/tutorial/) (python.org)
- [Kaggle Learn: Python](https://www.kaggle.com/learn/python) (Kaggle)

### Environments, Packages and Jupyter

core · beginner · about 5 h · https://www.internhack.in/roadmaps/tracks/machine-learning/environments-and-notebooks

Isolated environments, dependency management and working productively in notebooks without creating an unreproducible mess.

ML projects depend on many fast-moving libraries (NumPy, PyTorch, CUDA builds). Without isolated environments you will eventually break one project by upgrading another. Pick one tool and use it for every project.

#### Environment options
- **venv + pip**: built into Python, fine for most CPU work. Pin versions in `requirements.txt`.
- **uv**: a very fast drop-in for pip/venv with lockfiles; a great modern default.
- **conda / mamba**: useful when you need non-Python binaries (CUDA toolkits, GDAL).

#### Jupyter
Notebooks are ideal for exploration: run a cell, look at a plot, adjust. JupyterLab, VS Code notebooks and Google Colab (free GPU) are all fine. Learn the kernel concept, magic commands like `%timeit`, and restarting the kernel to confirm your notebook runs top to bottom.

#### Pitfalls
- Hidden state: cells run out of order produce results nobody can reproduce. Use **Restart and Run All** before trusting a result.
- Installing packages into the global interpreter or mixing conda and pip carelessly.
- Keeping all logic in notebooks forever. Move stable code into `.py` modules and import it.

**Good enough to move on** when you can create a fresh environment from a requirements or lock file on a new machine and reproduce a notebook result.

Key concepts: venv and pip, uv, conda or mamba, JupyterLab and VS Code notebooks, Google Colab and Kaggle notebooks, Pinning and lockfiles.

Mini project: Create a project folder with a pinned environment, a notebook that loads a dataset, and a README explaining how a teammate recreates the environment and runs the notebook end to end.

Self-check: Your notebook gives a different result after Restart and Run All. What most likely happened?

Resources:
- [venv: Creation of virtual environments](https://docs.python.org/3/library/venv.html) (python.org)
- [uv documentation](https://docs.astral.sh/uv/) (Astral)
- [Project Jupyter documentation](https://docs.jupyter.org/en/latest/) (Jupyter)

### NumPy and Array Thinking

core · beginner · about 10 h · https://www.internhack.in/roadmaps/tracks/machine-learning/numpy

N-dimensional arrays, vectorization and broadcasting: the mental model underneath pandas, scikit-learn and every tensor library.

NumPy's `ndarray` is a block of typed numbers with a **shape**. Nearly all ML data (tables, images, batches of embeddings) ends up as arrays, and PyTorch tensors behave almost identically, so time spent here transfers directly to deep learning.

#### Key ideas
- **Shape, dtype and axes**: `X.shape == (n_samples, n_features)` is the universal convention. Know what `axis=0` versus `axis=1` means in `sum` or `mean`.
- **Vectorization**: replace Python loops with whole-array operations; it is often 10-100x faster.
- **Broadcasting**: how `X - X.mean(axis=0)` subtracts a row vector from every row. Learn the rules (align trailing dims, size 1 stretches).
- **Indexing**: slicing, boolean masks (`X[y == 1]`), fancy indexing, and views versus copies.
- **Linear algebra**: `@` for matrix multiply, `np.linalg` for solves, norms and eigen decompositions.
- **Random numbers**: use `rng = np.random.default_rng(42)` for reproducible experiments.

#### Pitfalls
Silent broadcasting of shapes like `(n,)` against `(n, 1)` producing an `(n, n)` matrix is a classic bug. Print shapes constantly. Also beware integer dtypes truncating division results.

**Good enough to move on** when you can implement standardization, a pairwise distance matrix and a one-line softmax without loops.

Key concepts: ndarray, shape and dtype, Vectorized operations, Broadcasting rules, Slicing, masks and fancy indexing, Views versus copies, np.linalg basics, Random Generator API, einsum.

Mini project: Implement k-nearest-neighbour classification on the scikit-learn digits dataset using only NumPy: vectorized distance matrix, argsort, majority vote, and accuracy.

Self-check: What shape does `a - b` produce if `a` has shape (5,) and `b` has shape (5, 1), and why?

Resources:
- [NumPy user guide](https://numpy.org/doc/stable/user/) (numpy.org)
- [NumPy: the absolute basics for beginners](https://numpy.org/doc/stable/user/absolute_beginners.html) (numpy.org)

### pandas for Tabular Data

core · beginner · about 14 h · https://www.internhack.in/roadmaps/tracks/machine-learning/pandas

Loading, filtering, joining, grouping and reshaping tables, the daily bread of data scientists before and after modelling.

Most real ML problems begin as tables: CSV exports, database dumps, logs. pandas gives you the `DataFrame`, a labelled table with typed columns, plus a huge toolkit for wrangling it.

#### Core operations
- **I/O**: `read_csv`, `read_parquet`, `read_sql`; set `dtype` and `parse_dates` explicitly.
- **Selection**: `df.loc` (labels) versus `df.iloc` (positions), boolean filtering, `query`.
- **Transformation**: new columns, `assign`, vectorized string (`.str`) and datetime (`.dt`) accessors.
- **Aggregation**: `groupby(...).agg(...)` is the single most useful pattern for features and reports.
- **Combining**: `merge` (SQL-like joins), `concat`; check row counts before and after every join.
- **Reshaping**: `pivot_table`, `melt`, `stack`.
- **Missing data**: `isna`, `fillna`, `dropna`, and understanding `NaN` semantics.

#### Pitfalls
`SettingWithCopyWarning` means you may be editing a temporary copy. Row-wise `apply` is slow; look for a vectorized method first. Many-to-many merges silently multiply rows. For data that does not fit in memory look at Polars or DuckDB later.

**Good enough to move on** when you can take two related raw tables, join them, engineer a few grouped aggregates and export a clean modelling table without copying code from Stack Overflow for every step.

Key concepts: Series and DataFrame, loc, iloc and boolean filters, groupby and aggregation, merge and concat, pivot_table and melt, String and datetime accessors, Parquet and dtypes, Polars.

Mini project: Using the public NYC TLC taxi trip data (one month in Parquet), compute average fare and trip duration by hour of day and pickup zone, joined with the zone lookup table.

Self-check: You merge orders with customers and the row count grows. What does that tell you about the join keys?

Resources:
- [pandas user guide](https://pandas.pydata.org/docs/user_guide/) (pandas)
- [Kaggle Learn: Pandas](https://www.kaggle.com/learn/pandas) (Kaggle)

### Visualization with Matplotlib and Seaborn

core · beginner · about 6 h · https://www.internhack.in/roadmaps/tracks/machine-learning/data-visualization

Plotting distributions, relationships and model diagnostics so you see problems in data and models before metrics hide them.

Plots are how you catch skewed features, outliers, label noise and overfitting curves. Matplotlib is the low-level engine; Seaborn sits on top and makes statistical plots from DataFrames in one line.

#### What to learn
- **Matplotlib object API**: `fig, ax = plt.subplots()` and calling methods on `ax`. It scales to multi-panel figures far better than the `plt.` state machine.
- **Distributions**: histograms, KDEs, box and violin plots (`sns.histplot`, `sns.boxplot`).
- **Relationships**: scatter plots, pair plots, correlation heatmaps.
- **Categorical comparisons**: bar and count plots with confidence intervals.
- **ML diagnostics**: learning curves, confusion matrices, residual plots, ROC curves.

#### Habits
Always label axes and units, use log scales for heavy-tailed data, and prefer small multiples over cramming ten series on one chart. Interactive tools like Plotly are handy for dashboards but optional here.

**Good enough to move on** when you can produce a one-page EDA figure (distribution, relationship and category panels) for any new dataset in a few minutes.

Key concepts: Figure and Axes API, Distribution plots, Scatter and pair plots, Heatmaps, Diagnostic plots for models, Plotly for interactivity.

Mini project: Build a 2x3 subplot EDA figure for the Palmer Penguins dataset: species counts, bill length distributions per species, a flipper versus body mass scatter, and a correlation heatmap.

Self-check: When would a histogram mislead you where a box plot or ECDF would not?

Resources:
- [Seaborn tutorial](https://seaborn.pydata.org/tutorial.html) (seaborn)
- [Matplotlib documentation](https://matplotlib.org/stable/) (matplotlib)
- [Kaggle Learn: Data Visualization](https://www.kaggle.com/learn/data-visualization) (Kaggle)

### Git for ML Projects

core · beginner · about 5 h · https://www.internhack.in/roadmaps/tracks/machine-learning/git-for-ml

Versioning code and notebooks, branching for experiments and keeping large data and model files out of your repository.

Every serious ML result should be traceable to a commit. Git gives you history, safe experimentation on branches and collaboration through pull requests.

#### Essentials
- `init`, `add`, `commit`, `log`, `diff`, `status` as muscle memory.
- Branches per experiment or feature, merging and resolving conflicts.
- Remotes on GitHub or GitLab, pull requests and reviews.
- A good `.gitignore`: data folders, checkpoints, `.ipynb_checkpoints`, environment folders.

#### ML-specific concerns
- **Do not commit large data or model weights.** Use DVC, Git LFS or object storage instead (covered in MLOps).
- **Notebooks diff badly** because outputs are stored as JSON. Clear outputs before committing, or use tools like `nbstripout` or Jupytext.
- Record the commit hash with every experiment run so results are reproducible.

**Good enough to move on** when you can branch, commit, push, open a pull request and recover from an accidental commit without panic.

Key concepts: Commits, diffs and history, Branching and merging, GitHub remotes and pull requests, .gitignore for data projects, Notebook diffs with nbstripout or Jupytext, Git LFS.

Mini project: Put your previous NumPy and pandas notebooks in a GitHub repo with a proper .gitignore, stripped notebook outputs, a README and one feature branch merged via pull request.

Self-check: Why is committing a 2 GB CSV to Git a problem even if you delete it in the next commit?

Resources:
- [Pro Git](https://git-scm.com/book/en/v2) (git-scm.com)
- [The Missing Semester: Version Control](https://missing.csail.mit.edu/2020/version-control/) (MIT)

### SQL for Pulling Training Data

recommended · beginner · about 8 h · https://www.internhack.in/roadmaps/tracks/machine-learning/sql-for-data

Querying relational databases and warehouses to build datasets, since most company data lives behind SQL rather than in CSV files.

In industry you rarely get a tidy CSV. Training data is extracted from Postgres, BigQuery, Snowflake or similar with SQL, and interviewers for data roles almost always test it.

#### What to know
- `SELECT`, `WHERE`, `ORDER BY`, `LIMIT` and filtering on dates.
- `GROUP BY` with aggregates and `HAVING`.
- Joins (`INNER`, `LEFT`) and how they create or drop rows.
- Common table expressions (`WITH`) to keep complex queries readable.
- **Window functions** (`ROW_NUMBER`, `LAG`, running sums): essential for time-based features.

#### ML angle
Build features **as of a point in time**: when predicting churn on 1 March, only use events before 1 March. Getting this wrong in SQL is one of the most common sources of target leakage. DuckDB lets you run SQL directly over local Parquet files, which is great for practice.

**Good enough to move on** when you can write a query that produces one row per customer with aggregated activity features over the previous 30 days.

Key concepts: SELECT, WHERE and ORDER BY, GROUP BY and HAVING, Joins, CTEs, Window functions, DuckDB over Parquet.

Mini project: Load a public e-commerce dataset (for example the Olist Brazilian E-Commerce data on Kaggle) into DuckDB and write a query producing per-customer features such as order count, total spend and days since last order.

Self-check: How would you compute a feature like 'purchases in the 30 days before each order' without leaking future data?

Resources:
- [SQLBolt interactive lessons](https://sqlbolt.com/) (SQLBolt)
- [Kaggle Learn: Intro to SQL](https://www.kaggle.com/learn/intro-to-sql) (Kaggle)
- [DuckDB documentation](https://duckdb.org/docs/) (DuckDB)

## The Math Behind the Models

Linear algebra, calculus, probability, statistics and optimization at the depth needed to understand, debug and adapt models.

### Linear Algebra for ML

core · beginner · about 18 h · https://www.internhack.in/roadmaps/tracks/machine-learning/linear-algebra

Vectors, matrices, dot products, projections and decompositions: the language in which data, models and embeddings are written.

A dataset is a matrix, a linear model is a matrix-vector product, and a neural network layer is a matrix multiply followed by a nonlinearity. Linear algebra is how you reason about all of them.

#### Concepts to own
- **Vectors and dot products**: similarity, angles, and why cosine similarity drives search over embeddings.
- **Matrices as transformations**: rotation, scaling, projection; matrix multiplication as composition.
- **Norms**: L1 and L2 norms reappear as regularization penalties.
- **Rank, span and linear independence**: why duplicated features break ordinary least squares.
- **Eigenvalues and eigenvectors**: the core of PCA and of understanding covariance.
- **Singular value decomposition (SVD)**: low-rank approximation, PCA, recommender systems, LoRA.

#### How to study
Build geometric intuition first (the 3Blue1Brown series), then verify every idea in NumPy: multiply matrices, check shapes, compute an SVD and reconstruct the matrix. You do not need proofs; you need to predict shapes and interpret results.

**Good enough to move on** when you can explain PCA as finding directions of maximum variance using eigenvectors of the covariance matrix, and implement it with `np.linalg.svd`.

Key concepts: Vectors, dot product and cosine similarity, Matrix multiplication and shapes, Norms, Rank and linear independence, Eigenvalues and eigenvectors, SVD and low-rank approximation, Matrix calculus notation.

Mini project: Compress a grayscale image with truncated SVD in NumPy, plot reconstructions at ranks 5, 20 and 50, and chart how much of the total energy (sum of squared singular values) each rank keeps.

Self-check: If a feature matrix has two perfectly correlated columns, what happens to its rank and why does that matter for linear regression?

Resources:
- [Essence of Linear Algebra](https://www.3blue1brown.com/topics/linear-algebra) (3Blue1Brown)
- [Mathematics for Machine Learning](https://mml-book.github.io/) (Deisenroth, Faisal, Ong)

### Calculus and Gradients

core · beginner · about 12 h · https://www.internhack.in/roadmaps/tracks/machine-learning/calculus-gradients

Derivatives, partial derivatives, the chain rule and gradients: what lets a model know which way to adjust its parameters.

Training is minimizing a loss function. The gradient tells you the direction of steepest increase, so stepping the opposite way decreases the loss. Backpropagation is simply the chain rule applied efficiently.

#### Concepts
- **Derivatives** as local slopes; derivatives of common functions (polynomials, exp, log, sigmoid).
- **Partial derivatives and the gradient vector** for functions of many parameters.
- **The chain rule**: derivative of a composition. Draw computation graphs to apply it mechanically.
- **Jacobians and Hessians**: shapes of derivatives for vector outputs and second-order curvature (conceptual level).
- **Numerical gradient checking**: approximate `(f(x+h) - f(x-h)) / 2h` to verify an analytic gradient.

#### Practical focus
You will rarely derive gradients by hand in practice because autograd does it, but you must understand them to debug vanishing gradients, choose learning rates and read papers. Derive the gradient of mean squared error for linear regression and of log loss for logistic regression once, by hand.

**Good enough to move on** when you can compute the gradient of a small composed function via a computation graph and confirm it numerically.

Key concepts: Derivatives of common functions, Partial derivatives and gradients, Chain rule and computation graphs, Jacobians and Hessians, Numerical gradient checking.

Mini project: Derive the MSE gradient for linear regression, implement it in NumPy, verify it with finite differences, and use it to fit a line to synthetic noisy data.

Self-check: Using the chain rule, what is the derivative of sigmoid(w * x + b) with respect to w?

Resources:
- [Essence of Calculus](https://www.3blue1brown.com/topics/calculus) (3Blue1Brown)
- [Mathematics for Machine Learning (vector calculus chapter)](https://mml-book.github.io/) (Deisenroth, Faisal, Ong)
- [Khan Academy: Multivariable calculus](https://www.khanacademy.org/math/multivariable-calculus) (Khan Academy)

### Probability for ML

core · beginner · about 12 h · https://www.internhack.in/roadmaps/tracks/machine-learning/probability

Random variables, distributions, conditional probability and Bayes' rule, the vocabulary for uncertainty, likelihoods and loss functions.

Classifiers output probabilities, losses are negative log-likelihoods, and many models (naive Bayes, Gaussian mixtures, VAEs) are explicitly probabilistic. Probability lets you interpret all of them.

#### Concepts
- **Random variables, PMFs and PDFs**; expectation and variance.
- **Key distributions**: Bernoulli, binomial, categorical, Poisson, uniform, Gaussian (and the multivariate Gaussian).
- **Joint, marginal and conditional probability**; independence.
- **Bayes' rule**: updating beliefs from evidence; base rates and why rare-event classifiers produce many false positives.
- **Likelihood and maximum likelihood estimation**: MSE corresponds to a Gaussian likelihood, cross-entropy to a categorical one.
- **Entropy, cross-entropy and KL divergence**: the information-theory terms used in loss functions and generative models.

#### Practice
Simulate. Sample from distributions with NumPy, estimate means and probabilities empirically, and compare with the formulas. Simulation builds intuition faster than algebra alone.

**Good enough to move on** when you can explain why minimizing cross-entropy is the same as maximizing likelihood for a classifier.

Key concepts: Random variables and expectation, Common distributions, Conditional probability and independence, Bayes' rule, Maximum likelihood estimation, Entropy, cross-entropy and KL divergence, Multivariate Gaussian.

Mini project: Simulate a medical test with 1% prevalence, 95% sensitivity and 90% specificity for 100,000 people and compare the empirical probability of disease given a positive test to the Bayes' rule answer.

Self-check: A fraud model flags 1,000 transactions with a 2% true fraud base rate. Why can precision be low even when recall and specificity look good?

Resources:
- [Seeing Theory: a visual introduction to probability](https://seeing-theory.brown.edu/) (Brown University)
- [Khan Academy: Statistics and probability](https://www.khanacademy.org/math/statistics-probability) (Khan Academy)
- [Mathematics for Machine Learning (probability chapter)](https://mml-book.github.io/) (Deisenroth, Faisal, Ong)

### Statistics for Data Science

core · beginner · about 14 h · https://www.internhack.in/roadmaps/tracks/machine-learning/statistics

Descriptive statistics, sampling, confidence intervals, hypothesis tests and A/B testing to reason about data and model results honestly.

Statistics separates real effects from noise. It tells you whether model B is actually better than model A and whether an observed pattern in data would survive a new sample.

#### Topics
- **Descriptive stats**: mean, median, variance, quantiles, skew; correlation versus causation.
- **Sampling and the central limit theorem**: why averages are approximately normal and how sample size affects precision.
- **Confidence intervals and the bootstrap**: resample your test set to put error bars on a metric.
- **Hypothesis testing**: null hypotheses, p-values, t-tests, chi-squared tests, and what a p-value does not mean.
- **Multiple comparisons**: testing 50 features or 50 model variants inflates false discoveries.
- **A/B testing**: randomization, power, minimum detectable effect; how models are validated in production.

#### Pitfalls
Reporting a single accuracy number with no uncertainty, p-hacking by trying many analyses until one is significant, and confusing statistical significance with practical importance.

**Good enough to move on** when you can bootstrap a 95% confidence interval for a model's F1 score and interpret whether two models differ meaningfully.

Key concepts: Descriptive statistics, Central limit theorem, Confidence intervals and bootstrap, Hypothesis tests and p-values, Multiple comparisons, A/B testing and power, Bayesian inference basics.

Mini project: Train two classifiers on the UCI Adult income dataset and use bootstrap resampling of the test set to estimate confidence intervals for the accuracy difference between them.

Self-check: What exactly does a p-value of 0.03 tell you, and what does it not tell you?

Resources:
- [An Introduction to Statistical Learning](https://www.statlearning.com/) (James, Witten, Hastie, Tibshirani)
- [Khan Academy: Statistics and probability](https://www.khanacademy.org/math/statistics-probability) (Khan Academy)

### Optimization and Gradient Descent

core · intermediate · about 10 h · https://www.internhack.in/roadmaps/tracks/machine-learning/optimization

Loss landscapes, convexity, gradient descent and its stochastic variants: how model parameters are actually found.

Fitting a model means solving an optimization problem: find parameters that minimize a loss. A few models have closed-form solutions, but almost everything else uses iterative, gradient-based methods.

#### Concepts
- **Objective functions**: loss plus regularization terms.
- **Convex versus non-convex**: linear and logistic regression have one global minimum; neural networks do not, yet still train well in practice.
- **Gradient descent**: repeat `theta = theta - lr * grad`. The learning rate is the most important knob.
- **Stochastic and mini-batch gradient descent**: noisy but cheap gradient estimates from small batches; the default for large data.
- **Momentum and adaptive methods** (preview): SGD with momentum, RMSProp, Adam. Covered in depth in the deep learning section.
- **Constrained optimization and Lagrange multipliers**: conceptual level, for understanding SVMs.

#### Diagnosing
Plot the loss per iteration. Divergence or oscillation means the learning rate is too high; a flat slow curve means too low or poorly scaled features. Feature scaling dramatically speeds up gradient descent.

**Good enough to move on** when you can implement mini-batch gradient descent for logistic regression and explain the effect of learning rate and batch size on the loss curve.

Key concepts: Loss functions and objectives, Convexity, Batch gradient descent, Stochastic and mini-batch GD, Learning rate effects, Momentum and Adam preview, Lagrange multipliers.

Mini project: Implement batch, mini-batch and stochastic gradient descent for logistic regression on the Breast Cancer Wisconsin dataset and plot loss curves for three learning rates on one figure.

Self-check: Your loss goes to NaN after a few iterations. Name two likely causes and how you would check each.

Resources:
- [Google ML Crash Course (gradient descent module)](https://developers.google.com/machine-learning/crash-course) (Google)
- [Dive into Deep Learning: Optimization Algorithms](https://d2l.ai/chapter_optimization/index.html) (d2l.ai)

## From Raw Data to Model-Ready Features

Exploring, cleaning, transforming and splitting data correctly, which usually matters more than which algorithm you pick.

### Exploratory Data Analysis

core · beginner · about 6 h · https://www.internhack.in/roadmaps/tracks/machine-learning/exploratory-data-analysis

A systematic first pass over a new dataset to understand its shape, quality, target and the relationships worth modelling.

EDA is where you form hypotheses and find problems cheaply. Skipping it leads to models that learn from IDs, duplicated rows or data-entry artifacts.

#### A repeatable checklist
- **Shape and schema**: rows, columns, dtypes, what one row represents.
- **Target**: distribution, class balance, how and when it was recorded.
- **Missingness**: which columns, how much, and whether missingness itself correlates with the target.
- **Univariate views**: ranges, outliers, impossible values (negative ages, dates in the future).
- **Bivariate views**: each feature against the target; correlations among features.
- **Duplicates and leakage suspects**: columns that look too predictive usually encode the answer.

#### Output
Write down findings as a short list of decisions: which columns to drop, how to handle missing values, which features to engineer. EDA without written conclusions is sightseeing.

**Good enough to move on** when you can open an unfamiliar Kaggle dataset and, within an hour, produce a notebook with key plots and a clear list of data issues and modelling ideas.

Key concepts: Schema and unit of analysis, Target distribution, Missingness patterns, Outliers and impossible values, Feature-target relationships, Automated profiling tools.

Mini project: Run a full EDA on the Kaggle House Prices (Ames) dataset and finish the notebook with a written list of ten concrete cleaning and feature decisions.

Self-check: You find a column that alone predicts the target with 99% accuracy. What should you investigate before celebrating?

Resources:
- [Kaggle Learn courses](https://www.kaggle.com/learn) (Kaggle)
- [pandas user guide](https://pandas.pydata.org/docs/user_guide/) (pandas)

### Data Cleaning and Missing Values

core · beginner · about 6 h · https://www.internhack.in/roadmaps/tracks/machine-learning/data-cleaning

Handling missing values, outliers, duplicates, inconsistent categories and type errors in a principled, reproducible way.

Real data is messy. Cleaning decisions change model behaviour, so make them deliberately and encode them in code rather than editing files by hand.

#### Missing values
- Understand the mechanism: missing completely at random, at random, or not at random (a blank income field may mean something).
- Simple imputation: median for numeric, most frequent or an explicit `missing` category for categorical.
- Add **missing indicator** columns when missingness may be informative.
- Model-based imputation (KNN, iterative) is optional and rarely worth the complexity early on.
- Tree boosting libraries handle `NaN` natively, which is often the simplest option.

#### Other cleaning
- **Outliers**: distinguish errors (fix or drop) from real extremes (keep, maybe clip or log-transform).
- **Duplicates**: exact and near duplicates can leak between train and test.
- **Inconsistent categories**: `NY`, `New York`, `new york ` should be one value.
- **Types**: numbers stored as strings, dates as text, units mixed in one column.

#### Critical rule
Fit imputers and other data-dependent cleaning **on training data only**, then apply to validation and test. scikit-learn pipelines (later) make this automatic.

**Good enough to move on** when your cleaning is a rerunnable function or pipeline, not a sequence of manual notebook edits.

Key concepts: Missing data mechanisms, Simple imputation, Missing indicators, Outlier handling, Deduplication, Category normalization, KNN and iterative imputation.

Mini project: Write a reusable clean() function for the Kaggle House Prices data that handles every missing column with a justified strategy, fixes types, and is covered by a few assert-based sanity checks.

Self-check: Why is it wrong to compute the median for imputation on the full dataset before splitting into train and test?

Resources:
- [Kaggle Learn: Data Cleaning](https://www.kaggle.com/learn/data-cleaning) (Kaggle)
- [scikit-learn: Imputation of missing values](https://scikit-learn.org/stable/modules/impute.html) (scikit-learn)

### Feature Engineering

core · intermediate · about 10 h · https://www.internhack.in/roadmaps/tracks/machine-learning/feature-engineering

Turning domain knowledge into informative inputs: aggregates, ratios, date parts, text counts, interactions and transformations.

For tabular problems, good features beat fancy algorithms. Feature engineering encodes what you know about the domain in a form models can use.

#### Common patterns
- **Datetime features**: hour, weekday, month, holidays, time since an event. Use cyclical sine/cosine encoding for hour or month when order wraps around.
- **Aggregates**: counts, means and recency per user, product or region (group-by features).
- **Ratios and differences**: price per square foot, debt to income.
- **Transformations**: `log1p` for heavy-tailed values, binning when relationships are step-like.
- **Interactions**: products of features for linear models; trees find many interactions on their own.
- **Text and geo basics**: word counts, TF-IDF, distances to landmarks.

#### Process
Add features one idea at a time and measure the change in cross-validated score. Keep a log of what helped. Remove features that add noise or are expensive to compute in production.

#### Pitfalls
Aggregates computed over the whole dataset (including the future or the test set) leak information. Features that are unavailable at prediction time are useless no matter how predictive they look offline.

**Good enough to move on** when you can add three to five engineered features to a baseline and demonstrate their value with cross-validation.

Key concepts: Datetime and cyclical features, Group-by aggregates, Ratios and domain features, Log and power transforms, Interaction and polynomial features, Feature selection, Automated feature tools.

Mini project: On the Kaggle Bike Sharing Demand dataset, engineer datetime, weather and rolling features and report the cross-validated RMSE gain of each feature group over a baseline.

Self-check: Why might a feature that improves validation score still be a bad feature to ship?

Resources:
- [Kaggle Learn: Feature Engineering](https://www.kaggle.com/learn/feature-engineering) (Kaggle)
- [scikit-learn: Feature selection](https://scikit-learn.org/stable/modules/feature_selection.html) (scikit-learn)

### Encoding Categories and Scaling Numbers

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/machine-learning/encoding-and-scaling

Converting categorical variables into numbers and putting numeric features on comparable scales, and knowing which models care.

Models need numeric input, and many are sensitive to feature scale. The right encoding and scaling depends on the model family.

#### Categorical encoding
- **One-hot encoding**: the safe default for low-cardinality categories; set `handle_unknown='ignore'` for unseen values at inference.
- **Ordinal encoding**: for truly ordered categories (small, medium, large) and often fine for tree models.
- **Target (mean) encoding**: powerful for high-cardinality columns like ZIP codes but leaks unless computed out-of-fold.
- **Hashing and embeddings**: for very high cardinality or deep learning models.

#### Scaling
- **StandardScaler** (zero mean, unit variance): default for linear models, SVMs, kNN, neural networks.
- **MinMaxScaler**: bounded ranges, common for images and some neural nets.
- **RobustScaler**: uses medians and IQR, better with outliers.
- **Tree-based models do not need scaling**; splits are invariant to monotonic transforms.

#### Rule
Fit encoders and scalers on the training fold only. Use `ColumnTransformer` to apply different preprocessing to numeric and categorical columns in one object.

**Good enough to move on** when you can explain which preprocessing a kNN model, a logistic regression and a random forest each require, and implement it without leakage.

Key concepts: One-hot encoding, Ordinal encoding, Target encoding, Standard, min-max and robust scaling, ColumnTransformer, Feature hashing.

Mini project: Compare one-hot, ordinal and target encoding for the high-cardinality columns of the UCI Adult dataset using logistic regression and a gradient boosted model, reporting cross-validated scores for each.

Self-check: Why does kNN performance change drastically when you forget to scale features, while a decision tree does not change at all?

Resources:
- [scikit-learn: Preprocessing data](https://scikit-learn.org/stable/modules/preprocessing.html) (scikit-learn)
- [Kaggle Learn: Intermediate Machine Learning](https://www.kaggle.com/learn/intermediate-machine-learning) (Kaggle)

### Train/Validation/Test Splits and Data Leakage

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/machine-learning/splits-and-leakage

Designing splits that mimic real deployment and spotting the leakage that makes offline results look far better than reality.

Your evaluation is only as honest as your split. The test set simulates the future; if information from it (or from the future) sneaks into training, your metrics lie.

#### Split strategies
- **Train / validation / test**: train fits parameters, validation guides choices, test is touched once at the end.
- **Stratified splits** keep class proportions stable for classification.
- **Group splits**: all rows from one patient, user or device stay in the same split (`GroupKFold`).
- **Time-based splits**: train on the past, validate on the future. Random splits on time series are almost always wrong.

#### Kinds of leakage
- **Target leakage**: a feature that is only known after the outcome (for example `refund_issued` when predicting fraud).
- **Train-test contamination**: fitting scalers, imputers or feature selection on all data before splitting.
- **Duplicate or near-duplicate rows** across splits (common with images and user records).
- **Temporal leakage**: aggregates or normalizations computed with future data.
- **Test set overuse**: tuning repeatedly against the test set turns it into a validation set.

**Good enough to move on** when, for any new problem, you can state what one prediction looks like in production, what data is available at that moment, and design a split that mirrors it.

Key concepts: Holdout splits, Stratified splitting, Group-aware splits, Time-based splits, Target leakage, Preprocessing leakage, Adversarial validation.

Mini project: Deliberately build a leaky pipeline on a public dataset (scale and select features before splitting, random split on time-ordered data), measure the inflated score, then fix each leak and report the honest score.

Self-check: You have multiple X-ray images per patient. Why does a random image-level split overestimate performance?

Resources:
- [scikit-learn: Common pitfalls and recommended practices](https://scikit-learn.org/stable/common_pitfalls.html) (scikit-learn)
- [Kaggle Learn: Intermediate Machine Learning (data leakage lesson)](https://www.kaggle.com/learn/intermediate-machine-learning) (Kaggle)

## Classical Supervised Learning

The workhorse algorithms for labelled tabular data, from linear baselines to gradient boosted trees, learned through scikit-learn.

### Framing ML Problems and the scikit-learn API

core · beginner · about 5 h · https://www.internhack.in/roadmaps/tracks/machine-learning/ml-problem-framing

Turning a business question into a learning task with a target, metric and baseline, and the fit/predict interface shared by scikit-learn models.

Before choosing an algorithm, decide what you are predicting, for whom, and how success is measured. Many failed ML projects had fine models for the wrong question.

#### Framing
- **Task type**: regression (a number), binary or multiclass classification, ranking, clustering, forecasting.
- **Unit and timing**: one prediction per what, made when, using which information.
- **Metric tied to cost**: a missed fraud case and a false alarm rarely cost the same.
- **Baselines**: predict the mean or majority class, or a simple rule. If ML cannot beat a heuristic, stop and rethink.
- **Is ML even needed?** Deterministic rules are cheaper to build and explain when they work.

#### The scikit-learn estimator API
Every model follows the same shape: `model = SomeEstimator(**hyperparams)`, `model.fit(X_train, y_train)`, then `model.predict(X)` or `model.predict_proba(X)`. Transformers use `fit` / `transform`. Learned attributes end in an underscore (`coef_`, `feature_importances_`). This consistency means once you learn one model you can swap in others in one line.

**Good enough to move on** when you can write a one-paragraph problem statement with target, metric and baseline, and train a `DummyClassifier` baseline plus one real model with scikit-learn.

Key concepts: Regression versus classification, Choosing a metric from business cost, Baselines and DummyEstimators, fit, predict and predict_proba, Transformers and fit_transform, When not to use ML.

Mini project: Write a one-page problem framing for predicting customer churn with the public Telco Customer Churn dataset, then train a majority-class baseline and a logistic regression and compare them.

Self-check: Why should every project start with a dummy baseline before any tuned model?

Resources:
- [scikit-learn: Getting started](https://scikit-learn.org/stable/getting_started.html) (scikit-learn)
- [Google ML Crash Course](https://developers.google.com/machine-learning/crash-course) (Google)
- [Kaggle Learn: Intro to Machine Learning](https://www.kaggle.com/learn/intro-to-machine-learning) (Kaggle)

### Linear Regression and Regularization

core · beginner · about 8 h · https://www.internhack.in/roadmaps/tracks/machine-learning/linear-regression

Least squares, interpreting coefficients, and ridge, lasso and elastic net penalties for more stable models.

Linear regression predicts a number as a weighted sum of features. It is fast, interpretable and a strong baseline, and its ideas (loss, gradients, regularization) carry into every other model.

#### Core ideas
- **Ordinary least squares** minimizes mean squared error; it has a closed-form solution and a gradient descent solution.
- **Coefficients** give the change in prediction per unit feature change, holding others fixed. Scale features before comparing magnitudes.
- **Assumptions** (linearity, independent errors, constant variance) matter most for inference, less for pure prediction.
- **Polynomial and spline features** let a linear model fit curves.

#### Regularization
- **Ridge (L2)** shrinks all coefficients; helps with correlated features.
- **Lasso (L1)** drives some coefficients to exactly zero, acting as feature selection.
- **Elastic net** mixes both.
The penalty strength (`alpha`) is a hyperparameter chosen by cross-validation. Always scale features first, because the penalty treats all coefficients equally.

#### Pitfalls
Extrapolating far outside the training range, reading coefficients causally, and ignoring residual plots that reveal a missing nonlinearity.

**Good enough to move on** when you can fit OLS, ridge and lasso, choose alpha with `RidgeCV` or `LassoCV`, and interpret the resulting coefficients and residuals.

Key concepts: Ordinary least squares, Interpreting coefficients, Residual analysis, Polynomial features, Ridge, lasso and elastic net, Statsmodels for inference.

Mini project: Predict median house value on the scikit-learn California Housing dataset with OLS, ridge and lasso, compare cross-validated RMSE, and plot which coefficients lasso sets to zero as alpha grows.

Self-check: Why must you standardize features before applying ridge or lasso regularization?

Resources:
- [scikit-learn: Linear models](https://scikit-learn.org/stable/modules/linear_model.html) (scikit-learn)
- [An Introduction to Statistical Learning (chapters 3 and 6)](https://www.statlearning.com/) (ISL)

### Logistic Regression and Linear Classifiers

core · beginner · about 6 h · https://www.internhack.in/roadmaps/tracks/machine-learning/logistic-regression

Modelling class probabilities with the sigmoid and softmax, log loss, decision thresholds and calibrated linear baselines.

Logistic regression is the default first classifier: fast, robust, interpretable and it outputs probabilities. Understanding it deeply also means understanding the last layer of most neural network classifiers.

#### How it works
- Compute a linear score `z = w . x + b`, squash it with the **sigmoid** to get a probability.
- Train by minimizing **log loss (binary cross-entropy)**, which is convex, so optimization is reliable.
- **Multiclass**: softmax (multinomial) regression or one-vs-rest.
- **Coefficients** are changes in log-odds; `exp(coef)` is an odds ratio.

#### Practical points
- The default decision threshold of 0.5 is arbitrary. Choose a threshold from the costs of false positives and false negatives.
- Regularization is on by default in scikit-learn (`C` is the inverse strength).
- Scale features, and one-hot encode categories.
- Linear decision boundaries can be made flexible with engineered or polynomial features.

**Good enough to move on** when you can train a logistic regression, explain a coefficient as an odds ratio, and pick a threshold that meets a target recall.

Key concepts: Sigmoid and log-odds, Log loss, Softmax for multiclass, Decision thresholds, Regularization strength C, Odds ratio interpretation.

Mini project: Build a logistic regression on the Telco Customer Churn dataset, report the five strongest odds ratios, and choose a threshold that catches 80% of churners while reporting the resulting precision.

Self-check: Why is log loss preferred over accuracy as the training objective for a probabilistic classifier?

Resources:
- [scikit-learn: Logistic regression](https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression) (scikit-learn)
- [Google ML Crash Course: Logistic regression](https://developers.google.com/machine-learning/crash-course) (Google)

### k-Nearest Neighbours and Naive Bayes

recommended · beginner · about 4 h · https://www.internhack.in/roadmaps/tracks/machine-learning/knn-and-naive-bayes

Two simple, instructive models: similarity-based prediction and fast probabilistic classification with independence assumptions.

These models are rarely your final choice on tabular data, but they are fast baselines, teach key concepts and remain useful in specific niches.

#### k-nearest neighbours
- Predicts from the labels of the `k` closest training points; no real training step.
- Needs **scaled features** and a sensible distance metric.
- Small `k` overfits (noisy), large `k` underfits (too smooth).
- Suffers from the **curse of dimensionality**: in many dimensions all points look equally far apart.
- The same idea powers vector search over embeddings (approximate nearest neighbours).

#### Naive Bayes
- Applies Bayes' rule assuming features are independent given the class.
- **Multinomial NB** on word counts is a classic, very strong baseline for text classification.
- **Gaussian NB** for continuous features, **Bernoulli NB** for binary ones.
- Trains in one pass and handles huge vocabularies easily; probabilities tend to be poorly calibrated.

**Good enough to move on** when you can explain why kNN degrades in high dimensions and build a text classifier with TF-IDF or counts plus naive Bayes.

Key concepts: Distance metrics, Choosing k, Curse of dimensionality, Multinomial naive Bayes for text, Gaussian and Bernoulli NB, Approximate nearest neighbour search.

Mini project: Build an SMS spam filter on the UCI SMS Spam Collection with CountVectorizer and multinomial naive Bayes, and compare it with kNN on TF-IDF features.

Self-check: What does the 'naive' in naive Bayes assume, and why does the model often work well anyway?

Resources:
- [scikit-learn: Nearest neighbors](https://scikit-learn.org/stable/modules/neighbors.html) (scikit-learn)
- [scikit-learn: Naive Bayes](https://scikit-learn.org/stable/modules/naive_bayes.html) (scikit-learn)

### Decision Trees

core · beginner · about 5 h · https://www.internhack.in/roadmaps/tracks/machine-learning/decision-trees

Recursive splitting on features to build interpretable if-then models, and how depth and leaf size control overfitting.

A decision tree asks a sequence of yes/no questions about features. Trees handle mixed feature types, need no scaling, capture interactions and are easy to visualize. On their own they overfit easily, but they are the building block of the strongest tabular models.

#### How trees learn
- At each node, choose the feature and threshold that best reduce **impurity**: Gini or entropy for classification, variance (MSE) for regression.
- Split greedily until a stopping rule is hit.
- Leaves predict the majority class or mean target of their samples.

#### Controlling complexity
- `max_depth`, `min_samples_leaf`, `min_samples_split`, `max_leaf_nodes`.
- **Cost-complexity pruning** (`ccp_alpha`) trims branches after growing.
- A fully grown tree memorizes training data: near-100% training accuracy, poor test accuracy.

#### Interpretation
Plot the tree with `plot_tree` or export rules. Impurity-based feature importances are convenient but biased toward high-cardinality features; prefer permutation importance for conclusions.

**Good enough to move on** when you can show the overfitting curve of a tree as depth grows and pick a depth by cross-validation.

Key concepts: Gini, entropy and variance splits, Depth and leaf-size limits, Cost-complexity pruning, Visualizing trees, Feature importance caveats.

Mini project: Train decision trees of depth 1 to 20 on the UCI Heart Disease dataset, plot train versus validation accuracy, and visualize the best tree's top three levels.

Self-check: Why does a decision tree not need feature scaling, and why does it still overfit easily?

Resources:
- [scikit-learn: Decision trees](https://scikit-learn.org/stable/modules/tree.html) (scikit-learn)
- [An Introduction to Statistical Learning (chapter 8)](https://www.statlearning.com/) (ISL)

### Bagging and Random Forests

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/machine-learning/random-forests

Averaging many decorrelated trees to cut variance, giving a robust, low-tuning model for tabular data.

A single tree is high variance: small data changes produce a very different tree. **Bagging** trains many trees on bootstrap samples and averages them. **Random forests** add random feature subsets at each split so trees disagree more, which makes the average even better.

#### Key hyperparameters
- `n_estimators`: more trees rarely hurt, just cost time; a few hundred is typical.
- `max_features`: features considered per split; the main decorrelation knob.
- `max_depth` / `min_samples_leaf`: usually left fairly deep.
- `n_jobs=-1` to train in parallel.

#### Useful extras
- **Out-of-bag (OOB) score**: each tree ignores about a third of the data, giving a free validation estimate.
- **Extra Trees**: even more randomized splits, faster and sometimes better.
- **Permutation importance** for trustworthy feature rankings.

#### When to use
Random forests are an excellent low-effort baseline: hard to badly misconfigure, robust to outliers and irrelevant features. They are usually beaten by well-tuned gradient boosting, and they cannot extrapolate beyond the target range seen in training.

**Good enough to move on** when you can explain why averaging decorrelated trees reduces variance and use the OOB score to sanity-check a model.

Key concepts: Bootstrap aggregation, Random feature subsets, Out-of-bag evaluation, Permutation importance, Extra Trees.

Mini project: Train a random forest on the Kaggle House Prices dataset, compare OOB score with 5-fold CV score, and compare impurity-based and permutation feature importances.

Self-check: Why does restricting max_features at each split usually improve a forest even though each tree gets worse?

Resources:
- [scikit-learn: Ensemble methods](https://scikit-learn.org/stable/modules/ensemble.html) (scikit-learn)
- [scikit-learn: Permutation feature importance](https://scikit-learn.org/stable/modules/permutation_importance.html) (scikit-learn)

### Gradient Boosting with XGBoost and LightGBM

core · intermediate · about 10 h · https://www.internhack.in/roadmaps/tracks/machine-learning/gradient-boosting

Sequentially adding small trees that fix previous errors, the go-to method for winning tabular problems in industry and on Kaggle.

Gradient boosting builds trees one after another, each fitted to the errors (gradients of the loss) of the ensemble so far. With sensible settings it is the strongest general-purpose model for structured data.

#### Libraries
- **XGBoost**: mature, fast, widely deployed.
- **LightGBM**: very fast on large data thanks to histogram and leaf-wise growth.
- **CatBoost**: excellent native handling of categorical features.
- **scikit-learn HistGradientBoosting**: good built-in option with no extra dependency.

#### Important hyperparameters
- `learning_rate` and `n_estimators` trade off together: lower rate, more trees.
- Tree size: `max_depth` or `num_leaves`, and `min_child_weight` / `min_data_in_leaf`.
- Randomness: `subsample` and `colsample_bytree` reduce overfitting.
- Regularization: `lambda` (L2) and `alpha` (L1) on leaf weights.
- **Early stopping** on a validation set picks the number of trees automatically; always use it.

#### Pitfalls
Early stopping on the test set (leakage), tuning twenty parameters before trying reasonable defaults, and ignoring native categorical and missing-value support that could simplify preprocessing.

**Good enough to move on** when you can train LightGBM or XGBoost with early stopping, beat your random forest on a Kaggle tabular dataset, and explain what the learning rate does.

Key concepts: Boosting intuition and residual fitting, XGBoost, LightGBM, CatBoost, Learning rate and number of trees, Early stopping, Native categorical and missing handling.

Mini project: Enter the Kaggle Spaceship Titanic competition with a LightGBM or XGBoost model using early stopping and engineered features, and document your cross-validation versus leaderboard scores.

Self-check: What happens to the best number of trees when you halve the learning rate, and why?

Resources:
- [XGBoost documentation](https://xgboost.readthedocs.io/en/stable/) (XGBoost)
- [LightGBM documentation](https://lightgbm.readthedocs.io/en/stable/) (LightGBM)
- [scikit-learn: Gradient boosting](https://scikit-learn.org/stable/modules/ensemble.html) (scikit-learn)

### Support Vector Machines and Kernels

recommended · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/machine-learning/support-vector-machines

Maximum-margin classifiers and the kernel trick for nonlinear boundaries on small and medium datasets.

SVMs find the boundary that separates classes with the widest margin. The **kernel trick** lets them draw nonlinear boundaries by implicitly mapping data into higher dimensions.

#### Concepts
- **Margin and support vectors**: only the points closest to the boundary define it.
- **Soft margin and C**: trades margin width against training errors; high C overfits.
- **Kernels**: linear, polynomial and RBF. For RBF, `gamma` controls how local each point's influence is.
- **Hinge loss**: the loss behind linear SVMs, comparable to log loss for logistic regression.
- **SVR** applies the same ideas to regression.

#### When to use today
SVMs shine on small to medium datasets with many features (for example text or bioinformatics). Kernel SVMs scale poorly past roughly 100k samples, and gradient boosting usually wins on typical tabular data. They do not output probabilities natively.

#### Must-do
Scale features and tune `C` and `gamma` together on a log grid.

**Good enough to move on** when you can visualize decision boundaries for linear and RBF SVMs on a 2D toy dataset and explain the effect of C and gamma.

Key concepts: Maximum margin, Soft margin and C, Kernel trick and RBF, Hinge loss, Support vector regression.

Mini project: Plot decision boundaries of linear, polynomial and RBF SVMs on scikit-learn's make_moons data for a grid of C and gamma values, then apply the best setup to the digits dataset.

Self-check: What does a very large gamma do to an RBF SVM's decision boundary?

Resources:
- [scikit-learn: Support vector machines](https://scikit-learn.org/stable/modules/svm.html) (scikit-learn)
- [An Introduction to Statistical Learning (chapter 9)](https://www.statlearning.com/) (ISL)

## Evaluating, Tuning and Packaging Models

Measuring models honestly, diagnosing under- and overfitting, tuning hyperparameters and wrapping everything in leak-proof pipelines.

### Evaluation Metrics

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/machine-learning/evaluation-metrics

Choosing and interpreting metrics for classification, regression and ranking so they reflect what actually matters.

A metric is a proxy for value. Picking the wrong one leads you to optimize the wrong thing, for example 99% accuracy on a dataset where 99% of cases are negative.

#### Classification
- **Confusion matrix**: the source of everything else.
- **Precision, recall, F1**: precision is how many flags are right, recall is how many positives are caught.
- **ROC AUC**: threshold-free ranking quality; can look optimistic under heavy imbalance.
- **PR AUC / average precision**: better for rare positives.
- **Log loss and Brier score**: quality of probabilities; pair with **calibration curves**.
- Macro versus weighted averages for multiclass.

#### Regression
- **MAE**: robust, in target units. **RMSE**: penalizes large errors more.
- **R squared**: variance explained, but not comparable across datasets.
- **MAPE**: intuitive percentages, breaks near zero targets.

#### Ranking
Precision@k, recall@k, MAP and NDCG for search and recommendations.

#### Habits
Always compare against a baseline, report uncertainty, and look at errors by segment (region, device, user group). A good global metric can hide a terrible subgroup.

**Good enough to move on** when you can pick an appropriate metric for a given business problem and justify it in two sentences.

Key concepts: Confusion matrix, Precision, recall and F1, ROC AUC and PR AUC, Log loss and calibration, MAE, RMSE and R squared, Ranking metrics, Slice-based evaluation.

Mini project: On the Kaggle Credit Card Fraud dataset, compare accuracy, ROC AUC, PR AUC and F1 for a logistic regression and a dummy model, and write a short note on which metric you would report to a fraud team.

Self-check: When would you prefer PR AUC over ROC AUC, and why?

Resources:
- [scikit-learn: Metrics and scoring](https://scikit-learn.org/stable/modules/model_evaluation.html) (scikit-learn)
- [scikit-learn: Probability calibration](https://scikit-learn.org/stable/modules/calibration.html) (scikit-learn)

### Cross-Validation

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/machine-learning/cross-validation

Using k-fold, stratified, group and time-series cross-validation to get stable performance estimates and compare models fairly.

A single validation split gives a noisy estimate. **Cross-validation** trains and evaluates on several different splits and averages the scores, giving both a better estimate and a sense of its variance.

#### Variants
- **KFold**: split into k folds, each serves once as validation. k = 5 or 10 is typical.
- **StratifiedKFold**: preserves class balance; default for classification.
- **GroupKFold / StratifiedGroupKFold**: keeps related rows together.
- **TimeSeriesSplit**: expanding windows that always validate on later data.
- **Repeated CV**: repeats with different shuffles for small datasets.

#### Using it well
- `cross_val_score` and `cross_validate` in scikit-learn; always pass a pipeline so preprocessing is refit in each fold.
- Look at the **standard deviation** across folds, not only the mean. A 0.2% improvement inside a 1% spread is noise.
- **Nested CV** gives an unbiased estimate when you also tune hyperparameters (inner loop tunes, outer loop evaluates).
- Keep a final holdout test set anyway for one last check.

**Good enough to move on** when you can pick the right CV splitter for a problem's structure and report mean and spread of the metric.

Key concepts: k-fold and stratified k-fold, Group k-fold, Time series split, Reading fold variance, Nested cross-validation.

Mini project: Compare three models on the UCI Wine Quality dataset using repeated stratified 5-fold CV, and plot score distributions per model as box plots to judge whether differences are real.

Self-check: Why must scaling and imputation happen inside each CV fold rather than once before cross-validation?

Resources:
- [scikit-learn: Cross-validation](https://scikit-learn.org/stable/modules/cross_validation.html) (scikit-learn)
- [An Introduction to Statistical Learning (chapter 5)](https://www.statlearning.com/) (ISL)

### Bias, Variance and Generalization

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/machine-learning/bias-variance

Diagnosing underfitting and overfitting with learning and validation curves, and choosing the right fix for each.

Every model error comes from some mix of **bias** (too simple to capture the pattern), **variance** (too sensitive to the particular training sample) and irreducible noise. Knowing which dominates tells you what to do next.

#### Diagnosis
- **High bias (underfitting)**: training and validation scores are both poor and close together.
- **High variance (overfitting)**: training score is great, validation score much worse.
- **Learning curves** (score versus training set size) show whether more data would help.
- **Validation curves** (score versus one hyperparameter) show the sweet spot of complexity.

#### Fixes
- For bias: more expressive model, better features, less regularization, train longer.
- For variance: more data, regularization, simpler model, ensembling, data augmentation, early stopping.

#### Modern nuance
Very large neural networks can fit training data perfectly and still generalize (double descent). The classical U-shaped curve is a guide, not a law, but the diagnostic habits still apply everywhere.

**Good enough to move on** when you can look at a pair of train and validation curves and prescribe the right next experiment.

Key concepts: Bias-variance decomposition, Learning curves, Validation curves, Regularization as variance control, Double descent.

Mini project: Plot learning curves for a depth-2 tree, a fully grown tree and a random forest on the Adult income dataset and write the diagnosis and recommended fix for each.

Self-check: Your learning curve shows training and validation scores converging at a low value. Will more data help? What would?

Resources:
- [scikit-learn: Validation and learning curves](https://scikit-learn.org/stable/modules/learning_curve.html) (scikit-learn)
- [Google ML Crash Course: Overfitting](https://developers.google.com/machine-learning/crash-course) (Google)

### Hyperparameter Tuning

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/machine-learning/hyperparameter-tuning

Grid, random and Bayesian search with tools like Optuna, plus how to tune efficiently without overfitting the validation set.

Hyperparameters are settings you choose rather than learn (tree depth, learning rate, regularization strength). Systematic tuning often gives a solid gain, but beyond a point it offers less than better data or features.

#### Methods
- **Grid search**: exhaustive, fine for two or three parameters.
- **Random search**: usually more efficient than grid, because only a few parameters matter much.
- **Bayesian optimization** (Optuna, scikit-optimize): builds a model of the score surface and samples promising regions.
- **Successive halving / Hyperband**: kill bad configurations early to save compute.

#### Practice
- Search learning rates and regularization on a **log scale**.
- Start from library defaults and published good ranges; tune the most important parameters first.
- Tune inside cross-validation with a pipeline, then evaluate the final choice on the untouched test set.
- Log every trial (value, parameters, time) so you can see which parameters matter.

#### Pitfalls
Running thousands of trials against one small validation split effectively trains on it. Watch for improvements smaller than fold-to-fold noise.

**Good enough to move on** when you can run an Optuna study on a gradient boosting model with cross-validation and explain the parameter importance plot.

Key concepts: Grid search, Random search, Bayesian optimization with Optuna, Successive halving, Log-scale search spaces.

Mini project: Tune a LightGBM model on the Kaggle House Prices data with both RandomizedSearchCV and an Optuna study of equal budget, and compare best scores and wall-clock time.

Self-check: Why does random search often beat grid search with the same number of trials?

Resources:
- [scikit-learn: Tuning hyperparameters](https://scikit-learn.org/stable/modules/grid_search.html) (scikit-learn)
- [Optuna documentation](https://optuna.readthedocs.io/en/stable/) (Optuna)

### Imbalanced Data

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/machine-learning/imbalanced-data

Handling rare positive classes with the right metrics, class weights, resampling and threshold tuning.

Fraud, churn, disease and defects are rare events. With 1% positives, a model that always says no is 99% accurate and completely useless. Imbalance is mostly an **evaluation and decision** problem, not a mysterious data defect.

#### Toolbox, roughly in order of what to try
- **Use the right metric**: PR AUC, recall at fixed precision, or cost-weighted metrics.
- **Tune the decision threshold** on validation data instead of using 0.5.
- **Class weights** (`class_weight='balanced'`, `scale_pos_weight` in XGBoost).
- **Resampling**: random undersampling of the majority, oversampling of the minority, or SMOTE variants via imbalanced-learn.
- **Collect more positive examples** when possible; nothing beats real data.

#### Pitfalls
- Resampling **before** splitting or outside the CV loop leaks synthetic copies into validation.
- Oversampling changes predicted probabilities; recalibrate if you need real probabilities.
- Stratify every split so each fold contains positives.

**Good enough to move on** when you can compare class weights, SMOTE and threshold tuning fairly within a pipeline and explain which you would deploy.

Key concepts: Metrics for rare classes, Threshold tuning, Class weights, Under- and oversampling, SMOTE with imbalanced-learn, Cost-sensitive evaluation.

Mini project: On the Kaggle Credit Card Fraud dataset, compare no treatment, class weights, SMOTE and threshold tuning inside stratified CV, reporting PR AUC and recall at 90% precision.

Self-check: Why must SMOTE be applied only to the training portion of each fold?

Resources:
- [imbalanced-learn user guide](https://imbalanced-learn.org/stable/user_guide.html) (imbalanced-learn)
- [scikit-learn: Tuning the decision threshold](https://scikit-learn.org/stable/modules/classification_threshold.html) (scikit-learn)

### scikit-learn Pipelines and Model Persistence

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/machine-learning/sklearn-pipelines

Composing preprocessing and models into a single leak-proof, tunable, saveable object ready for reuse and deployment.

A `Pipeline` chains transformers and a final estimator so that `fit` and `predict` run every step in the right order. It is the single best habit for avoiding leakage and for shipping models.

#### Building blocks
- `Pipeline` / `make_pipeline`: sequential steps.
- `ColumnTransformer`: different preprocessing per column group (numeric, categorical, text).
- `FunctionTransformer` and custom transformers (subclass `BaseEstimator`, `TransformerMixin`) for your own feature code.
- Parameter names like `model__max_depth` let you tune any step's settings in `GridSearchCV`.

#### Why it matters
- Preprocessing is refit inside every CV fold automatically.
- The same object transforms training data and live requests, so there is no training/serving skew from reimplemented preprocessing.
- One artifact to version and deploy.

#### Persistence
Save with `joblib.dump` or `skops`. Pickled models are tied to library versions, so record them, and never load pickles from untrusted sources because unpickling can execute code. For cross-language serving consider ONNX.

**Good enough to move on** when your whole modelling workflow is one pipeline that you tune with CV, save to disk, reload in a fresh process and use to predict on raw input rows.

Key concepts: Pipeline and make_pipeline, ColumnTransformer, Custom transformers, Tuning pipeline parameters, joblib and skops persistence, ONNX export.

Mini project: Package your best Telco Churn model as a single Pipeline with ColumnTransformer, tune it with GridSearchCV, save it with joblib, and write a small script that loads it and scores a CSV of raw customers.

Self-check: How does using a Pipeline prevent training/serving skew?

Resources:
- [scikit-learn: Pipelines and composite estimators](https://scikit-learn.org/stable/modules/compose.html) (scikit-learn)
- [scikit-learn: Model persistence](https://scikit-learn.org/stable/model_persistence.html) (scikit-learn)

## Finding Structure Without Labels

Clustering, dimensionality reduction and anomaly detection for exploring data, compressing it and finding the unusual.

### k-Means Clustering

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/machine-learning/k-means

Partitioning data into k groups around centroids, choosing k, and understanding where the method breaks down.

k-means alternates between assigning each point to its nearest centroid and moving each centroid to the mean of its points. It is fast, simple and the first clustering method to try.

#### Using it
- **Scale features first**; k-means uses Euclidean distance.
- Use `k-means++` initialization (the default) and several restarts (`n_init`).
- **Choosing k**: elbow plot of inertia, silhouette score, and above all whether clusters are useful and interpretable for the task.
- `MiniBatchKMeans` for large datasets.

#### Limitations
k-means assumes roughly spherical, similarly sized clusters and forces every point into a cluster, including outliers. It struggles with elongated or nested shapes. **Gaussian mixture models** generalize it with soft assignments and elliptical clusters.

#### Evaluating clusters
Without labels, evaluation is partly subjective. Profile each cluster (feature means, sizes), check stability across random seeds, and validate against a downstream use such as targeted marketing.

**Good enough to move on** when you can segment a dataset, justify k, and describe each cluster in plain language.

Key concepts: Lloyd's algorithm, k-means++ initialization, Elbow and silhouette, Cluster profiling, Gaussian mixture models, MiniBatchKMeans.

Mini project: Segment customers in the UCI Online Retail dataset using RFM (recency, frequency, monetary) features and k-means, then write a one-line persona for each segment.

Self-check: Why does k-means perform badly on two interleaved crescent-shaped clusters?

Resources:
- [scikit-learn: Clustering](https://scikit-learn.org/stable/modules/clustering.html) (scikit-learn)
- [scikit-learn: Gaussian mixture models](https://scikit-learn.org/stable/modules/mixture.html) (scikit-learn)

### Hierarchical and Density-Based Clustering

recommended · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/machine-learning/hierarchical-and-density-clustering

Agglomerative clustering with dendrograms, and DBSCAN / HDBSCAN for arbitrary shapes and automatic noise detection.

When clusters are not round blobs, or you do not know how many there are, other families often work better than k-means.

#### Hierarchical (agglomerative) clustering
- Start with every point as its own cluster and repeatedly merge the closest pair.
- **Linkage** decides what closest means: single, complete, average or Ward (minimizes variance, most k-means-like).
- A **dendrogram** shows the full merge tree; cut it at a height to choose the number of clusters.
- Quadratic memory cost limits it to tens of thousands of points.

#### DBSCAN and HDBSCAN
- Clusters are dense regions separated by sparse ones; points in sparse areas are labelled **noise**.
- DBSCAN needs `eps` (neighbourhood radius) and `min_samples`. A k-distance plot helps choose eps.
- **HDBSCAN** removes the need for a single eps and handles varying density; often the better default.
- Finds arbitrary shapes and does not require k.

#### Tip
Clustering high-dimensional data directly is hard. Reduce dimensions first (PCA or UMAP), then cluster.

**Good enough to move on** when you can pick between k-means, agglomerative and HDBSCAN for a dataset and explain the choice.

Key concepts: Agglomerative clustering, Linkage criteria, Dendrograms, DBSCAN, HDBSCAN.

Mini project: Cluster GPS points of a public city dataset (for example NYC taxi pickup coordinates) with DBSCAN or HDBSCAN to find hotspots, and compare the result with k-means on a map scatter plot.

Self-check: What does DBSCAN do with a point that is not within eps of enough neighbours, and why is that useful?

Resources:
- [scikit-learn: Clustering](https://scikit-learn.org/stable/modules/clustering.html) (scikit-learn)
- [HDBSCAN documentation](https://hdbscan.readthedocs.io/en/latest/) (hdbscan)

### Principal Component Analysis

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/machine-learning/pca

Projecting data onto the directions of greatest variance for compression, denoising, visualization and faster models.

PCA finds orthogonal directions (principal components) that capture the most variance, then lets you keep only the first few. It is linear algebra in action: eigenvectors of the covariance matrix, computed in practice with SVD.

#### Uses
- **Visualization**: plot the first two components to see structure.
- **Compression and speed**: fewer features for downstream models.
- **Denoising**: discard low-variance components that are mostly noise.
- **Decorrelation** of features before linear models.

#### How to apply
- **Standardize features first** unless they share units; otherwise the largest-scale feature dominates.
- Choose the number of components from the **explained variance ratio** (for example keep 95%).
- Fit PCA on training data only, inside a pipeline.

#### Limitations
Components are linear combinations and can be hard to interpret. PCA captures variance, which is not necessarily what predicts your target. Nonlinear structure needs other tools (kernel PCA, t-SNE, UMAP, autoencoders).

**Good enough to move on** when you can implement PCA from SVD in NumPy, match scikit-learn's result, and choose components from a cumulative variance plot.

Key concepts: Variance and covariance, PCA via SVD, Explained variance ratio, PCA in pipelines, Kernel and incremental PCA.

Mini project: Apply PCA to the Olivetti faces or MNIST digits, visualize the top components as images, and plot classifier accuracy against the number of components kept.

Self-check: Why can PCA throw away a low-variance feature that is actually the most predictive of the target?

Resources:
- [scikit-learn: Decomposing signals in components](https://scikit-learn.org/stable/modules/decomposition.html) (scikit-learn)
- [Mathematics for Machine Learning (dimensionality reduction chapter)](https://mml-book.github.io/) (MML)

### t-SNE and UMAP for Visualization

recommended · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/machine-learning/tsne-umap

Nonlinear embeddings that reveal clusters and manifolds in 2D, and how to avoid over-reading their pictures.

t-SNE and UMAP map high-dimensional points (embeddings, images, gene expression) into 2D while trying to keep neighbours close. They produce striking plots that often reveal structure PCA misses.

#### Differences
- **t-SNE** focuses on local neighbourhoods; `perplexity` roughly sets neighbourhood size. Slow on large data and has no simple transform for new points.
- **UMAP** is faster, tends to preserve more global structure and can transform new data. `n_neighbors` and `min_dist` are the main knobs.

#### Reading the plots honestly
- **Cluster sizes and distances between clusters are not meaningful** in t-SNE plots.
- Different random seeds and hyperparameters give different pictures; try several.
- Apparent clusters can appear in pure noise with poor settings.
- Common practice: PCA to around 50 dimensions first, then t-SNE or UMAP.

#### Uses
Inspecting learned embeddings, spotting mislabelled examples, and exploring data before clustering. Use them as exploration tools, not as features for final models without careful validation.

**Good enough to move on** when you can produce t-SNE and UMAP plots of the same data, vary their hyperparameters and explain what conclusions are and are not justified.

Key concepts: t-SNE and perplexity, UMAP parameters, Interpretation caveats, PCA preprocessing.

Mini project: Embed Fashion-MNIST with PCA, t-SNE and UMAP, color by label, and write three observations plus one conclusion you deliberately refuse to draw.

Self-check: In a t-SNE plot, one cluster is twice as large and far from the others. What can you actually conclude?

Resources:
- [How to Use t-SNE Effectively](https://distill.pub/2016/misread-tsne/) (Distill)
- [UMAP documentation](https://umap-learn.readthedocs.io/en/latest/) (umap-learn)
- [scikit-learn: Manifold learning](https://scikit-learn.org/stable/modules/manifold.html) (scikit-learn)

### Anomaly and Outlier Detection

recommended · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/machine-learning/anomaly-detection

Finding rare, unusual observations with statistical rules, Isolation Forest, LOF and one-class methods when labels are scarce.

Anomaly detection flags data points that do not fit the usual pattern: fraudulent transactions, failing machines, intrusions, data-quality errors. Labels are usually rare or missing, so methods are largely unsupervised.

#### Methods
- **Statistical rules**: z-scores, IQR fences, rolling thresholds for time series. Simple and often enough.
- **Isolation Forest**: anomalies are isolated in fewer random splits; fast, scales well, a strong default.
- **Local Outlier Factor**: compares local density with neighbours; good for varying densities.
- **One-class SVM**: learns a boundary around normal data; sensitive to parameters.
- **Reconstruction error** from PCA or autoencoders: high error suggests an anomaly.

#### Practical concerns
- The `contamination` parameter sets how many points get flagged; tie it to review capacity.
- Evaluate with any labels you do have (precision at top k) or with human review of the top flagged cases.
- If you gather enough labelled anomalies, a supervised classifier usually beats unsupervised detection.

**Good enough to move on** when you can build an anomaly detector, rank cases by score and evaluate precision at k against held-out labels.

Key concepts: Statistical thresholds, Isolation Forest, Local Outlier Factor, One-class SVM, Reconstruction-based detection, Precision at k evaluation.

Mini project: Train Isolation Forest and LOF on the Kaggle Credit Card Fraud data without using labels, then use the labels only to compute precision at the top 500 flagged transactions.

Self-check: When would you switch from an unsupervised anomaly detector to a supervised classifier?

Resources:
- [scikit-learn: Novelty and outlier detection](https://scikit-learn.org/stable/modules/outlier_detection.html) (scikit-learn)
- [PyOD documentation](https://pyod.readthedocs.io/en/latest/) (PyOD)

## Neural Network Fundamentals

How neural networks compute, learn through backpropagation and are trained reliably, independent of any framework.

### Perceptrons and Multilayer Networks

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/machine-learning/neural-networks-basics

From a single neuron to stacked layers: weights, biases, forward passes and why depth plus nonlinearity makes networks expressive.

A neuron computes a weighted sum of its inputs plus a bias, then applies a nonlinear activation. A **multilayer perceptron (MLP)** stacks layers of neurons so each layer transforms the previous one's output.

#### Core ideas
- **The perceptron** is a linear classifier; logistic regression is essentially a single neuron with a sigmoid.
- **Layers as matrix multiplies**: `h = activation(W @ x + b)`. A batch of inputs is a matrix, so a layer is one matrix product.
- **Why nonlinearity**: without it, stacked linear layers collapse into one linear layer.
- **Universal approximation**: a wide enough network can approximate any function, but depth makes learning efficient.
- **Representation learning**: hidden layers learn features automatically instead of you engineering them.

#### When neural networks win
Unstructured data (images, text, audio) and very large datasets. On small or medium tabular data, gradient boosting still usually wins.

**Good enough to move on** when you can implement the forward pass of a two-layer MLP in NumPy and explain every shape along the way.

Key concepts: Perceptron, Neurons, weights and biases, Layers as matrix multiplication, Why nonlinearity matters, Universal approximation.

Mini project: Build a two-layer MLP forward pass in NumPy and experiment in TensorFlow Playground to find the smallest network that separates the spiral dataset.

Self-check: Why does a network of ten linear layers with no activations have the same power as a single linear layer?

Resources:
- [Neural Networks series](https://www.3blue1brown.com/topics/neural-networks) (3Blue1Brown)
- [TensorFlow Playground](https://playground.tensorflow.org/) (TensorFlow)
- [Dive into Deep Learning](https://d2l.ai/) (d2l.ai)

### Backpropagation and Autograd

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/machine-learning/backpropagation

How gradients flow backward through a computation graph, and how automatic differentiation libraries compute them for you.

Backpropagation computes the gradient of the loss with respect to every weight by applying the chain rule from the output back to the input, reusing intermediate results so the cost is similar to one forward pass.

#### Understand it by building it
- Represent the computation as a graph of simple operations (add, multiply, tanh).
- Each node knows its local derivative; multiply local derivatives backward along the graph.
- Gradients from multiple paths into a node **add up**.
- Implementing a tiny scalar autograd engine (in the style of micrograd) makes this click permanently.

#### Autograd in frameworks
PyTorch, TensorFlow and JAX record operations and compute gradients automatically: `loss.backward()` in PyTorch, `GradientTape` in TensorFlow, `jax.grad` in JAX. You still need the mental model to debug.

#### Problems it explains
- **Vanishing gradients**: repeated multiplication by small derivatives (sigmoid saturation, deep stacks) shrinks gradients toward zero.
- **Exploding gradients**: the opposite, common in RNNs; fixed with gradient clipping.
- Why initialization, normalization and residual connections matter.

**Good enough to move on** when you can build a small autograd engine, train an MLP with it, and verify its gradients against PyTorch.

Key concepts: Computation graphs, Chain rule backward pass, Gradient accumulation across paths, Automatic differentiation, Vanishing and exploding gradients, Gradient clipping.

Mini project: Implement a scalar autograd engine with add, multiply, tanh and backward(), train a small MLP on make_moons with it, and compare gradients to PyTorch on the same inputs.

Self-check: Why do gradients from two different paths into the same node get summed rather than averaged or overwritten?

Resources:
- [Neural Networks: Zero to Hero (micrograd lecture)](https://karpathy.ai/zero-to-hero.html) (Andrej Karpathy)
- [CS231n: Backpropagation, intuitions](https://cs231n.github.io/optimization-2/) (Stanford)
- [Neural Networks series (backpropagation chapters)](https://www.3blue1brown.com/topics/neural-networks) (3Blue1Brown)

### Activation and Loss Functions

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/machine-learning/activations-and-losses

Picking activations for hidden and output layers and matching the loss function to the prediction task.

Activations give networks nonlinearity; the output activation and loss must match the task. Mismatches (for example softmax plus MSE for classification) train poorly or not at all.

#### Hidden activations
- **ReLU**: simple, fast, the historical default. Can produce dead units.
- **Leaky ReLU / ELU**: small slope for negatives to avoid dead units.
- **GELU / SiLU (Swish)**: smooth variants used in transformers and modern CNNs.
- **Sigmoid and tanh**: saturate and cause vanishing gradients in deep stacks; still used for gates in LSTMs.

#### Output layer plus loss
- **Regression**: linear output + MSE, MAE or Huber loss.
- **Binary classification**: one logit + binary cross-entropy (use the with-logits version for numerical stability).
- **Multiclass**: logits + softmax cross-entropy. In PyTorch, `nn.CrossEntropyLoss` expects raw logits, not probabilities.
- **Multi-label**: independent sigmoid per label + BCE.
- Specialized losses: focal loss for imbalance, contrastive and triplet losses for embeddings.

**Good enough to move on** when, given any prediction target, you can choose the output layer and loss and explain why applying softmax before `CrossEntropyLoss` is a bug.

Key concepts: ReLU and variants, GELU and SiLU, Sigmoid, tanh and saturation, Cross-entropy with logits, Regression losses, Focal and contrastive losses.

Mini project: Train the same small MLP on Fashion-MNIST with sigmoid, tanh, ReLU and GELU activations and plot training loss curves side by side.

Self-check: Which output activation and loss would you use for tagging an image with any of 20 non-exclusive labels?

Resources:
- [Dive into Deep Learning: Multilayer perceptrons](https://d2l.ai/chapter_multilayer-perceptrons/index.html) (d2l.ai)
- [PyTorch torch.nn reference](https://pytorch.org/docs/stable/nn.html) (PyTorch)

### Optimizers and Learning Rate Schedules

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/machine-learning/deep-learning-optimizers

SGD with momentum, Adam and AdamW, warmup and decay schedules, and how to find a learning rate that works.

The optimizer and learning rate decide whether a network trains fast, slowly or not at all. Most practitioners use a small set of well-understood defaults.

#### Optimizers
- **SGD with momentum**: accumulates a velocity to smooth noisy gradients; still strong for vision with good schedules.
- **RMSProp**: per-parameter step sizes from recent gradient magnitudes.
- **Adam**: momentum plus adaptive scaling; robust default.
- **AdamW**: Adam with decoupled weight decay; the standard for transformers.

#### Learning rate
- The single most important hyperparameter. Typical Adam starting points are around 1e-3 for small nets and 1e-4 or lower for fine-tuning large pretrained models.
- **LR range test**: increase the rate exponentially over a short run and pick a value just before the loss blows up.
- **Schedules**: step decay, cosine annealing, one-cycle, and **linear warmup** for large models.

#### Batch size
Larger batches give smoother gradients and better hardware utilization but may need a higher learning rate and can generalize slightly worse. Use gradient accumulation to simulate large batches on small GPUs.

**Good enough to move on** when you can run an LR range test, pick an optimizer and schedule, and justify the choice from loss curves.

Key concepts: SGD with momentum, Adam and AdamW, Learning rate range test, Cosine, step and one-cycle schedules, Warmup, Batch size and gradient accumulation.

Mini project: Train a small CNN on CIFAR-10 with SGD+momentum, Adam and AdamW, each with and without a cosine schedule, and compare validation accuracy after a fixed epoch budget.

Self-check: What is the practical difference between L2 regularization in Adam and decoupled weight decay in AdamW?

Resources:
- [Dive into Deep Learning: Optimization Algorithms](https://d2l.ai/chapter_optimization/index.html) (d2l.ai)
- [PyTorch torch.optim](https://pytorch.org/docs/stable/optim.html) (PyTorch)

### Regularization, Initialization and Normalization

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/machine-learning/regularization-and-normalization

Dropout, weight decay, early stopping, data augmentation, weight initialization and batch/layer normalization for stable, generalizing networks.

Deep networks have enough capacity to memorize training data. Regularization pushes them toward solutions that generalize, while initialization and normalization keep training numerically stable.

#### Regularization
- **Weight decay**: penalizes large weights.
- **Dropout**: randomly zeroes activations during training; disabled at evaluation time (`model.eval()`).
- **Early stopping**: stop when validation loss stops improving; keep the best checkpoint.
- **Data augmentation**: often the most effective regularizer for images, audio and text.
- **Label smoothing**: softens one-hot targets to reduce overconfidence.

#### Initialization
Random weights must be scaled so activations neither vanish nor explode through layers: **Xavier/Glorot** for tanh-like activations, **He/Kaiming** for ReLU. Frameworks choose sensible defaults, but know why.

#### Normalization
- **Batch normalization**: normalizes activations using batch statistics; speeds up CNN training; behaves differently in train and eval mode, and struggles with tiny batches.
- **Layer normalization**: normalizes per example; the standard in transformers and RNNs.
- **Residual connections** (preview): skip paths that let gradients flow through very deep networks.

**Good enough to move on** when you can show on a validation curve how dropout, weight decay and augmentation each reduce overfitting, and explain the train/eval behaviour of batch norm.

Key concepts: Weight decay, Dropout, Early stopping and checkpoints, Xavier and He initialization, Batch normalization, Layer normalization, Label smoothing.

Mini project: Deliberately overfit an MLP on a 5,000-image subset of Fashion-MNIST, then add weight decay, dropout, batch norm and early stopping one at a time and chart the validation accuracy after each change.

Self-check: What goes wrong if you forget to call model.eval() before evaluating a network with dropout and batch norm?

Resources:
- [Deep Learning (regularization chapter)](https://www.deeplearningbook.org/) (Goodfellow, Bengio, Courville)
- [Dive into Deep Learning](https://d2l.ai/) (d2l.ai)

### Debugging and Running Training Experiments

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/machine-learning/training-debugging

A disciplined recipe for getting networks to train: overfit a batch first, sanity-check data, read loss curves and change one thing at a time.

Neural network bugs rarely crash; they silently produce a model that is a bit worse. A methodical process saves days.

#### A practical recipe
1. **Look at the data** after every transform: plot images with labels, decode tokenized text.
2. **Establish baselines**: a trivial model and a simple non-neural model.
3. **Overfit one small batch**. If the loss cannot reach near zero on 32 examples, something is broken.
4. **Check initial loss**: for 10 balanced classes it should be about ln(10) = 2.3.
5. Scale up gradually, adding regularization only once you can overfit.
6. **Change one thing at a time** and log every run.

#### Common bugs
- Labels shuffled independently of inputs.
- Forgetting `optimizer.zero_grad()` so gradients accumulate.
- Softmax applied twice, or wrong loss for the output format.
- Train mode left on during evaluation, or data augmentation applied to validation data.
- Normalization statistics that differ between training and inference.

#### Reading curves
Train loss not decreasing: learning rate, bug or capacity. Validation loss rising while train falls: overfitting. Spiky loss: learning rate too high or bad batches.

**Good enough to move on** when you default to the overfit-one-batch test and can diagnose a failed run from its curves.

Key concepts: Visualizing inputs after transforms, Overfit a single batch, Initial loss sanity check, Reading loss curves, Common training bugs, Ablation discipline.

Mini project: Take a working training script, have a friend (or yourself, blind) inject three bugs from the common-bugs list, then find each using only the debugging recipe and write down which check caught it.

Self-check: Your 10-class classifier starts with a loss of 15 instead of about 2.3. What does that suggest?

Resources:
- [A Recipe for Training Neural Networks](https://karpathy.github.io/2019/04/25/recipe/) (Andrej Karpathy)
- [Google Deep Learning Tuning Playbook](https://github.com/google-research/tuning_playbook) (Google Research)

## Deep Learning Frameworks and Hardware

Pick one framework to build and train real models, and learn to use GPUs efficiently.

### PyTorch

recommended · intermediate · about 20 h · https://www.internhack.in/roadmaps/tracks/machine-learning/pytorch

Tensors, autograd, nn.Module, Dataset/DataLoader and the explicit training loop, the most widely used framework in research and much of industry.

PyTorch is the recommended framework: it dominates research, most new models and papers ship PyTorch code, and Hugging Face is built around it. Its Pythonic, eager style makes debugging straightforward.

#### What to learn
- **Tensors**: NumPy-like API plus `device` (`cpu`, `cuda`, `mps`) and `dtype`.
- **Autograd**: `requires_grad`, `loss.backward()`, `torch.no_grad()` for inference.
- **nn.Module**: define layers in `__init__`, computation in `forward`; `parameters()`, `state_dict()`.
- **Data**: `Dataset` (indexing one example) and `DataLoader` (batching, shuffling, workers).
- **The training loop**: forward, loss, `zero_grad`, `backward`, `step`; separate evaluation loop with `model.eval()`.
- **Saving**: save `state_dict`, not the whole model object.
- **torch.compile** for speedups once things work.

#### Higher-level helpers
PyTorch Lightning, Hugging Face Accelerate or fastai remove boilerplate. Learn the raw loop first so you know what they hide.

**Good enough to move on** when you can write a complete training and evaluation loop from memory, including checkpointing and running on GPU.

Key concepts: Tensors and devices, Autograd, nn.Module, Dataset and DataLoader, Training and evaluation loops, Saving state_dict checkpoints, torch.compile, PyTorch Lightning or Accelerate.

Mini project: Write a PyTorch training script for Fashion-MNIST with a custom Dataset, an MLP and a CNN, validation each epoch, best-checkpoint saving and a command-line flag for the device.

Self-check: Why do you call optimizer.zero_grad() on every iteration, and what happens if you forget?

Resources:
- [PyTorch tutorials](https://pytorch.org/tutorials/) (PyTorch)
- [PyTorch documentation](https://pytorch.org/docs/stable/index.html) (PyTorch)
- [Practical Deep Learning for Coders](https://course.fast.ai/) (fast.ai)

### TensorFlow and Keras

alternative · intermediate · about 18 h · https://www.internhack.in/roadmaps/tracks/machine-learning/tensorflow-keras

The Keras high-level API for fast model building with fit/evaluate, and the TensorFlow ecosystem for mobile and production deployment.

Keras offers a concise, high-level way to build models: stack layers, `compile` with an optimizer and loss, call `fit`. It is a valid alternative if your team or target platform uses it. Keras 3 can also run on PyTorch or JAX backends.

#### What to learn
- **Sequential and Functional APIs** for building models; subclassing for custom logic.
- `compile`, `fit`, `evaluate`, `predict`, and **callbacks** (early stopping, checkpoints, learning rate schedules).
- **tf.data** pipelines for efficient input loading.
- **GradientTape** for custom training loops.
- Saving in the `.keras` format; exporting for serving.

#### Ecosystem
TensorFlow Lite (LiteRT) for mobile and edge devices, TensorFlow Serving and TFX for production pipelines, and TensorFlow.js in the browser.

#### Trade-offs
Very quick to get started and strong deployment tooling, but most new research code and Hugging Face examples are PyTorch first.

**Good enough to move on** when you can build, train with callbacks and save a Keras model, and write one custom training step with GradientTape.

Key concepts: Sequential and Functional APIs, compile and fit, Callbacks, tf.data pipelines, GradientTape custom loops, TensorFlow Lite deployment.

Mini project: Build a Keras image classifier for Fashion-MNIST with a tf.data pipeline, early stopping and checkpoint callbacks, then convert it to TensorFlow Lite and check the file size and accuracy.

Self-check: What does model.compile() configure, and why must it happen before fit()?

Resources:
- [TensorFlow tutorials](https://www.tensorflow.org/tutorials) (TensorFlow)
- [Keras developer guides](https://keras.io/guides/) (Keras)

### JAX

alternative · advanced · about 18 h · https://www.internhack.in/roadmaps/tracks/machine-learning/jax

Composable function transformations (grad, jit, vmap) over NumPy-style code, popular for research and large-scale training on TPUs and GPUs.

JAX looks like NumPy but lets you transform functions: take gradients, compile them with XLA, vectorize them and parallelize them across devices. It favours a functional style where model parameters are explicit data rather than hidden object state.

#### Core transformations
- `jax.grad`: gradient of a scalar function.
- `jax.jit`: compile a function for big speedups.
- `jax.vmap`: automatic batching of a per-example function.
- `jax.pmap` / sharding APIs: multi-device parallelism.

#### Things that surprise newcomers
- Arrays are **immutable**; use `x.at[i].set(v)` instead of in-place assignment.
- **Explicit random keys** (`jax.random.PRNGKey`, `split`) instead of global seeds.
- Python control flow inside jitted functions needs `jax.lax.cond` / `scan` when it depends on array values.

#### Ecosystem
Flax (neural network layers), Optax (optimizers) and Orbax (checkpointing). Choose JAX if you work on TPUs, in research groups that use it, or need its transformations; otherwise PyTorch is the more common path.

**Good enough to move on** when you can train an MLP with Flax and Optax and explain what jit, grad and vmap each do.

Key concepts: grad, jit and XLA, vmap, PRNG keys, Flax, Optax, Multi-device sharding.

Mini project: Implement logistic regression in pure JAX using grad, jit and vmap for per-example gradients, then rebuild a Fashion-MNIST MLP with Flax and Optax.

Self-check: Why does JAX require explicit random keys instead of a global random seed?

Resources:
- [JAX documentation](https://docs.jax.dev/en/latest/) (JAX)
- [JAX on GitHub](https://github.com/jax-ml/jax) (GitHub)
- [Flax documentation](https://flax.readthedocs.io/en/latest/) (Flax)

### GPUs and Efficient Training

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/machine-learning/gpu-training

Using GPUs well: device placement, data loading bottlenecks, mixed precision, memory limits and a first look at multi-GPU training.

Deep learning is compute bound, and GPUs speed up the matrix math by one to two orders of magnitude. Using them well is a practical skill employers expect.

#### Essentials
- **Access**: Google Colab and Kaggle notebooks offer free GPUs; cloud GPU rentals for bigger jobs.
- **Device placement**: move model and each batch to the same device; avoid needless CPU-GPU copies and `.item()` calls inside hot loops.
- **Monitor utilization** with `nvidia-smi`. Low utilization usually means the **data loader** is the bottleneck: increase `num_workers`, use `pin_memory`, preprocess ahead of time.
- **Mixed precision** (fp16 or bf16 with autocast) roughly halves memory and speeds up training on modern GPUs.
- **Out of memory fixes**: smaller batch plus gradient accumulation, mixed precision, gradient checkpointing.

#### Scaling out (optional for now)
Distributed Data Parallel (DDP) replicates the model on several GPUs; FSDP and DeepSpeed shard large models. You mostly need these for large model work.

#### Reproducibility
Set seeds for Python, NumPy and the framework, and record GPU type and library versions; exact bitwise reproducibility on GPUs is not guaranteed.

**Good enough to move on** when you can profile a slow training run, identify whether data loading or compute is the bottleneck, and enable mixed precision.

Key concepts: Free GPU platforms, Device placement, Data loading bottlenecks, Mixed precision training, Handling out-of-memory errors, DDP and FSDP.

Mini project: Benchmark CIFAR-10 CNN training on a free Colab or Kaggle GPU with different num_workers settings and with and without mixed precision, and report images per second and peak memory.

Self-check: nvidia-smi shows your GPU at 25% utilization during training. What is the most likely cause and how would you confirm it?

Resources:
- [PyTorch automatic mixed precision](https://pytorch.org/docs/stable/amp.html) (PyTorch)
- [PyTorch tutorials (performance and distributed)](https://pytorch.org/tutorials/) (PyTorch)

## Computer Vision

Teach networks to see: convolutions, data augmentation, reusing pretrained backbones, and the step up to detection and segmentation.

### Convolutional Neural Networks

core · intermediate · about 14 h · https://www.internhack.in/roadmaps/tracks/machine-learning/cnns

How convolutions, pooling and stacked feature maps let a network learn edges, textures and objects with far fewer parameters than a dense layer.

A dense layer treats each pixel as an unrelated input, which wastes parameters and ignores the fact that nearby pixels belong together. A **convolution** slides a small learned filter across the image, so the same weights detect a pattern wherever it appears. This built-in assumption (translation equivariance) is why CNNs learn vision tasks from modest data.

#### Building blocks
- **Kernel size, stride and padding** decide the output shape. Practise computing it by hand: `out = (in + 2*pad - kernel) / stride + 1`.
- **Channels**: each filter produces one feature map; a layer with 64 filters outputs 64 channels.
- **Pooling** (max or average) and strided convolutions shrink spatial size so later layers see a wider **receptive field**.
- **Batch normalization and ReLU** after each convolution are the standard recipe.
- **Global average pooling** plus a linear layer turns feature maps into class scores.

#### Landmark architectures
LeNet showed the idea, AlexNet and VGG proved depth helps, and **ResNet** introduced skip connections that make very deep networks trainable. Today you will also meet EfficientNet, ConvNeXt and Vision Transformers (ViT), which split an image into patches and apply attention. You rarely design an architecture from scratch; you need to read one and know which knobs matter.

#### Inspecting what was learned
Visualize first-layer filters and feature maps, and use saliency methods such as Grad-CAM to check that the model looks at the object and not the background.

**Good enough to move on** when you can build a small CNN, predict every tensor shape through it, and explain why a residual connection helps optimization.

Key concepts: Convolution, stride and padding, Channels and feature maps, Pooling and receptive field, ResNet and skip connections, Global average pooling, Vision Transformers (ViT), Grad-CAM and saliency maps.

Mini project: Train a small CNN on CIFAR-10, then add residual blocks and batch normalization and compare accuracy and training curves. Plot Grad-CAM heatmaps for five correct and five wrong predictions.

Self-check: A 32x32x3 image passes through a 3x3 convolution with 16 filters, stride 1 and padding 1, then 2x2 max pooling. What is the output shape and how many learnable weights did the convolution have?

Resources:
- [CS231n: Deep Learning for Computer Vision notes](https://cs231n.github.io/) (Stanford)
- [Dive into Deep Learning](https://d2l.ai/) (d2l.ai)
- [PyTorch tutorials](https://pytorch.org/tutorials/) (PyTorch)

### Image Data Pipelines and Augmentation

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/machine-learning/image-data-pipelines

Loading, resizing and normalizing images efficiently, and using augmentation to multiply your effective dataset without collecting more labels.

In vision projects the data pipeline often matters more than the architecture. Slow loading starves the GPU, and inconsistent preprocessing between training and serving silently ruins accuracy.

#### The pipeline
- **Decode and resize** to a fixed size; decide between cropping, padding or stretching.
- **Normalize** with the mean and standard deviation the pretrained model expects.
- **Folder layouts** such as `ImageFolder` (one directory per class) versus CSV manifests of paths and labels.
- **Parallel loading** with multiple workers and pinned memory; cache decoded images for small datasets.

#### Augmentation
Augmentations are label-preserving transformations applied randomly at training time only.
- **Geometric**: random crops, flips, small rotations and scale changes.
- **Photometric**: brightness, contrast, colour jitter, blur.
- **Mixing methods**: Mixup and CutMix blend images and labels and act as strong regularizers.
- **Policy search**: RandAugment and TrivialAugment pick transformations automatically.

Always ask whether an augmentation keeps the label true. Horizontal flips are fine for cats but wrong for digit recognition or reading text. For detection and segmentation, boxes and masks must be transformed together with the image; libraries such as torchvision transforms v2 and Albumentations handle that.

#### Checking your work
Display a grid of augmented batches before training. Most pipeline bugs (wrong channel order, labels shuffled separately, over-strong augmentation) are obvious when you look.

**Good enough to move on** when your GPU utilization stays high during training and you can justify every augmentation you apply.

Key concepts: Resizing and normalization, ImageFolder and manifests, Geometric augmentation, Photometric augmentation, Mixup and CutMix, RandAugment, Albumentations.

Mini project: Take 10 percent of a small image dataset and train the same CNN with no augmentation, basic flips and crops, and RandAugment plus Mixup. Report validation accuracy and plot a grid of augmented samples for each setting.

Self-check: Why should augmentation be applied to the training set only, and give one augmentation that would corrupt labels for a specific task.

Resources:
- [torchvision transforms](https://pytorch.org/vision/stable/transforms.html) (PyTorch)
- [Albumentations documentation](https://albumentations.ai/docs/) (Albumentations)

### Transfer Learning and Fine-Tuning

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/machine-learning/transfer-learning-vision

Start from a model pretrained on millions of images and adapt it to your task with a few hundred labelled examples.

Training a vision model from scratch is rarely the right call. A backbone pretrained on ImageNet or a large web dataset has already learned general features (edges, textures, parts), and you only need to teach it your classes. This is the single most practical technique in applied deep learning.

#### Two strategies
- **Feature extraction**: freeze the backbone, replace the final layer, and train only the new head. Fast, works with very little data.
- **Fine-tuning**: unfreeze some or all layers and continue training with a small learning rate. Better accuracy when you have more data or your images look different from the pretraining set (medical scans, satellite images).

#### Practical recipe
1. Load a pretrained model from torchvision, `timm` or the Hugging Face Hub.
2. Apply the same preprocessing it was trained with.
3. Train the new head for a few epochs with the backbone frozen.
4. Unfreeze and fine-tune with a lower learning rate, often using **discriminative learning rates** (smaller for early layers).
5. Use a learning rate finder and a one-cycle or cosine schedule.

#### Foundation models
Models such as CLIP and DINOv2 produce embeddings good enough for **zero-shot** classification or a simple linear probe. Try them as a baseline before fine-tuning anything.

#### Pitfalls
Forgetting to switch batch normalization layers correctly between train and eval mode, using a learning rate so high it destroys pretrained features, and leakage when near-duplicate images land in both train and test.

**Good enough to move on** when you can fine-tune a pretrained backbone on a custom dataset of a few hundred images and beat a from-scratch model by a clear margin.

Key concepts: Pretrained backbones, Feature extraction with frozen layers, Full fine-tuning, Discriminative learning rates, timm model library, CLIP zero-shot classification, Linear probing embeddings.

Mini project: Collect about 300 photos of 3 to 5 categories you care about, fine-tune a pretrained ResNet or ConvNeXt, compare it with CLIP zero-shot, and publish the model with a small Gradio demo.

Self-check: When would you freeze the whole backbone versus fine-tune every layer, and why is a lower learning rate used when fine-tuning?

Resources:
- [Practical Deep Learning for Coders](https://course.fast.ai/) (fast.ai)
- [PyTorch tutorials](https://pytorch.org/tutorials/) (PyTorch)
- [timm documentation](https://huggingface.co/docs/timm/index) (Hugging Face)

### Object Detection

optional · advanced · about 10 h · https://www.internhack.in/roadmaps/tracks/machine-learning/object-detection

Locate and classify multiple objects per image with bounding boxes, using detectors such as YOLO and Faster R-CNN.

Classification answers what is in the image; detection answers what and where, for every object. It powers retail shelf analysis, traffic monitoring, document layout parsing and much more.

#### Core concepts
- **Bounding boxes** in formats like `xyxy`, `xywh` or normalized YOLO format. Mixing formats is the most common bug.
- **Intersection over Union (IoU)** measures box overlap and decides whether a prediction counts as correct.
- **Anchors and anchor-free heads**: older detectors predict offsets from preset boxes; newer ones predict box centres directly.
- **Non-maximum suppression (NMS)** removes duplicate boxes around the same object.
- **mAP** (mean average precision, often at IoU 0.5 and averaged over 0.5 to 0.95) is the standard metric.

#### Model families
- **Two-stage** (Faster R-CNN): propose regions, then classify them. Accurate, slower.
- **One-stage** (YOLO family, RetinaNet, SSD): predict boxes in a single pass. The usual choice for real time.
- **Transformer based** (DETR and successors) and **open-vocabulary** detectors that find objects from a text prompt.

#### Practical workflow
Label data in a tool such as CVAT or Label Studio, export to COCO or YOLO format, fine-tune a pretrained detector, and inspect false positives and misses per class. Small objects and class imbalance are the typical weak spots.

**Good enough to move on** when you can fine-tune a detector on a custom dataset, compute mAP, and explain what NMS does.

Key concepts: Bounding box formats, IoU, Non-maximum suppression, mAP evaluation, YOLO one-stage detectors, Faster R-CNN, COCO dataset format, Open-vocabulary detection.

Mini project: Label 150 images of two object types in Label Studio or CVAT, fine-tune a small YOLO model, report mAP@0.5, and write up the three most common failure patterns you see.

Self-check: Two predicted boxes overlap the same object with IoU 0.8 and confidences 0.9 and 0.6. What does NMS do with them, and how would a lower IoU threshold change the result?

Resources:
- [Ultralytics YOLO documentation](https://docs.ultralytics.com/) (Ultralytics)
- [torchvision models](https://pytorch.org/vision/stable/models.html) (PyTorch)
- [CS231n: Deep Learning for Computer Vision notes](https://cs231n.github.io/) (Stanford)

### Image Segmentation

optional · advanced · about 10 h · https://www.internhack.in/roadmaps/tracks/machine-learning/image-segmentation

Classify every pixel: semantic, instance and panoptic segmentation with encoder-decoder models like U-Net and promptable models like SAM.

Segmentation produces a label for every pixel instead of a box. It is essential in medical imaging, autonomous driving, satellite analysis and photo editing tools.

#### Flavours
- **Semantic segmentation**: each pixel gets a class (road, car, sky), but two cars share one label.
- **Instance segmentation**: separate masks for each object (car 1, car 2), as in Mask R-CNN.
- **Panoptic segmentation**: combines both for a complete scene description.

#### Architectures
- **U-Net**: an encoder downsamples to capture context, a decoder upsamples back to full resolution, and **skip connections** carry fine spatial detail across. Still the default in medical imaging.
- **DeepLab** uses dilated (atrous) convolutions to widen the receptive field without losing resolution.
- **Segment Anything (SAM)** and its successors segment any object from a click or box prompt and are excellent for speeding up labelling.

#### Losses and metrics
Pixel-wise cross-entropy is the baseline. **Dice loss** and focal loss help when the foreground is tiny compared to the background. Evaluate with **IoU (Jaccard)** and the **Dice coefficient** per class, not plain pixel accuracy, which looks great when a model predicts background everywhere.

#### Practical notes
Masks must receive the same geometric augmentations as images, but use nearest-neighbour resizing so labels stay integers. Libraries such as `segmentation_models_pytorch` give you pretrained encoders plugged into U-Net style decoders.

**Good enough to move on** when you can train a U-Net with a pretrained encoder, evaluate it with Dice and IoU, and explain the difference between semantic and instance segmentation.

Key concepts: Semantic vs instance vs panoptic, U-Net encoder-decoder, Dice and focal loss, IoU and Dice metrics, Mask R-CNN, Segment Anything (SAM), Mask-aware augmentation.

Mini project: Train a U-Net with a pretrained encoder on a public segmentation dataset (for example pets or road scenes), report per-class IoU, and overlay predicted masks on 10 validation images.

Self-check: Why can pixel accuracy be misleading for segmentation, and what does Dice loss do differently from cross-entropy?

Resources:
- [PyTorch tutorials](https://pytorch.org/tutorials/) (PyTorch)
- [Hugging Face Transformers documentation](https://huggingface.co/docs/transformers/index) (Hugging Face)
- [Dive into Deep Learning](https://d2l.ai/) (d2l.ai)

## Language, Sequences and Transformers

Turn text into numbers, model sequences, understand attention, and fine-tune pretrained transformers with the Hugging Face ecosystem.

### Text Preprocessing and Representations

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/machine-learning/text-representation

From bag-of-words and TF-IDF to subword tokenizers and dense embeddings: the ways text becomes model input.

Models only consume numbers, so every NLP system starts by deciding how text becomes vectors. The choice shapes what the model can learn and how well it handles words it never saw.

#### Classical representations
- **Normalization**: lowercasing, Unicode handling, removing markup. Stemming and lemmatization matter for classical models but rarely for transformers.
- **Bag-of-words and n-grams**: count which words appear, ignoring order.
- **TF-IDF** down-weights words that appear everywhere. TF-IDF plus logistic regression is a strong, fast baseline for classification that you should always try first.

#### Tokenization
Modern models split text into **subword tokens** using algorithms such as BPE, WordPiece or SentencePiece. Rare words break into pieces (`unbelievable` might become `un`, `believ`, `able`), so there are no unknown words and the vocabulary stays manageable. Learn to inspect token ids, special tokens, padding, truncation and attention masks, because many bugs live here.

#### Embeddings
- **Word embeddings** (word2vec, GloVe) map each word to a dense vector where similar words sit close together.
- **Contextual embeddings** from transformers give the same word different vectors depending on the sentence (river bank versus savings bank).
- **Sentence embeddings** (for example sentence-transformers models) power semantic search, clustering and deduplication using cosine similarity.

**Good enough to move on** when you can build a TF-IDF baseline, tokenize text with a pretrained tokenizer and explain every field it returns, and run a semantic similarity search with sentence embeddings.

Key concepts: Text normalization, Bag-of-words and n-grams, TF-IDF baselines, Subword tokenization (BPE, WordPiece), Word embeddings (word2vec, GloVe), Sentence embeddings, Stemming and lemmatization.

Mini project: Build a news or review classifier with TF-IDF and logistic regression, then a semantic search over the same corpus using sentence embeddings, and compare what each approach gets right.

Self-check: Why do subword tokenizers avoid the unknown-word problem, and what is the attention mask used for when batching sequences of different lengths?

Resources:
- [Hugging Face Learn](https://huggingface.co/learn) (Hugging Face)
- [scikit-learn: working with text data](https://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html) (scikit-learn)
- [Sentence Transformers documentation](https://sbert.net/) (SBERT)

### Recurrent Networks and Sequence Modelling

recommended · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/machine-learning/sequence-models

RNNs, LSTMs and GRUs process sequences step by step; learning them makes the motivation for attention clear.

Before transformers, sequence data (text, audio, sensor streams) was handled by **recurrent neural networks**. They read one element at a time and carry a hidden state forward, like a running summary. Transformers have replaced them in most NLP work, but RNN ideas still appear in time series, streaming and on-device models, and understanding their limits explains why attention was such a breakthrough.

#### Key ideas
- **Vanilla RNN**: the hidden state is updated from the previous state and the current input with shared weights.
- **Backpropagation through time** unrolls the network across steps; long sequences cause **vanishing or exploding gradients**.
- **LSTM and GRU** add gates that decide what to remember and forget, which preserves information over longer spans.
- **Bidirectional** RNNs read the sequence both ways when the whole input is available.
- **Sequence-to-sequence** models pair an encoder and a decoder for translation and summarization; the encoder squeezing everything into one vector is the bottleneck attention was invented to fix.

#### Practical notes
Pad and pack variable-length batches, clip gradients, and use teacher forcing when training decoders. For many time series problems a 1D CNN or gradient boosting on lag features is a tough baseline to beat.

#### Where to spend time
Build one LSTM model end to end so the concepts are concrete, then move on. Do not spend weeks here; the transformer topic is where modern NLP lives.

**Good enough to move on** when you can train an LSTM on a sequence task and explain why plain RNNs struggle with long-range dependencies.

Key concepts: Hidden state and recurrence, Backpropagation through time, Vanishing and exploding gradients, LSTM and GRU gates, Bidirectional RNNs, Encoder-decoder seq2seq, Padding and packing sequences.

Mini project: Train a character-level LSTM that generates names or short text in a style of your choice, and plot how sample quality changes with sequence length and hidden size.

Self-check: What problem do the gates in an LSTM solve, and why does a fixed-size encoder vector limit seq2seq translation quality?

Resources:
- [Dive into Deep Learning](https://d2l.ai/) (d2l.ai)
- [PyTorch tutorials](https://pytorch.org/tutorials/) (PyTorch)

### Attention and the Transformer Architecture

core · advanced · about 12 h · https://www.internhack.in/roadmaps/tracks/machine-learning/attention-and-transformers

Self-attention, multi-head attention, positional information and the encoder, decoder and encoder-decoder transformer families.

The transformer is the architecture behind modern language models, and increasingly vision, audio and multimodal models too. Its core idea is **attention**: every token looks at every other token and decides how much each one matters, all in parallel.

#### Self-attention step by step
- Each token vector is projected into a **query**, a **key** and a **value**.
- Scores are the dot products of queries with keys, scaled by the square root of the dimension, then passed through softmax.
- The output for each token is a weighted sum of values: `softmax(QK^T / sqrt(d)) V`.
- **Multi-head attention** runs several of these in parallel so different heads can track different relationships.

#### The rest of a block
Residual connections, layer normalization and a position-wise feed-forward network wrap each attention layer. Because attention ignores order, **positional encodings** (sinusoidal, learned, or rotary RoPE) inject position information.

#### Three families
- **Encoder-only** (BERT style): bidirectional, great for classification, tagging and embeddings.
- **Decoder-only** (GPT style): **causal masking** so each token sees only the past; trained to predict the next token. This is what large language models are.
- **Encoder-decoder** (T5, BART): for translation and summarization.

#### Cost
Attention is quadratic in sequence length, which drives research on efficient attention, KV caching and long-context tricks.

**Good enough to move on** when you can implement single-head self-attention in NumPy or PyTorch, explain causal masking, and say which family suits a given task.

Key concepts: Queries, keys and values, Scaled dot-product attention, Multi-head attention, Positional encodings and RoPE, Causal masking, Encoder vs decoder vs encoder-decoder, KV caching, Efficient attention variants.

Mini project: Implement a tiny decoder-only transformer from scratch (a few layers, character-level) and train it on a small text corpus until it generates plausible text. Visualize the attention weights for one sample.

Self-check: Why is the dot product divided by sqrt(d) before softmax, and what would go wrong in a language model without a causal mask?

Resources:
- [Dive into Deep Learning: attention mechanisms and transformers](https://d2l.ai/) (d2l.ai)
- [Hugging Face Learn](https://huggingface.co/learn) (Hugging Face)
- [The Illustrated Transformer](https://jalammar.github.io/illustrated-transformer/) (Jay Alammar)

### Fine-Tuning with Hugging Face Transformers

core · intermediate · about 12 h · https://www.internhack.in/roadmaps/tracks/machine-learning/hugging-face-transformers

Use the Hub, tokenizers, datasets and the Trainer API to fine-tune pretrained models for classification, NER and question answering.

Hugging Face is the standard toolkit for working with pretrained transformers. Knowing it well lets you go from idea to a fine-tuned, shareable model in an afternoon.

#### The pieces
- **The Hub**: hundreds of thousands of models and datasets, each with a model card. Learn to read cards for license, training data and intended use.
- **`pipeline()`**: one-line inference for sentiment, NER, summarization, zero-shot classification and more. Use it to build a baseline in minutes.
- **`AutoTokenizer` and `AutoModelFor...`** classes load the right architecture and task head from a checkpoint name.
- **`datasets`**: memory-mapped datasets with fast `map` for tokenization and easy train/validation splits.
- **`Trainer` and `TrainingArguments`**: a ready-made training loop with evaluation, checkpointing, mixed precision and logging. **Accelerate** helps if you want your own loop.

#### Typical fine-tuning flow
1. Pick a small, suitable checkpoint (for example a DistilBERT or DeBERTa variant for English classification).
2. Tokenize with truncation and dynamic padding via a data collator.
3. Define `compute_metrics` with the metrics that matter for your task.
4. Train, evaluate on a held-out set, and inspect errors.
5. `push_to_hub` with a model card, or save locally for serving.

#### Tasks to practise
Sequence classification, token classification (NER), extractive question answering and summarization each use a different head and label format. Doing one of each teaches the patterns.

**Good enough to move on** when you can fine-tune a pretrained model on a labelled dataset, beat your TF-IDF baseline, and share the model with a clear model card.

Key concepts: Hugging Face Hub and model cards, pipeline() inference, AutoTokenizer and AutoModel, datasets library, Trainer and TrainingArguments, Token classification (NER), Question answering and summarization, Accelerate custom loops.

Mini project: Fine-tune a small encoder model on a text classification dataset from the Hub, compare it with your TF-IDF baseline on the same split, and publish it to the Hub with a model card that lists limitations.

Self-check: What does a data collator with dynamic padding do, and why is it more efficient than padding every example to the maximum length?

Resources:
- [Hugging Face Learn](https://huggingface.co/learn) (Hugging Face)
- [Transformers documentation](https://huggingface.co/docs/transformers/index) (Hugging Face)
- [Datasets documentation](https://huggingface.co/docs/datasets/index) (Hugging Face)

### Large Language Models and Efficient Fine-Tuning

optional · advanced · about 12 h · https://www.internhack.in/roadmaps/tracks/machine-learning/llm-fine-tuning

How LLMs are pretrained and aligned, and how to adapt open models cheaply with LoRA, quantization and instruction data.

Large language models are decoder-only transformers trained on huge text corpora to predict the next token, then refined to follow instructions. As an ML engineer you will more often adapt or evaluate them than pretrain one.

#### How LLMs are built
- **Pretraining**: next-token prediction on trillions of tokens. Scaling laws relate loss to parameters, data and compute.
- **Supervised fine-tuning (SFT)** on instruction and response pairs teaches the model to be helpful.
- **Preference tuning** (RLHF, DPO and related methods) aligns outputs with human preferences.
- **Decoding**: greedy, temperature, top-k and top-p sampling change output style and diversity.

#### Adapting open models
- Try **prompting and retrieval (RAG)** first; they are cheaper and easier to update than fine-tuning.
- Fine-tune when you need a consistent format, domain style or smaller, faster model.
- **LoRA** trains small low-rank adapter matrices instead of all weights. **QLoRA** does this on a 4-bit quantized base model, so a 7B model fits on a single consumer GPU.
- Libraries: Hugging Face **PEFT** and **TRL** for SFT and DPO.

#### Evaluation
Hold out test prompts, compare against the base model, and combine automatic metrics with human or model-graded review. Watch for **catastrophic forgetting** and for test data that leaked into training.

**Good enough to move on** when you can fine-tune a small open model with LoRA on an instruction dataset and show, with an evaluation set, whether it actually improved.

Key concepts: Next-token pretraining and scaling, Supervised instruction tuning, RLHF and DPO, Decoding and sampling, LoRA and QLoRA, PEFT and TRL libraries, Prompting vs RAG vs fine-tuning, LLM evaluation.

Mini project: Fine-tune a 1B to 3B parameter open model with QLoRA to answer in a fixed JSON format for a narrow task, and compare format accuracy and answer quality with the base model on 50 held-out prompts.

Self-check: Why does LoRA need far less GPU memory than full fine-tuning, and when would you choose RAG over fine-tuning?

Resources:
- [Hugging Face Learn](https://huggingface.co/learn) (Hugging Face)
- [PEFT documentation](https://huggingface.co/docs/peft/index) (Hugging Face)
- [TRL documentation](https://huggingface.co/docs/trl/index) (Hugging Face)

## Generative Models

Models that create new data: autoencoders and VAEs, adversarial training, and the diffusion models behind modern image generation.

### Autoencoders and Variational Autoencoders

optional · advanced · about 8 h · https://www.internhack.in/roadmaps/tracks/machine-learning/autoencoders-vaes

Compress data into a latent space and reconstruct it; add a probabilistic twist and you get a model that can sample new examples.

An **autoencoder** has an encoder that squeezes the input into a small latent vector and a decoder that rebuilds the input from it. Because the bottleneck is narrow, the network must learn the most important structure of the data. That makes autoencoders useful well beyond generation.

#### Plain autoencoders
- **Dimensionality reduction**: a nonlinear cousin of PCA.
- **Denoising autoencoders** learn to remove noise by reconstructing clean inputs from corrupted ones.
- **Anomaly detection**: inputs unlike the training data reconstruct poorly, so reconstruction error flags them.

#### Variational autoencoders (VAEs)
A plain autoencoder's latent space has gaps, so random points decode to garbage. A **VAE** makes the encoder output a distribution (a mean and variance) and pushes it towards a standard normal. The loss has two parts:
- a **reconstruction term** (how well the output matches the input), and
- a **KL divergence term** (how close the latent distribution is to the prior).

The **reparameterization trick** (`z = mu + sigma * eps`) keeps sampling differentiable so the model trains with ordinary backpropagation. After training you can sample `z` from a normal distribution and decode brand new examples, or interpolate smoothly between two inputs.

#### Why it still matters
VAEs produce blurrier samples than GANs or diffusion, but the idea of a learned latent space is everywhere: **latent diffusion** models such as Stable Diffusion run their denoising inside a VAE's latent space.

**Good enough to move on** when you can train a VAE on a small image dataset, sample new images, and explain both terms of its loss.

Key concepts: Encoder, bottleneck, decoder, Denoising autoencoders, Reconstruction-based anomaly detection, VAE latent distributions, KL divergence term, Reparameterization trick, Latent space interpolation.

Mini project: Train a convolutional VAE on Fashion-MNIST, plot a 2D latent space coloured by class, generate a grid of new samples, and use reconstruction error to detect images from a different dataset.

Self-check: What would happen to a VAE's samples if you removed the KL term from the loss, and why is the reparameterization trick needed?

Resources:
- [Dive into Deep Learning](https://d2l.ai/) (d2l.ai)
- [Deep Learning (Goodfellow, Bengio, Courville)](https://www.deeplearningbook.org/) (MIT Press)
- [PyTorch tutorials](https://pytorch.org/tutorials/) (PyTorch)

### Generative Adversarial Networks

optional · advanced · about 8 h · https://www.internhack.in/roadmaps/tracks/machine-learning/gans

A generator and a discriminator trained against each other; powerful for sharp images and a lesson in unstable optimization.

A **GAN** sets up a game. The **generator** turns random noise into fake samples; the **discriminator** tries to tell real from fake. Each improves by exploiting the other's weaknesses, and at equilibrium the generator produces samples the discriminator cannot distinguish from real data.

#### Training loop
1. Sample real data and generate fakes from noise.
2. Update the discriminator to label real as 1 and fake as 0.
3. Update the generator so the discriminator labels its fakes as real.

#### Why GANs are hard
- **Mode collapse**: the generator finds a few outputs that fool the discriminator and stops producing variety.
- **Non-convergence**: the two networks oscillate instead of settling.
- **Balance**: if the discriminator gets too good, the generator's gradients vanish.

Fixes that became standard include the **DCGAN** architecture guidelines, **Wasserstein loss with gradient penalty**, spectral normalization and careful learning rates for each network.

#### Notable variants
Conditional GANs generate a requested class; Pix2Pix and CycleGAN translate images between domains; StyleGAN produces high-resolution faces with controllable style.

#### Evaluating generators
Visual inspection is essential but biased. **FID** (Frechet Inception Distance) compares statistics of real and generated images and is the common benchmark; lower is better.

Diffusion models have largely overtaken GANs for image quality, but GANs remain fast at sampling and appear in super-resolution and real-time applications.

**Good enough to move on** when you can train a DCGAN on a small dataset, recognize mode collapse in its samples, and describe one fix.

Key concepts: Generator and discriminator, Adversarial training loop, Mode collapse, DCGAN architecture, Wasserstein loss and gradient penalty, Conditional GANs and CycleGAN, FID evaluation.

Mini project: Train a DCGAN on a small image dataset, save a sample grid every epoch into an animation, and compare results with and without label smoothing or spectral normalization.

Self-check: What is mode collapse, how would you notice it, and why can an overly strong discriminator stop the generator from learning?

Resources:
- [Google: Generative Adversarial Networks](https://developers.google.com/machine-learning/gan) (Google)
- [PyTorch tutorials](https://pytorch.org/tutorials/) (PyTorch)

### Diffusion Models

optional · advanced · about 12 h · https://www.internhack.in/roadmaps/tracks/machine-learning/diffusion-models

Learn to reverse a gradual noising process; the technique behind Stable Diffusion and most state-of-the-art image, audio and video generators.

Diffusion models generate data by learning to remove noise. During training you take a real image, add a random amount of Gaussian noise, and teach a network to predict that noise. At generation time you start from pure noise and denoise step by step until an image appears.

#### Core pieces
- **Forward process**: a fixed schedule that gradually adds noise over many timesteps.
- **Denoising network**: usually a **U-Net** (or a diffusion transformer) that takes the noisy image and the timestep and predicts the noise.
- **Loss**: simple mean squared error between predicted and actual noise, which makes training far more stable than GANs.
- **Samplers and schedulers** (DDPM, DDIM, DPM-Solver and others) trade the number of steps against quality.

#### Controlling what you get
- **Conditioning** on text via embeddings from a text encoder injected through cross-attention.
- **Classifier-free guidance** strengthens the effect of the prompt; the guidance scale is a key knob.
- **Latent diffusion** runs the whole process in a compressed VAE latent space, making high-resolution generation affordable.
- **ControlNet, LoRA and DreamBooth** add spatial control or teach new concepts with a few images.

#### Using them in practice
The Hugging Face **diffusers** library gives you pipelines, schedulers and training scripts. Start by running a pretrained pipeline, then train a tiny unconditional model on small images so you understand the loop, then try a LoRA fine-tune.

Be thoughtful about licensing of models and training images, consent for likeness, and labelling generated content.

**Good enough to move on** when you can explain the forward and reverse processes, train a small diffusion model from scratch, and tune guidance and steps in a pretrained pipeline.

Key concepts: Forward noising process, Noise-prediction training objective, U-Net denoiser and timesteps, Samplers and schedulers, Classifier-free guidance, Latent diffusion, diffusers library, LoRA, DreamBooth and ControlNet.

Mini project: Train a small unconditional diffusion model on 32x32 images with diffusers, then use a pretrained text-to-image pipeline to compare 10, 25 and 50 sampling steps and three guidance scales on the same prompts.

Self-check: What exactly is the network trained to predict in a DDPM, and what does raising the classifier-free guidance scale trade off?

Resources:
- [Diffusers documentation](https://huggingface.co/docs/diffusers/index) (Hugging Face)
- [Hugging Face Learn](https://huggingface.co/learn) (Hugging Face)
- [Practical Deep Learning for Coders](https://course.fast.ai/) (fast.ai)

## Recommenders, Time Series and Reinforcement Learning

Problem types with their own data shapes, evaluation traps and algorithms; pick the ones that match the domain you want to work in.

### Recommender Systems

optional · advanced · about 10 h · https://www.internhack.in/roadmaps/tracks/machine-learning/recommender-systems

Collaborative filtering, content-based and two-tower retrieval models, plus the ranking metrics and feedback loops that make recommenders unusual.

Recommenders decide what a user sees next: products, videos, jobs, songs. They drive a large share of revenue at many companies, so they are a common ML engineering specialty.

#### Approaches
- **Popularity and heuristics**: the baseline that is surprisingly hard to beat for new users.
- **Content-based**: recommend items similar to what the user liked, using item features or embeddings.
- **Collaborative filtering**: users who behaved alike will like similar things. **Matrix factorization** learns user and item vectors whose dot product predicts interest.
- **Two-tower models**: one network embeds users, another embeds items; nearest-neighbour search retrieves candidates quickly.
- **Ranking models**: gradient boosting or deep models rescore a few hundred candidates with rich features.

#### Data realities
Most data is **implicit feedback** (clicks, views, purchases) rather than ratings, and missing does not mean disliked. The **cold-start** problem hits new users and new items. Recommendations also shape future training data, creating **feedback loops** and popularity bias.

#### Evaluation
- Offline ranking metrics: **precision@k, recall@k, MAP, NDCG, hit rate**.
- Split by time, not at random, so you never train on the future.
- Beyond accuracy: coverage, diversity and novelty.
- The final judge is an **online A/B test**.

**Good enough to move on** when you can build a retrieval plus ranking recommender on a public dataset and evaluate it with NDCG@10 on a time-based split.

Key concepts: Popularity baselines, Content-based filtering, Matrix factorization, Implicit feedback, Two-tower retrieval, Candidate ranking stage, NDCG and recall@k, Cold start and feedback loops.

Mini project: Using the MovieLens dataset, compare a popularity baseline, matrix factorization and a two-tower model on a time-based split with recall@20 and NDCG@10, and show recommendations for three sample users.

Self-check: Why is a random train/test split misleading for recommender evaluation, and what does NDCG reward that precision@k does not?

Resources:
- [Google: Recommendation Systems](https://developers.google.com/machine-learning/recommendation) (Google)
- [Dive into Deep Learning](https://d2l.ai/) (d2l.ai)

### Time Series Forecasting

optional · intermediate · about 10 h · https://www.internhack.in/roadmaps/tracks/machine-learning/time-series-forecasting

Trend, seasonality, lag features and proper backtesting, from classical models to gradient boosting and deep forecasters.

Forecasting demand, traffic, prices or sensor readings is one of the most common business uses of ML, and one of the easiest to get wrong because time breaks the usual assumptions.

#### Understand the series first
- Plot it. Look for **trend**, **seasonality** (daily, weekly, yearly), holidays, outliers and structural breaks.
- **Decomposition** separates trend, seasonal and residual parts.
- **Stationarity** and autocorrelation plots (ACF, PACF) guide classical model choices.

#### Model options
- **Baselines**: last value, seasonal naive (same day last week) and moving averages. Always report them.
- **Classical**: exponential smoothing (ETS) and ARIMA/SARIMA, strong on single series with clear patterns.
- **ML on features**: build **lag features**, rolling statistics and calendar features, then use gradient boosting. This wins many competitions and works across many related series.
- **Deep and foundation models**: N-BEATS, temporal fusion transformers and pretrained forecasting models for large collections of series.

#### Evaluation without cheating
Never shuffle. Use **rolling-origin backtesting** (train up to time t, forecast the next horizon, move forward, repeat). Compute rolling features using only past data. Choose metrics that match the business: MAE, RMSE, MAPE (breaks near zero) or MASE, and produce **prediction intervals**, not just point forecasts.

**Good enough to move on** when you can beat a seasonal naive baseline in a proper backtest and explain which features could have leaked future information.

Key concepts: Trend and seasonality decomposition, Naive and seasonal baselines, ARIMA and exponential smoothing, Lag and rolling features, Rolling-origin backtesting, Forecast metrics (MAE, MAPE, MASE), Prediction intervals, Deep forecasting models.

Mini project: Forecast daily sales or energy demand 14 days ahead: compare seasonal naive, ETS and LightGBM with lag features in a 6-fold rolling backtest, and plot forecasts with 80 percent intervals.

Self-check: Why is a random K-fold split invalid for time series, and how does rolling-origin evaluation fix it?

Resources:
- [Forecasting: Principles and Practice](https://otexts.com/fpp3/) (OTexts)
- [TensorFlow: time series forecasting tutorial](https://www.tensorflow.org/tutorials/structured_data/time_series) (TensorFlow)
- [Kaggle Learn: Time Series](https://www.kaggle.com/learn/time-series) (Kaggle)

### Reinforcement Learning Fundamentals

optional · intermediate · about 10 h · https://www.internhack.in/roadmaps/tracks/machine-learning/reinforcement-learning-basics

Agents, environments, rewards and value functions: the MDP framework, bandits, and tabular methods like Q-learning.

In reinforcement learning (RL) there are no labels. An **agent** takes actions in an **environment**, receives **rewards**, and must learn a **policy** that maximizes long-term reward. It is the framework behind game-playing agents, robotics control, and the preference tuning of language models.

#### The vocabulary
- **Markov decision process (MDP)**: states, actions, transition probabilities, rewards and a **discount factor** gamma.
- **Return**: the discounted sum of future rewards.
- **Value function** V(s) and **action-value function** Q(s, a): how good a state or action is under a policy.
- **Bellman equations** express a value in terms of the next step's value; almost every algorithm is built on them.

#### Core ideas
- **Exploration versus exploitation**: try new actions or use the best known one. **Multi-armed bandits** isolate this trade-off and are used directly for A/B testing and ad selection.
- **Dynamic programming** (value and policy iteration) when the environment model is known.
- **Monte Carlo** and **temporal-difference** learning when it is not.
- **Q-learning** (off-policy) and **SARSA** (on-policy) learn Q-values from experience with epsilon-greedy exploration.

#### Tools
**Gymnasium** provides standard environments (CartPole, FrozenLake, MountainCar) with a common `reset` and `step` API. Start with tabular problems where you can print the whole Q-table and watch it converge.

**Good enough to move on** when you can implement tabular Q-learning for a grid world, tune epsilon and the learning rate, and explain the Bellman update you are applying.

Key concepts: Agents, states, actions, rewards, Markov decision processes, Value functions and Bellman equations, Exploration vs exploitation, Multi-armed bandits, Q-learning and SARSA, Gymnasium environments.

Mini project: Implement tabular Q-learning and SARSA for FrozenLake in Gymnasium, plot reward per episode for several epsilon schedules, and render the learned policy as arrows on the grid.

Self-check: What is the difference between on-policy SARSA and off-policy Q-learning, and why does the discount factor matter?

Resources:
- [Reinforcement Learning: An Introduction (Sutton and Barto)](https://incompleteideas.net/book/the-book-2nd.html) (Sutton and Barto)
- [Gymnasium documentation](https://gymnasium.farama.org/) (Farama Foundation)
- [Hugging Face Learn](https://huggingface.co/learn) (Hugging Face)

### Deep Reinforcement Learning

optional · advanced · about 12 h · https://www.internhack.in/roadmaps/tracks/machine-learning/deep-reinforcement-learning

Neural networks as value functions and policies: DQN, policy gradients, actor-critic methods and PPO.

Tabular methods break down when states are images or continuous vectors. **Deep RL** replaces the table with a neural network that generalizes across states.

#### Value-based: DQN
A **Deep Q-Network** approximates Q(s, a). Two tricks made it stable: an **experience replay buffer** that breaks correlation between consecutive samples, and a slowly updated **target network**. Extensions include Double DQN, dueling heads and prioritized replay.

#### Policy-based methods
- **Policy gradients (REINFORCE)** directly adjust action probabilities in the direction that increases return. Simple but high variance.
- **Actor-critic** methods (A2C, A3C) add a learned value function (the critic) as a baseline to reduce variance.
- **PPO** clips each policy update so it cannot move too far, making training robust. It is the default algorithm in many libraries and was used in RLHF for language models.
- **SAC** and TD3 handle continuous action spaces such as robot joints.

#### Practical realities
Deep RL is notoriously sensitive to hyperparameters, random seeds and reward design. Agents exploit poorly specified rewards in surprising ways (**reward hacking**). Run several seeds, log episode returns, and use tested implementations from **Stable-Baselines3** or CleanRL before writing your own.

#### Where it is used
Games, robotics and simulation, recommendation and bidding systems, chip design, and aligning language models with human preferences.

**Good enough to move on** when you can train PPO and DQN on standard environments, compare them across seeds, and explain why experience replay stabilizes DQN.

Key concepts: Deep Q-Networks (DQN), Experience replay and target networks, Policy gradients (REINFORCE), Actor-critic methods, PPO, SAC for continuous control, Reward design and reward hacking, Stable-Baselines3.

Mini project: Train DQN and PPO on CartPole and LunarLander with Stable-Baselines3 across three seeds, plot mean and spread of returns, then implement REINFORCE yourself on CartPole and compare its variance.

Self-check: Why does subtracting a baseline (the critic) reduce the variance of policy gradient estimates without biasing them?

Resources:
- [OpenAI Spinning Up in Deep RL](https://spinningup.openai.com/) (OpenAI)
- [Stable-Baselines3 documentation](https://stable-baselines3.readthedocs.io/) (Stable-Baselines3)
- [Hugging Face Learn](https://huggingface.co/learn) (Hugging Face)

## MLOps: Shipping and Operating Models

Turn notebooks into reliable systems: tracked experiments, versioned data, containerized services, automated pipelines and monitoring in production.

### From Notebook to Production Code

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/machine-learning/notebook-to-production-code

Refactor exploratory notebooks into a tested, configurable Python package that anyone on the team can run.

Notebooks are wonderful for exploration and terrible as the only home of a model. Hidden state, out-of-order cells and copy-pasted code make results impossible to reproduce. The first MLOps skill is moving working ideas into ordinary, well-structured code.

#### Project structure
- A `src/` package with modules for data loading, features, training, evaluation and inference.
- **Configuration** in YAML or dataclasses (Hydra and Pydantic are popular) instead of constants scattered through code.
- **Entry points** such as `python -m project.train --config configs/base.yaml`.
- Pinned dependencies with `uv`, Poetry or a lock file, and a README explaining how to run everything.

#### Code quality
- **Type hints** and a linter/formatter (Ruff) keep code readable.
- **Logging** instead of print statements.
- **Seeds** and deterministic settings where practical.

#### Testing ML code
Traditional unit tests still apply: feature functions, data validation, metric calculations. Add ML-specific checks:
- **Shape and dtype tests** for model inputs and outputs.
- **Overfit-one-batch** tests that prove the training loop can learn.
- **Data validation** of schema, ranges and null rates (Pandera or Great Expectations).
- **Behavioural tests**: invariances (a name change should not flip sentiment) and directional expectations.

Keep notebooks for exploration and reports, importing functions from the package so logic lives in one place.

**Good enough to move on** when a teammate can clone your repo, install it, run training from one command, and see the same metrics with tests passing in CI.

Key concepts: Package layout and entry points, Config files (Hydra, Pydantic), Dependency pinning, Linting and type hints, Unit tests with pytest, Data validation checks, Behavioural model tests.

Mini project: Take one of your earlier notebook projects and refactor it into a package with a config file, a train command, a predict command, pytest tests for features and data validation, and a GitHub Actions workflow that runs them.

Self-check: Name three kinds of bugs a notebook-only workflow hides, and describe one test that is specific to ML code rather than normal software.

Resources:
- [Made With ML](https://madewithml.com/) (Made With ML)
- [pytest documentation](https://docs.pytest.org/) (pytest)
- [Rules of Machine Learning](https://developers.google.com/machine-learning/guides/rules-of-ml) (Google)

### Experiment Tracking with MLflow and Weights and Biases

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/machine-learning/experiment-tracking

Log parameters, metrics, artifacts and code versions for every run so you can compare, reproduce and promote models with confidence.

After a few dozen training runs, nobody remembers which learning rate produced the good model or which data version it used. **Experiment tracking** records that automatically.

#### What to log for every run
- **Parameters**: hyperparameters and config values.
- **Metrics**: training and validation curves, final test scores.
- **Artifacts**: model files, plots, confusion matrices, sample predictions.
- **Context**: git commit, data version, environment, hardware.

#### Tools
- **MLflow** (open source, self-hostable): tracking server, UI, `mlflow.autolog()` for popular libraries, and a **model registry** with versions and aliases such as `champion`.
- **Weights and Biases** (hosted, free for personal use): rich dashboards, sweeps for hyperparameter search, reports to share findings.
- Alternatives include TensorBoard for curves and Neptune or Comet.

#### Working habits
- Name experiments by question ("does augmentation X help?") rather than by date.
- Compare runs with parallel coordinates and overlaid curves before deciding.
- Tag the run that becomes production and register it, so serving code loads a model by name and version instead of a file path.
- Log enough to rerun: a run you cannot reproduce is only an anecdote.

**Good enough to move on** when every training run you do is tracked, you can reproduce a registered model from its logged metadata, and you can load a model from the registry in a separate script.

Key concepts: Logging params, metrics and artifacts, MLflow tracking and autolog, Model registry and aliases, Weights and Biases dashboards, Sweeps for hyperparameter search, TensorBoard.

Mini project: Add MLflow tracking to your refactored project, run a 20-trial hyperparameter search, register the best model, and write a script that loads the champion model by alias and scores new data.

Self-check: What information would you need to exactly reproduce a model from three months ago, and where would each piece be stored?

Resources:
- [MLflow documentation](https://mlflow.org/docs/latest/index.html) (MLflow)
- [Weights and Biases documentation](https://docs.wandb.ai/) (Weights and Biases)

### Data and Model Versioning with DVC

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/machine-learning/data-versioning

Version large datasets and model files alongside code, and define reproducible pipelines that rerun only what changed.

Git is built for text files, not 20 GB of images. Yet a model is a function of code **and** data, so both need versions. **DVC** (Data Version Control) extends Git to handle this.

#### How DVC works
- `dvc add data/raw` replaces the data in Git with a small `.dvc` pointer file holding a content hash.
- The actual files live in a **remote** (S3, GCS, Azure, SSH or a local folder) and are fetched with `dvc pull`.
- Checking out an old commit plus `dvc checkout` restores the exact data used then.

#### Pipelines
A `dvc.yaml` file describes stages (prepare, featurize, train, evaluate) with their dependencies and outputs. `dvc repro` reruns only stages whose inputs changed, like `make` for ML. `dvc metrics diff` and `dvc plots` compare results across branches.

#### Alternatives and complements
- **Lake formats** such as Delta Lake or Apache Iceberg offer time travel on tables.
- **LakeFS** gives Git-like branches over object storage.
- **Hugging Face Hub** datasets have versioned repos.
- Model files usually live in the **model registry** from experiment tracking, linked to the data version that produced them.

#### Lineage
The goal is lineage: for any prediction in production you can answer which model, trained on which data, by which code. That matters for debugging, audits and regulated industries.

**Good enough to move on** when you can clone a repo, run `dvc pull` and `dvc repro`, and get the same model and metrics as the original author.

Key concepts: Why data needs versions, dvc add and remotes, dvc.yaml pipelines and repro, Metrics and plots diff, Lineage and audit trails, Delta Lake, Iceberg and LakeFS.

Mini project: Put your project's raw data under DVC with a cloud or local remote, define a three-stage dvc.yaml pipeline, change one feature, and use dvc metrics diff to show the effect between two branches.

Self-check: What is actually committed to Git when you run dvc add on a folder, and how does dvc repro decide which stages to rerun?

Resources:
- [DVC documentation](https://dvc.org/doc) (Iterative)
- [Made With ML](https://madewithml.com/) (Made With ML)

### Docker for ML

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/machine-learning/docker-for-ml

Package a model, its dependencies and its runtime into a container image that runs the same on a laptop, a server or a GPU cluster.

"It works on my machine" is especially painful in ML, where results depend on exact library versions, CUDA drivers and system packages. **Containers** freeze the whole environment into an image.

#### Essentials
- **Images and containers**: an image is the blueprint, a container is a running instance.
- **Dockerfile**: start `FROM` a base image, `COPY` code, `RUN` installs, set a `CMD`.
- **Layer caching**: copy and install requirements before copying source code so rebuilds are fast.
- **Volumes** for datasets and model files you do not want baked into the image.
- **Port mapping** to reach an API running inside the container.
- **docker compose** to run the model API alongside a database or monitoring stack.

#### ML-specific concerns
- **Image size**: use slim base images and **multi-stage builds**; install CPU-only wheels for CPU inference.
- **GPU access**: use CUDA base images (or official PyTorch images) and the NVIDIA Container Toolkit, then `docker run --gpus all`.
- **Model weights**: either bake them in for immutability or download them at startup from a registry; choose deliberately.
- **Security**: run as a non-root user and never put secrets in the image.

#### Where it leads
The same image runs on cloud container services, Kubernetes and batch job platforms, which is why nearly every serving and pipeline tool expects one.

**Good enough to move on** when you can containerize a training script and an inference API, keep the image reasonably small, and run it with GPU access.

Key concepts: Images, containers and Dockerfiles, Layer caching, Volumes and port mapping, docker compose, Multi-stage builds and slim images, GPU containers, Non-root users and secrets.

Mini project: Write a multi-stage Dockerfile for your model's prediction service, get the image under 1 GB for CPU inference, and add a docker compose file that also starts a Prometheus container scraping it.

Self-check: Why should you copy requirements.txt and install dependencies before copying your source code in a Dockerfile?

Resources:
- [Docker: Get started](https://docs.docker.com/get-started/) (Docker)
- [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/index.html) (NVIDIA)

### Serving Models with FastAPI and BentoML

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/machine-learning/model-serving

Expose models as reliable prediction APIs or batch jobs, with input validation, batching, health checks and sensible latency budgets.

A model creates value only when something can call it. The main serving patterns are:
- **Online (real-time)**: an HTTP or gRPC API answers each request in milliseconds.
- **Batch**: score millions of rows on a schedule and write results to a table.
- **Streaming**: consume events from a queue such as Kafka and emit predictions.
- **Edge**: run on a phone or browser (TFLite, ONNX Runtime, Core ML).

Many teams start with batch, since it is simpler and cheaper; move to online only when freshness requires it.

#### A FastAPI service
- Load the model **once at startup**, not per request.
- Define request and response schemas with **Pydantic** so bad inputs fail with clear errors.
- Reuse the exact preprocessing pipeline from training (a saved scikit-learn pipeline or tokenizer).
- Add `/health` and `/ready` endpoints, structured logging and a model version in every response.

#### Dedicated serving frameworks
- **BentoML** packages models with their code into deployable services with adaptive batching.
- **NVIDIA Triton**, **TorchServe**, **Ray Serve** and **vLLM** (for LLMs) handle GPU batching and concurrency at scale.
- **Gradio** and **Streamlit** are for demos, not production traffic.

#### Performance and safety
Measure **p50 and p99 latency** and throughput with a load test. Batch requests on GPUs, cache repeated inputs, and set timeouts. Roll out new versions with **shadow**, **canary** or **A/B** deployments and keep a fast rollback path.

**Good enough to move on** when you can serve a model behind a validated API, load test it, and deploy a new version without downtime.

Key concepts: Online, batch, streaming and edge, FastAPI prediction endpoints, Pydantic input validation, Health checks and versioning, BentoML services, Triton, TorchServe and vLLM, Load testing and latency, Canary and shadow deployments.

Mini project: Serve your registered model with FastAPI in Docker, add Pydantic schemas, health checks and a version header, load test it with Locust to find p99 latency, then repackage it with BentoML and compare throughput.

Self-check: Why should the model load at application startup rather than inside the request handler, and when is batch scoring a better choice than a real-time API?

Resources:
- [FastAPI documentation](https://fastapi.tiangolo.com/) (FastAPI)
- [BentoML documentation](https://docs.bentoml.com/) (BentoML)
- [Made With ML](https://madewithml.com/) (Made With ML)

### ML Pipelines, Orchestration and CI/CD

recommended · advanced · about 8 h · https://www.internhack.in/roadmaps/tracks/machine-learning/ml-pipelines-cicd

Automate data ingestion, training, evaluation and deployment as scheduled, tested workflows instead of manual steps.

Models go stale as data changes, so retraining must be routine, not heroic. An **ML pipeline** chains the steps (ingest, validate, featurize, train, evaluate, register, deploy) into one automated, observable workflow.

#### Orchestrators
- **Airflow**: the veteran scheduler for data workflows, defined as Python DAGs.
- **Prefect** and **Dagster**: modern Python-first orchestration with good local development.
- **Kubeflow Pipelines**, **Metaflow** and **ZenML**: ML-focused, often on Kubernetes.
- Cloud-native options: SageMaker Pipelines, Vertex AI Pipelines, Azure ML.

Pick one and learn its ideas: tasks, dependencies, retries, caching, parameters, schedules and backfills.

#### CI/CD for ML
- **CI** runs on every pull request: linting, unit tests, data validation, and a quick training run on a sample to catch breakage.
- **Continuous training** retrains on a schedule or when monitoring detects drift.
- **Evaluation gates**: a candidate is promoted only if it beats the current model on a fixed test set and passes fairness and latency checks.
- **CD** deploys the promoted model through staging to production, with automatic rollback.

#### Maturity levels
Level 0 is manual notebooks. Level 1 automates the training pipeline. Level 2 automates building, testing and deploying the pipeline itself. Most teams should aim for level 1 first.

**Good enough to move on** when a schedule or a code change can trigger training, evaluation and a gated model promotion without anyone running cells by hand.

Key concepts: Pipeline stages and DAGs, Airflow, Prefect or Dagster, Kubeflow and Metaflow, CI with GitHub Actions, Continuous training triggers, Evaluation and promotion gates, MLOps maturity levels.

Mini project: Build a Prefect or Airflow flow that pulls fresh data, validates it, retrains, compares against the registered champion, and promotes the new model only if it wins, plus a GitHub Actions workflow that runs tests and a smoke training run on every PR.

Self-check: What checks would you put in an evaluation gate before automatically promoting a retrained model to production?

Resources:
- [MLOps: continuous delivery and automation pipelines in ML](https://cloud.google.com/architecture/mlops-continuous-delivery-and-automation-pipelines-in-machine-learning) (Google Cloud)
- [Prefect documentation](https://docs.prefect.io/) (Prefect)
- [Apache Airflow documentation](https://airflow.apache.org/docs/) (Apache)

### Monitoring, Drift and Model Maintenance

core · advanced · about 6 h · https://www.internhack.in/roadmaps/tracks/machine-learning/model-monitoring

Detect when production data or model quality drifts away from what you trained on, and decide when to retrain.

A model's accuracy on launch day is its best day. Customer behaviour shifts, upstream pipelines change, and the world moves on. Without monitoring you learn about it from angry users.

#### What can go wrong
- **Data drift (covariate shift)**: input distributions change, for example a new user segment.
- **Concept drift**: the relationship between inputs and target changes, for example fraud patterns adapt.
- **Label shift**: the class balance moves.
- **Data quality bugs**: a column becomes all nulls, units change, a category is renamed.
- **Training-serving skew**: features are computed differently online than in training.

#### What to monitor
- **Operational**: latency, error rates, throughput, resource use.
- **Inputs**: null rates, ranges, category frequencies, and drift statistics such as **PSI**, KL divergence or Kolmogorov-Smirnov tests.
- **Outputs**: prediction distribution and confidence.
- **Quality**: real metrics once labels arrive; use proxies (click-through, complaints) while you wait.

#### Tools and practice
Log every request and prediction with a model version. **Evidently**, WhyLabs or NannyML compute drift reports; Prometheus and Grafana handle dashboards and alerts. Set alert thresholds carefully: drift in an unimportant feature is noise. Decide in advance whether retraining is scheduled, triggered by drift, or triggered by a drop in measured quality, and keep humans in the loop for high-stakes models.

**Good enough to move on** when your deployed model has dashboards and alerts for inputs, outputs and latency, and you have a written plan for what happens when an alert fires.

Key concepts: Data drift vs concept drift, Training-serving skew, Drift statistics (PSI, KS test), Prediction and label logging, Evidently reports, Prometheus and Grafana alerts, Retraining strategies.

Mini project: Simulate drift by replaying a dataset in time order through your served model, log inputs and predictions, generate Evidently drift reports per week, and trigger an alert and retraining job when PSI crosses a threshold.

Self-check: How would you tell data drift apart from concept drift, and why can you detect one before labels arrive but not the other?

Resources:
- [Evidently documentation](https://docs.evidentlyai.com/) (Evidently AI)
- [Made With ML](https://madewithml.com/) (Made With ML)
- [Prometheus documentation](https://prometheus.io/docs/introduction/overview/) (Prometheus)

### Feature Stores

optional · advanced · about 5 h · https://www.internhack.in/roadmaps/tracks/machine-learning/feature-stores

Share consistent features between training and serving with offline and online stores and point-in-time correct joins.

When several models reuse the same features (customer lifetime value, recent purchase counts) and need them both for training on history and for real-time serving, teams build a **feature store**. It is a coordination tool as much as a database.

#### What a feature store provides
- **Feature definitions** as code, registered once and reused by many models.
- An **offline store** (a warehouse or data lake) with full history for training.
- An **online store** (a low-latency key-value database such as Redis) with the latest values for serving.
- **Materialization** jobs that keep the online store fresh from batch or streaming sources.
- **Point-in-time correct joins** so each training row only sees feature values that existed at that moment. This prevents a subtle form of leakage that hand-written joins often introduce.

#### Tools
**Feast** is the common open-source option. Managed versions exist in Databricks, SageMaker, Vertex AI and dedicated vendors such as Tecton and Hopsworks.

#### When you need one
Not on your first project. A feature store pays off when you have many models, real-time features, and repeated **training-serving skew** bugs. Before that, a well-organized set of SQL views or dbt models plus a shared feature module in Python is usually enough.

**Good enough to move on** when you can define features in Feast, generate a point-in-time correct training set, and fetch the same features online for a prediction request.

Key concepts: Offline vs online stores, Point-in-time correct joins, Feature definitions and reuse, Materialization jobs, Feast, Streaming features.

Mini project: Model a small e-commerce dataset in Feast with two entities and five features, build a point-in-time correct training set, materialize to a local online store, and serve features to your FastAPI model.

Self-check: What is a point-in-time correct join, and what leakage happens if you simply join the latest feature values onto historical labels?

Resources:
- [Feast documentation](https://docs.feast.dev/) (Feast)
- [Made With ML](https://madewithml.com/) (Made With ML)

## Scaling Up: Distributed Training and Efficient Inference

Train models that do not fit on one GPU, make trained models smaller and faster, and use managed cloud ML platforms.

### Distributed Training

optional · advanced · about 10 h · https://www.internhack.in/roadmaps/tracks/machine-learning/distributed-training

Data, model and pipeline parallelism with PyTorch DDP, FSDP and DeepSpeed for training across many GPUs and machines.

When a model takes days on one GPU, or simply does not fit in its memory, you spread the work across devices. The options differ in what gets split.

#### Kinds of parallelism
- **Data parallelism**: every GPU holds a full model copy, processes a different slice of the batch, and gradients are averaged with an **all-reduce**. PyTorch **DistributedDataParallel (DDP)** is the standard.
- **Sharded data parallelism**: **FSDP** and **DeepSpeed ZeRO** split parameters, gradients and optimizer states across GPUs so much larger models fit.
- **Tensor (model) parallelism** splits individual layers across devices.
- **Pipeline parallelism** places different layers on different devices and streams micro-batches through them.

Large language model training combines all of these (often called 3D parallelism).

#### Memory tricks on any setup
Mixed precision (bf16), **gradient accumulation** to simulate larger batches, **activation checkpointing** to trade compute for memory, and 8-bit optimizers.

#### Practicalities
- Launch with `torchrun`; use `DistributedSampler` so each process sees different data.
- Scale the learning rate (and warmup) when the global batch grows.
- Only rank 0 should log and save checkpoints.
- Interconnect bandwidth (NVLink, InfiniBand) often limits speedup; measure scaling efficiency.
- **Accelerate**, **Lightning** and **Ray Train** hide much of the boilerplate.

**Good enough to move on** when you can convert a single-GPU script to DDP, train with FSDP on a model that would not fit otherwise, and report the speedup you achieved.

Key concepts: Data parallelism and all-reduce, PyTorch DDP and torchrun, FSDP and DeepSpeed ZeRO, Tensor and pipeline parallelism, Gradient accumulation, Activation checkpointing, Accelerate and Ray Train.

Mini project: Take a transformer fine-tuning script, run it with DDP on 2 or more GPUs (a rented cloud instance is fine), then switch to FSDP with activation checkpointing and record throughput, memory per GPU and final accuracy for each setup.

Self-check: What is kept on every GPU under DDP that FSDP shards instead, and why does that let FSDP train larger models?

Resources:
- [PyTorch distributed overview](https://pytorch.org/tutorials/beginner/dist_overview.html) (PyTorch)
- [Accelerate documentation](https://huggingface.co/docs/accelerate/index) (Hugging Face)
- [DeepSpeed documentation](https://www.deepspeed.ai/) (Microsoft)

### Model Compression and Fast Inference

optional · advanced · about 8 h · https://www.internhack.in/roadmaps/tracks/machine-learning/model-optimization-inference

Quantization, pruning, distillation and export to ONNX or TensorRT to cut latency, memory and serving cost.

Serving cost often exceeds training cost over a model's lifetime, and many devices cannot run a full-size model at all. Making models smaller and faster is a core production skill.

#### Techniques
- **Quantization**: store weights (and sometimes activations) in int8 or 4-bit instead of float32. **Post-training quantization** is quick; **quantization-aware training** recovers more accuracy. For LLMs, formats such as GPTQ, AWQ and GGUF are common.
- **Pruning**: remove weights or whole channels with little impact. Structured pruning gives real speedups; unstructured sparsity needs hardware support.
- **Knowledge distillation**: train a small student model to mimic a large teacher's soft predictions. DistilBERT is a well-known example.
- **Architecture choice**: an efficient model (MobileNet, a smaller transformer) often beats compressing a huge one.

#### Export and runtimes
- **ONNX** is a portable model format; **ONNX Runtime** runs it fast on CPUs and GPUs.
- **TensorRT** compiles models for NVIDIA GPUs; **OpenVINO** targets Intel hardware; **Core ML** and **LiteRT** target mobile.
- `torch.compile` and `torch.export` optimize within PyTorch.

#### Measure everything
Benchmark latency (p50 and p99), throughput, memory and accuracy before and after each change, on the hardware you will actually deploy to. A 4x smaller model that loses 5 points of accuracy may or may not be worth it; that is a product decision, so present the trade-off clearly.

**Good enough to move on** when you can quantize and export a model to ONNX, benchmark it against the original, and explain the accuracy and speed trade-off.

Key concepts: Post-training quantization, Quantization-aware training, Pruning, Knowledge distillation, ONNX and ONNX Runtime, TensorRT and OpenVINO, Latency benchmarking.

Mini project: Export a fine-tuned image or text classifier to ONNX, apply int8 dynamic quantization, and build a table comparing file size, CPU latency, throughput and accuracy for PyTorch, ONNX and quantized ONNX versions.

Self-check: What does knowledge distillation transfer from the teacher that plain training on hard labels does not, and why might structured pruning speed up inference more than unstructured pruning?

Resources:
- [ONNX Runtime documentation](https://onnxruntime.ai/docs/) (Microsoft)
- [PyTorch tutorials](https://pytorch.org/tutorials/) (PyTorch)
- [Hugging Face Optimum documentation](https://huggingface.co/docs/optimum/index) (Hugging Face)

### Cloud ML Platforms

optional · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/machine-learning/cloud-ml-platforms

Managed notebooks, training jobs, endpoints and pipelines on AWS SageMaker, Google Vertex AI and Azure Machine Learning.

Most companies run ML on a cloud provider. The big three offer similar building blocks under different names, so learning one deeply makes the others easy to pick up.

#### Common building blocks
- **Storage**: object stores (S3, GCS, Azure Blob) for datasets and artifacts; warehouses (Redshift, BigQuery, Synapse) for tables.
- **Managed notebooks** with attachable GPUs.
- **Training jobs**: submit a container or script, pick instance types, get logs and artifacts; supports spot instances and distributed training.
- **Hyperparameter tuning** services.
- **Model registry and endpoints** with autoscaling, plus batch transform jobs.
- **Pipelines** and **monitoring** services that mirror the open-source tools you learned earlier.
- **Foundation model hubs** (Bedrock, Vertex AI Model Garden, Azure AI Foundry) for hosted LLMs.

#### Skills that transfer
- **IAM**: roles and least-privilege permissions for jobs and endpoints.
- **Cost control**: GPU hours are expensive. Use spot or preemptible instances with checkpointing, shut down idle notebooks, set budgets and alerts.
- **Infrastructure as code** (Terraform) to recreate environments.
- **Portability**: keep your training code as plain Python in a container so you are not locked into one SDK.

Free tiers and credits for students exist on all major clouds; Kaggle and Colab give free GPUs for experiments.

**Good enough to move on** when you can launch a training job, deploy an autoscaling endpoint, call it, and tear everything down without surprise bills.

Key concepts: Object storage and warehouses, Managed training jobs, Managed endpoints and autoscaling, IAM roles and permissions, Spot instances and cost control, SageMaker, Vertex AI or Azure ML, Terraform for ML infrastructure.

Mini project: On one cloud's free tier or credits, upload data to object storage, run a containerized training job on a spot instance, deploy the model to a managed endpoint, call it from a script, and document the total cost.

Self-check: Why should training on spot or preemptible instances always write checkpoints, and what IAM permissions does a training job minimally need?

Resources:
- [Amazon SageMaker documentation](https://docs.aws.amazon.com/sagemaker/) (AWS)
- [Vertex AI documentation](https://cloud.google.com/vertex-ai/docs) (Google Cloud)
- [Azure Machine Learning documentation](https://learn.microsoft.com/en-us/azure/machine-learning/) (Microsoft)

## Responsible and Trustworthy ML

Explain predictions, measure and reduce unfair outcomes, protect personal data, and document models honestly.

### Explainability with SHAP and LIME

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/machine-learning/explainability

Global and local explanations of model behaviour, from permutation importance and partial dependence to SHAP values and LIME.

Stakeholders, regulators and your own debugging all need to know why a model predicts what it does. Explainability tools answer two different questions: how the model behaves overall (**global**) and why it made this particular prediction (**local**).

#### Global methods
- **Coefficients** of linear models, if features are scaled and not strongly correlated.
- **Impurity-based importance** from trees is fast but biased towards high-cardinality features.
- **Permutation importance**: shuffle one feature on validation data and measure how much the score drops. Model-agnostic and more trustworthy.
- **Partial dependence and ICE plots** show how predictions change as one feature varies.

#### Local methods
- **SHAP** assigns each feature a contribution based on Shapley values from game theory; contributions add up to the difference between the prediction and the average prediction. `TreeExplainer` is exact and fast for gradient boosting; waterfall, beeswarm and dependence plots are the standard views.
- **LIME** fits a simple surrogate model around one prediction by perturbing the input.
- For deep models: **integrated gradients**, Grad-CAM for images, and attention visualizations (with caution).

#### Caveats
Explanations describe the model, not the real world; they do not imply causation. Correlated features split credit in confusing ways. Explanations can also be manipulated, so use them as evidence alongside other checks, and prefer inherently interpretable models when the stakes are high and accuracy allows.

**Good enough to move on** when you can produce global and local SHAP explanations for a gradient boosting model, spot a leaky feature with them, and explain their limits to a non-technical audience.

Key concepts: Global vs local explanations, Permutation importance, Partial dependence and ICE plots, SHAP values and plots, LIME, Integrated gradients, Limits of explanations.

Mini project: Train a LightGBM model on a tabular dataset, compare impurity, permutation and SHAP importance, produce waterfall plots for three individual predictions, and write a one-page explanation for a business reader.

Self-check: Why can impurity-based feature importance mislead, and what does it mean that SHAP values are additive?

Resources:
- [Interpretable Machine Learning](https://christophm.github.io/interpretable-ml-book/) (Christoph Molnar)
- [SHAP documentation](https://shap.readthedocs.io/) (SHAP)
- [scikit-learn: inspection](https://scikit-learn.org/stable/inspection.html) (scikit-learn)

### Fairness and Bias in ML

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/machine-learning/fairness

Where bias enters ML systems, how to measure group fairness, and what mitigation can and cannot fix.

Models learn from historical data, and history contains unequal treatment. A hiring, lending or healthcare model can quietly reproduce or amplify that. Measuring and addressing it is part of doing the job well, and increasingly a legal requirement.

#### Where bias comes from
- **Historical bias**: the labels themselves reflect past unfair decisions.
- **Representation bias**: some groups are under-sampled.
- **Measurement bias**: proxies (arrests for crime, clicks for interest) mean different things for different groups.
- **Proxy features**: removing a protected attribute does not help if postcode or name encodes it.
- **Deployment bias**: using a model in a context it was not built for.

#### Measuring it
Always slice metrics by group. Common definitions:
- **Demographic parity**: similar positive prediction rates across groups.
- **Equal opportunity / equalized odds**: similar true positive (and false positive) rates.
- **Calibration within groups**: a score of 0.7 means the same thing for everyone.

These definitions generally **cannot all hold at once**, so choosing one is a value judgement to make with domain experts and affected people, not a purely technical call.

#### Mitigation
- **Pre-processing**: better data collection, reweighting.
- **In-processing**: fairness constraints during training.
- **Post-processing**: group-specific thresholds.
- Sometimes the right answer is not to automate the decision at all.

**Fairlearn** and **AIF360** provide metrics and mitigation algorithms.

**Good enough to move on** when you can audit a model's metrics across groups, explain why fairness definitions conflict, and document the trade-off you chose.

Key concepts: Sources of bias, Proxy features, Sliced evaluation by group, Demographic parity and equalized odds, Fairness trade-offs, Mitigation strategies, Fairlearn toolkit.

Mini project: Train a classifier on the Adult income or a similar public dataset, report metrics by sex and race with Fairlearn, apply one mitigation method, and write up how accuracy and each fairness metric changed.

Self-check: Why does deleting the protected attribute column usually fail to make a model fair, and why can demographic parity and calibration conflict?

Resources:
- [Fairlearn documentation](https://fairlearn.org/) (Fairlearn)
- [Google Machine Learning Crash Course](https://developers.google.com/machine-learning/crash-course) (Google)
- [Fairness and Machine Learning](https://fairmlbook.org/) (Barocas, Hardt, Narayanan)

### Privacy and Security in ML

optional · advanced · about 5 h · https://www.internhack.in/roadmaps/tracks/machine-learning/privacy-and-security

Protecting personal data in training sets, differential privacy, federated learning, and attacks on models such as adversarial examples and data poisoning.

Training data often contains personal information, and models can leak it. Models can also be attacked. Awareness of both belongs in every ML engineer's toolkit, even if you never specialize in it.

#### Protecting data
- **Data minimization**: collect and keep only what the model needs; drop direct identifiers early.
- **Pseudonymization and access controls** on raw data; remember that anonymized data can often be re-identified by joining with other sources.
- **Regulation**: GDPR, India's DPDP Act and sector rules (health, finance) govern consent, retention and the right to deletion, which affects whether you can keep training on someone's data.

#### Privacy-preserving techniques
- **Differential privacy** adds calibrated noise so the output barely changes whether any one person is included. **DP-SGD** (for example via Opacus) clips and noises gradients during training, at some cost in accuracy.
- **Federated learning** trains on devices and shares only model updates, as in phone keyboards.
- Synthetic data and secure enclaves are other tools, each with limits.

#### Attacks on models
- **Membership inference**: guessing whether a record was in the training set, easier with overfit models.
- **Model inversion and training-data extraction**, a real concern for large generative models.
- **Adversarial examples**: tiny input changes that flip predictions; adversarial training improves robustness.
- **Data poisoning and backdoors** via tampered training data.
- **Prompt injection** against LLM applications.

**Good enough to move on** when you can train a model with DP-SGD and report the privacy-accuracy trade-off, and generate an adversarial example against one of your own models.

Key concepts: Data minimization and PII handling, Privacy regulation basics, Differential privacy and DP-SGD, Federated learning, Membership inference, Adversarial examples, Data poisoning and backdoors.

Mini project: Train an MNIST classifier normally and with Opacus DP-SGD at two privacy budgets, compare accuracy, then run an FGSM adversarial attack on the normal model and plot accuracy against perturbation size.

Self-check: What guarantee does differential privacy give in plain words, and why are overfit models more vulnerable to membership inference?

Resources:
- [Opacus documentation](https://opacus.ai/) (Meta)
- [PyTorch tutorials](https://pytorch.org/tutorials/) (PyTorch)
- [Google Machine Learning Crash Course](https://developers.google.com/machine-learning/crash-course) (Google)

### Model Cards, Datasheets and Governance

recommended · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/machine-learning/model-documentation

Document what a model is for, how it was built and evaluated, and where it should not be used, so others can use it responsibly.

A model without documentation gets reused in ways its builders never intended. Short, structured documents prevent that and make reviews, audits and hand-overs far easier.

#### Model cards
A model card answers:
- **Intended use** and explicitly **out-of-scope uses**.
- **Training data**: source, time range, known gaps.
- **Evaluation**: metrics overall and **sliced by relevant groups**, with the test data described.
- **Limitations, risks and ethical considerations**.
- Version, owners, license and contact.

Hugging Face renders model cards on every model page; writing one for each model you publish is good practice and a signal of maturity to employers.

#### Datasheets for datasets
The dataset counterpart: why it was collected, how, by whom, what consent applies, how it was labelled, recommended uses and maintenance plans.

#### Governance in organizations
- **Risk tiers**: a movie recommender and a loan approval model deserve different review depth.
- **Review checklists** before launch: fairness audit, privacy review, security review, monitoring plan.
- **Regulation**: the EU AI Act classifies systems by risk and imposes documentation, logging and human oversight duties on high-risk uses; other regions are following.
- **Human oversight and appeal paths** for people affected by automated decisions.

**Good enough to move on** when every model in your portfolio has a model card that a reader could use to decide whether it fits their use case.

Key concepts: Model card sections, Intended and out-of-scope uses, Datasheets for datasets, Risk tiers and review checklists, EU AI Act basics, Human oversight and appeals.

Mini project: Write a full model card for your best portfolio model (including sliced metrics and out-of-scope uses) and a datasheet for its dataset, and publish both with the model on the Hugging Face Hub or in the repo.

Self-check: What belongs in the out-of-scope uses section of a model card, and why is it as important as the intended use?

Resources:
- [Hugging Face: model cards](https://huggingface.co/docs/hub/model-cards) (Hugging Face)
- [Model Cards for Model Reporting (paper)](https://arxiv.org/abs/1810.03993) (arXiv)

## Kaggle, Research Papers and Staying Current

Sharpen skills against real leaderboards, learn to read and reproduce papers, and keep up with a fast-moving field without drowning.

### Kaggle and Competitive ML

recommended · intermediate · about 20 h · https://www.internhack.in/roadmaps/tracks/machine-learning/kaggle-competitions

Use Kaggle's free courses, datasets, notebooks and competitions to practise end-to-end modelling under honest evaluation.

Kaggle offers free GPUs, thousands of datasets, short courses and competitions with hidden test sets. A leaderboard is an honest judge: you cannot fool yourself about whether a change helped.

#### Getting started
- Work through the **Kaggle Learn** micro-courses to fill gaps quickly.
- Enter **Getting Started** and **Playground** competitions (Titanic, House Prices, monthly tabular playgrounds) where the pressure is low.
- Read top public notebooks after you have tried yourself, and ask why their choices work.

#### A competition workflow
1. Read the rules, the metric and the data description carefully.
2. Build a **validation scheme that mirrors the test split** (grouped, time-based or stratified). Trust your CV more than the public leaderboard, which is often a small sample.
3. Create a fast baseline and a submission pipeline on day one.
4. Iterate: EDA, features, model families, tuning, one change at a time with logged results.
5. **Ensemble** diverse models (blending, stacking) near the end.

#### What transfers to jobs and what does not
Competitions teach validation discipline, feature engineering and fast iteration. They skip problem framing, data collection, deployment and maintenance, and they reward tiny metric gains that no business would pay for. Balance them with end-to-end projects.

#### Community
Writing clear public notebooks and discussion posts builds a visible track record. Kaggle progression tiers (Expert, Master) are recognized by many recruiters.

**Good enough to move on** when you have finished at least two competitions with a validation scheme you trust and a written summary of what worked.

Key concepts: Kaggle Learn micro-courses, Playground competitions, Validation that mirrors the test set, Public vs private leaderboard, Ensembling and stacking, Publishing notebooks, Team competitions.

Mini project: Enter a current Kaggle Playground competition, set up a CV scheme and baseline on day one, log at least 15 experiments, finish with an ensemble, and publish a clean notebook explaining your approach.

Self-check: Why can climbing the public leaderboard hurt your final private leaderboard rank, and how does a good CV scheme protect you?

Resources:
- [Kaggle Learn](https://www.kaggle.com/learn) (Kaggle)
- [Kaggle competitions](https://www.kaggle.com/competitions) (Kaggle)

### Reading and Reproducing Research Papers

recommended · advanced · about 12 h · https://www.internhack.in/roadmaps/tracks/machine-learning/reading-papers

A repeatable method for reading ML papers, judging their claims, and reimplementing key results.

Much of ML knowledge first appears in papers on arXiv and at conferences such as NeurIPS, ICML, ICLR, CVPR and ACL. Being able to read them turns you from a user of tools into someone who understands where they come from.

#### A three-pass approach
- **Pass 1 (10 minutes)**: title, abstract, figures, conclusion. What problem, what claim, is it relevant?
- **Pass 2 (an hour)**: introduction, method overview, experiments. Note the baselines, datasets and metrics. Skip proofs.
- **Pass 3 (hours)**: work through the maths and details as if you had to reimplement it. Write down every question.

#### Reading critically
- Are the **baselines** strong and tuned fairly, or weak straw men?
- Are gains larger than **run-to-run variance**? Are error bars or multiple seeds reported?
- Do **ablations** show which component actually matters?
- Would it hold on your data, scale or compute budget?

#### Reproducing
Pick a well-known paper with a small-scale experiment and reimplement the core idea yourself before looking at the official code. Matching a reported number (or understanding why you cannot) teaches more than reading ten papers. Write a short blog post or README summarizing the method, your results and surprises.

#### Staying current without burnout
Follow a few curated sources (newsletters, reading groups, researchers you trust), keep a paper log, and go deep on your area rather than skimming everything. Survey papers and good blog explainers are efficient entry points.

**Good enough to move on** when you can summarize a new paper's contribution and weaknesses in a paragraph and have reproduced at least one result yourself.

Key concepts: Three-pass reading method, Finding papers on arXiv, Judging baselines and ablations, Variance and statistical significance, Reimplementing a paper, Writing paper summaries, Reading groups.

Mini project: Choose a classic paper (for example ResNet, Dropout, or Attention Is All You Need), reimplement its main experiment at small scale, compare your numbers with the paper's, and publish a write-up with your code.

Self-check: What three things would you check in a paper's experiment section before believing its claimed improvement?

Resources:
- [arXiv machine learning listings](https://arxiv.org/list/cs.LG/recent) (arXiv)
- [How to Read a Paper (S. Keshav)](https://web.stanford.edu/class/ee384m/Handouts/HowtoReadPaper.pdf) (Stanford)
- [Distill](https://distill.pub/) (Distill)

## Portfolio, Interviews and Capstone

Package your skills into evidence employers trust: end-to-end projects, ML system design practice, interview preparation and a final capstone.

### Building an ML Portfolio

core · intermediate · about 20 h · https://www.internhack.in/roadmaps/tracks/machine-learning/ml-portfolio

Choose, build and present a few deep, end-to-end projects that show judgement, not just model accuracy.

Recruiters and hiring managers see hundreds of Titanic and MNIST notebooks. What stands out is a small number of projects that look like real work: a genuine problem, messy data, sensible evaluation, and something that runs.

#### Choosing projects
- **Own the problem**: pick data you care about or collected yourself (scraped, from an API, from a hobby).
- **Cover different skills**: for example one tabular project with strong evaluation, one deep learning project (vision or NLP), and one deployed, monitored service.
- **Depth beats breadth**: three excellent projects outperform fifteen tutorials.

#### What each project should show
- A clear **problem statement** and why it matters.
- **Baselines** and a justified metric.
- Honest **error analysis**: where the model fails and why.
- Reproducible code: README, environment file, one-command training.
- A **demo**: a Hugging Face Space, Streamlit app or API endpoint.
- A short **write-up** or blog post explaining decisions and trade-offs.

#### Presenting it
Pin the best repos on GitHub, keep a simple portfolio page, and link it from your resume. On the resume, describe impact and scope ("reduced forecast error 18 percent against seasonal baseline"), not just tools. Open-source contributions to libraries like scikit-learn or Hugging Face, and clear Kaggle notebooks, are strong additional signals.

**Good enough to move on** when you have at least two polished, deployed projects with write-ups that a stranger could understand in five minutes.

Key concepts: Choosing original problems, Baselines and error analysis, Reproducible repositories, Live demos (Spaces, Streamlit), Project write-ups and blogs, Open-source contributions, Resume impact statements.

Mini project: Audit your existing projects against the checklist above, pick the best two, and bring each up to standard: README, one-command training, live demo, model card and a 600-word write-up.

Self-check: If a hiring manager spends two minutes on one of your repos, what should they learn about your judgement, and where in the repo will they find it?

Resources:
- [Hugging Face Spaces documentation](https://huggingface.co/docs/hub/spaces) (Hugging Face)
- [Made With ML](https://madewithml.com/) (Made With ML)
- [Practical Deep Learning for Coders](https://course.fast.ai/) (fast.ai)

### ML System Design

recommended · advanced · about 10 h · https://www.internhack.in/roadmaps/tracks/machine-learning/ml-system-design

Design full ML systems from business goal to monitoring, the way senior engineers and system design interviews expect.

ML system design asks: given a product goal, how would you build, ship and maintain an ML solution? It tests judgement across the whole lifecycle, which is exactly what distinguishes an ML engineer from someone who only trains models.

#### A framework to walk through
1. **Clarify the goal**: business objective, users, constraints (latency, scale, privacy). Is ML even needed, or would a rule do?
2. **Frame the ML task**: inputs, outputs, type of problem, and an offline metric that tracks the business metric.
3. **Data**: sources, labelling strategy, volume, freshness, bias risks.
4. **Features and model**: start with a simple baseline, then justify complexity.
5. **Training pipeline**: splits, retraining cadence, evaluation gates.
6. **Serving**: batch or online, latency budget, candidate generation plus ranking for large catalogues, caching.
7. **Evaluation online**: A/B tests and guardrail metrics.
8. **Monitoring and iteration**: drift, feedback loops, failure modes, fallbacks.

#### Classic practice prompts
Design a news feed ranker, a fraud detector, a search ranking system, a people-you-may-know feature, an ETA predictor, a content moderation pipeline, or a RAG-based support assistant.

#### Tips
Think out loud, state assumptions with numbers (requests per second, catalogue size), discuss trade-offs rather than naming tools, and always cover how you would know the system is working after launch.

**Good enough to move on** when you can talk through a complete design for any classic prompt in 40 minutes, including metrics, data, serving and monitoring.

Key concepts: Clarifying goals and constraints, Offline vs online metrics, Data and labelling strategy, Candidate generation and ranking, Latency and scale estimates, A/B testing and guardrails, Failure modes and fallbacks.

Mini project: Write two-page design docs for three classic prompts (for example fraud detection, feed ranking and ETA prediction) using the framework above, then do a timed mock design session with a peer and collect feedback.

Self-check: For a fraud detection system, which offline metric would you optimize, which business metric would you watch in an A/B test, and why might they disagree?

Resources:
- [Introduction to Machine Learning Interviews Book](https://huyenchip.com/ml-interviews-book/) (Chip Huyen)
- [Rules of Machine Learning](https://developers.google.com/machine-learning/guides/rules-of-ml) (Google)
- [Made With ML](https://madewithml.com/) (Made With ML)

### Preparing for ML Interviews

recommended · intermediate · about 15 h · https://www.internhack.in/roadmaps/tracks/machine-learning/ml-interviews

What ML engineer and data scientist interviews test: fundamentals, coding, ML design, project deep dives and behavioural rounds.

ML hiring loops vary by company, but the rounds usually come from a common menu. Knowing it lets you prepare deliberately instead of hoping.

#### Typical rounds
- **ML fundamentals**: bias-variance, regularization, metrics, how gradient boosting or attention works, handling imbalance and leakage. Expect "why" and "what if" follow-ups.
- **Coding**: data structures and algorithms in Python (often LeetCode easy to medium), plus ML coding such as implementing k-means, logistic regression with gradient descent, or a training loop from scratch.
- **Data manipulation**: pandas and SQL questions on realistic tables, common for data scientist roles.
- **Statistics and probability**: A/B test design, p-values, conditional probability puzzles.
- **ML system design** for mid-level and above.
- **Project deep dive**: you will be asked to defend decisions in your own projects in detail.
- **Behavioural**: collaboration, handling ambiguity, a time a model failed.

#### Preparing
- Build a one-page cheat sheet per core topic and explain each aloud.
- Implement 8 to 10 classic algorithms from scratch in NumPy.
- Prepare **STAR stories** for your top projects, including numbers and what you would do differently.
- Do timed mock interviews with peers; being clear under time pressure is a skill.
- Research each company's products and guess how they use ML.

#### Roles differ
Data scientist loops lean on statistics, SQL and product sense; ML engineer loops lean on coding, systems and deployment; research roles emphasize papers and maths.

**Good enough to move on** when you can explain any topic in this roadmap in two minutes, code classic algorithms from scratch, and tell a crisp story about each portfolio project.

Key concepts: ML fundamentals questions, Coding and algorithms, Algorithms from scratch in NumPy, SQL and pandas rounds, Statistics and A/B testing, Project deep dives, Behavioural STAR stories, Mock interviews.

Mini project: Over two weeks, implement linear regression, logistic regression, k-means, kNN, a decision tree and a two-layer neural network from scratch in NumPy with tests, and complete four timed mock interviews covering fundamentals, coding and design.

Self-check: Explain, in under two minutes and without jargon, how gradient boosting builds its ensemble and why it can overfit.

Resources:
- [Introduction to Machine Learning Interviews Book](https://huyenchip.com/ml-interviews-book/) (Chip Huyen)
- [Google Machine Learning Crash Course](https://developers.google.com/machine-learning/crash-course) (Google)

### Capstone: An End-to-End ML System

core · advanced · about 45 h · https://www.internhack.in/roadmaps/tracks/machine-learning/ml-capstone

Design, build, deploy and monitor one complete ML product that ties together everything in this roadmap.

The capstone is your proof that you can take an ML idea from a blank page to a system real users could rely on. Treat it like a job: scope it, plan it, ship it and write it up.

#### Requirements
- **A real problem** with a clear user and success metric, ideally with data you gathered or combined yourself.
- **Data work**: ingestion, validation, EDA and a leakage-safe split, all versioned.
- **Modelling**: a simple baseline, at least one stronger model (classical or deep), tuned and evaluated with cross-validation or a proper backtest.
- **Responsible ML**: sliced metrics, explanations and a model card.
- **Engineering**: a package with tests, experiment tracking, and a pipeline that retrains from one command or a schedule.
- **Deployment**: a containerized API or batch job plus a small user-facing demo.
- **Operations**: logging, a drift report and alerts.

#### Example directions
- A price or demand forecaster for a local market with weekly retraining.
- A document classifier or semantic search tool for a domain you know.
- A vision model that inspects photos for a hobby or small business need.
- A job or course recommender with a two-stage retrieval and ranking design.

#### Deliverables
A public repository, a live demo, a design document written before you started (and updated after), and a final write-up covering results, failures and what you would do next. Present it to peers and invite hard questions; you will face the same ones in interviews.

**Done** when a stranger can read your write-up, try your demo, rerun your pipeline and understand every major decision you made.

Key concepts: Problem scoping and design doc, Versioned data pipeline, Baseline and improved models, Responsible ML checks, Automated retraining, Deployed API and demo, Monitoring and drift alerts, Final write-up and presentation.

Mini project: Build and ship the capstone described above: design doc, versioned data, baseline and tuned models, model card, containerized serving with a demo, monitoring, and a public write-up presented to at least three peers.

Self-check: Could someone else rerun your capstone from scratch using only your README, and could you defend every modelling and engineering choice in an interview?

Resources:
- [Made With ML](https://madewithml.com/) (Made With ML)
- [Rules of Machine Learning](https://developers.google.com/machine-learning/guides/rules-of-ml) (Google)
- [Full Stack Deep Learning](https://fullstackdeeplearning.com/) (FSDL)

## Related

- [Career roadmaps](https://www.internhack.in/roadmaps)
