AI & Data
From the maths and Python basics to classical models, evaluation and deep learning architectures.
A path for developers who want to become machine learning engineers. It starts with the linear algebra, calculus, probability and statistics you actually need, then Python and its data stack, classical supervised and unsupervised models with scikit-learn, honest evaluation, and deep learning from basic networks to CNNs, Transformers and NLP. Each subject links the official documentation or a well-known free text.
The subjects follow the roadmap.sh Machine Learning roadmap.
Machine learning engineering is the work of turning data and models into reliable software: collecting and cleaning data, training and evaluating models, and shipping them behind an API or a batch job that keeps working as the data drifts.
An engineer who sits between data science and software engineering: they take a model from notebook to production, owning data pipelines, training jobs, serving, monitoring and retraining.
ML engineers usually train their own models on their own data; AI engineers more often build products on top of pretrained foundation models through APIs, prompting, retrieval and fine-tuning. The skills overlap heavily.
Solid Python and SQL, the maths behind the models, experiment tracking, testing data as well as code, containerising and serving models, and watching production metrics for drift.
Data is stored as vectors and matrices, and nearly every model is a chain of matrix multiplications. You need it to read papers, shape tensors correctly and understand methods like PCA.
A scalar is one number, a vector a 1-D array, a matrix 2-D, and a tensor any number of axes. In code these map to NumPy arrays and PyTorch tensors with a shape and dtype.
Addition, scalar multiplication, transpose, element-wise products and matrix multiplication (@ in NumPy). Know when shapes are compatible and that A @ B is not B @ A.
The determinant tells you whether a square matrix is invertible and how it scales volume. In practice you rarely compute an inverse; use np.linalg.solve for stability.
Eigenvectors are directions a matrix only stretches; eigenvalues are the stretch factors. Diagonalising a covariance matrix is exactly what PCA does.
Factorises any matrix into U Σ Vᵀ. It underlies PCA, low-rank approximation, recommender systems and solving least squares robustly.
Training a model means minimising a loss by following its slope. Derivatives tell you which way to move each parameter, and frameworks compute them for you with automatic differentiation, but you still need the ideas to debug training.
A derivative is the rate of change of a function; a partial derivative holds every other variable fixed. A loss has one partial per parameter.
The derivative of a composition is the product of derivatives along the chain. Backpropagation is the chain rule applied layer by layer from the loss back to the inputs.
The gradient collects first derivatives of a scalar function, the Jacobian does it for vector outputs, and the Hessian holds second derivatives that describe curvature, used by second-order optimisers.
Sets, logic, combinatorics and graphs show up in feature encoding, counting probabilities, decision trees and graph-based models. A working comfort with them makes algorithm analysis and probability far easier.
Models output probabilities, losses like cross-entropy come from likelihoods, and uncertainty is everywhere in real data. Learn to reason about events, conditional probability and distributions.
Sample spaces, events, independence, conditional probability and expectation. Most modelling mistakes trace back to confusing P(A|B) with P(B|A).
Updates a prior belief with evidence to get a posterior. It powers Naive Bayes classifiers and explains why a test with high accuracy can still mislead on rare events.
A random variable maps outcomes to numbers; discrete ones have a probability mass function, continuous ones a density whose integral over a range gives a probability.
Bernoulli, binomial, Poisson, uniform, normal and exponential cover most practical cases. Knowing which fits your data guides loss choice and anomaly thresholds.
Statistics turns samples into conclusions: summarising data, estimating quantities, testing whether a difference is real and plotting so you see problems before a model hides them.
Population versus sample, parameters versus statistics, bias and variance of estimators, and why sampling method matters as much as sample size.
Mean, median, mode, variance, standard deviation, percentiles and correlation. df.describe() in pandas is the first thing to run on a new dataset.
Confidence intervals, hypothesis tests and p-values let you judge whether a model or A/B result generalises beyond the sample you happened to collect.
Histograms for distributions, box plots for outliers, scatter plots for relationships and heatmaps for correlation matrices. Plot before modelling, every time.
The default language of machine learning, thanks to NumPy, pandas, scikit-learn and PyTorch. Write clean scripts and modules, use virtual environments, and do not live only in notebooks.
The core language you will use every day for data wrangling: variables, control flow, functions, collections and error handling. Idiomatic Python (comprehensions, unpacking, enumerate) keeps data code short and readable.
Names bound to objects of type int, float, str, bool and None. Floats are binary approximations, so compare them with a tolerance.
if / elif / else, truthiness rules and the match statement for structural pattern matching.
for over any iterable and while with break/continue. In numeric code, prefer vectorised NumPy operations over Python loops for speed.
try / except / finally, raising your own errors and catching specific exception types rather than a bare except.
Define with def, use default and keyword arguments, and lean on built-ins like len, sorted, zip, map and sum.
Lists, tuples, dicts and sets, plus collections helpers like Counter and defaultdict. Choose by access pattern: dict and set lookups are constant time.
Classes, inheritance and dunder methods are how ML libraries are built: scikit-learn estimators share fit/predict, and PyTorch models subclass nn.Module. Knowing OOP lets you write your own transformers and models that plug into them.
The scientific Python stack every ML project uses: NumPy for arrays, pandas for tables, Matplotlib and Seaborn for plots. Fluency here is most of the day-to-day work.
N-dimensional arrays with vectorised maths, broadcasting and linear algebra. Learn indexing, slicing, reshape, axis arguments and how broadcasting aligns shapes.
DataFrames for tabular data: loading files, filtering, groupby, joins, reshaping and handling missing values. Watch for silent dtype changes and chained-assignment pitfalls.
The base plotting library. Use the object-oriented API (fig, ax = plt.subplots()) for anything beyond a quick plot.
Statistical plots on top of Matplotlib that work directly with DataFrames: distributions, pair plots, regression fits and heatmaps in one call.
Models are only as good as their data, and data comes from many places with different reliability, freshness and licensing. Record where every dataset came from and how it was collected.
Most business data lives in relational databases; query it with SQL and load results with pandas.read_sql. Document and key-value stores hold logs and semi-structured events.
Public datasets (Hugging Face, UCI, Kaggle) and scraped web pages. Check licences and robots rules, and expect noise and duplicates.
Pull data from REST or GraphQL services with requests or httpx, respecting rate limits and paginating carefully.
App telemetry, user events and on-device sensor data. Mind consent and privacy rules, and that client clocks and versions vary.
Streams of sensor readings from devices, often time series with gaps, drift and irregular sampling that need resampling before modelling.
The file format decides how fast you can load data, whether types survive, and how much disk it takes. Text formats are easy to inspect; columnar binary formats are what you want at scale.
Plain comma-separated text, universal but untyped. Specify dtype, separators and encoding in read_csv to avoid silent parsing surprises.
Nested key-value text common from APIs. Flatten nested records with pd.json_normalize; JSON Lines (one object per line) streams better for large files.
Columnar, compressed and typed. Reads only the columns you need and is the standard for analytics and data lakes.
Spreadsheets from business users, read with pd.read_excel. Expect merged cells, multiple header rows and dates stored as numbers.
Images, audio and video files, HDF5 for large arrays, Avro and Feather for pipelines, TFRecord for TensorFlow input. Pick based on the tools that read it.
Raw data rarely fits a model directly. Cleaning, transforming and selecting features often matter more than the choice of algorithm, and every step must be fit on training data only to avoid leakage.
Handle missing values, duplicates, inconsistent categories, wrong types and outliers. Decide whether to drop, impute or flag, and document the choice.
Create informative inputs: date parts, ratios, aggregates, text counts, one-hot or target encodings. Domain knowledge is the main source of good features.
Drop irrelevant or redundant features with filter methods, recursive elimination or model-based importance to reduce overfitting and training time.
Standardise (StandardScaler) or rescale to a range (MinMaxScaler) so distance- and gradient-based models are not dominated by large-valued features. Tree models do not need it.
Instead of writing rules, you give an algorithm examples and it fits a function that generalises to new data. The core loop is: choose a model family, define a loss, optimise on training data, and measure on data the model has never seen.
Paradigms differ in what feedback the learner gets: labels, no labels, a few labels, labels derived from the data itself, or rewards from an environment.
Learn a mapping from inputs to known labels; classification for categories, regression for numbers.
Find structure in unlabelled data: clusters, lower-dimensional representations or anomalies.
Combine a small labelled set with lots of unlabelled data, for example by self-training on confident predictions or label propagation.
Create labels from the data itself, such as predicting masked words or the next token. It is how large language and vision models are pretrained.
An agent acts in an environment and learns from rewards rather than labels, trading off exploring new actions against exploiting known good ones.
The standard library for classical ML in Python. Every estimator shares fit, predict and transform, and Pipeline chains preprocessing and model so the same steps run in training and inference.
Toy and real datasets via sklearn.datasets (load_iris, fetch_openml), or any NumPy array or pandas DataFrame you load yourself.
Transformers such as SimpleImputer, OneHotEncoder and StandardScaler, combined per column type with ColumnTransformer inside a Pipeline.
train_test_split holds out data for an honest estimate. Use stratify=y for imbalanced classes and a time-based split for temporal data.
Compare candidate estimators with cross-validation on the training set, keeping the test set untouched until the very end.
Search hyperparameters with GridSearchCV, RandomizedSearchCV or successive halving, scoring with the metric you actually care about.
predict for labels, predict_proba for calibrated-ish probabilities. Persist the whole fitted pipeline (for example with joblib) so inference applies identical preprocessing.
Given pairs of inputs and correct outputs, learn a function that predicts the output for new inputs. The quality of labels and how well the training set represents production data set the ceiling on performance.
Predict a discrete class, binary or multi-class. Start with a simple baseline, watch for class imbalance, and choose a decision threshold based on the cost of each kind of error.
A linear model passed through a sigmoid to output probabilities, trained with log loss. Fast, interpretable and a strong baseline.
Find the maximum-margin boundary between classes; kernels like RBF allow non-linear boundaries. Needs scaled features and gets slow on large datasets.
Classify by majority vote of the k closest training points. No training step, but prediction cost grows with data and it suffers in high dimensions.
Trees split on feature thresholds and are easy to read but overfit; a random forest averages many trees trained on bootstrapped data and random feature subsets.
Build trees sequentially, each fixing the previous errors. XGBoost, LightGBM and HistGradientBoostingClassifier usually win on tabular data.
Predict a continuous value such as a price or duration. Check residual plots, not just a single score, and add regularisation when features are many or correlated.
Fit a weighted sum of features by minimising squared error. Assumes a linear relationship and is sensitive to outliers.
Linear regression on polynomial features (PolynomialFeatures) to model curves. Higher degrees overfit quickly, so pair it with regularisation.
Adds an L2 penalty that shrinks coefficients toward zero, stabilising the fit when features are correlated.
An L1 penalty that drives some coefficients exactly to zero, giving built-in feature selection.
Mixes L1 and L2 penalties via l1_ratio, keeping Lasso sparsity while handling groups of correlated features better.
Learning from data without labels: grouping similar items, compressing features, detecting outliers. Results are harder to evaluate, so combine metrics with domain review.
Group points so items in a cluster are more similar to each other than to others. Algorithms differ in whether a point belongs to one cluster, several, or a tree of nested groups.
Hard clustering: each point belongs to exactly one cluster, as in k-means. Choose k with the elbow method or silhouette score.
A point can belong to several clusters with different degrees, as in fuzzy c-means. Useful when categories genuinely blend.
Builds a tree of merges (agglomerative) or splits; cut the dendrogram at the level that suits the question. Linkage choice changes results a lot.
Model the data as a mixture of distributions, such as Gaussian mixture models fitted with expectation-maximisation, giving a probability of membership for each cluster.
Compress many features into fewer while keeping the important structure, for visualisation, speed or noise removal. Linear methods like PCA come first; t-SNE and UMAP are for visualising, not as model inputs.
Projects data onto the orthogonal directions of greatest variance. Scale features first and use explained_variance_ratio_ to choose how many components to keep.
An agent observes a state, takes an action and receives a reward, learning a policy that maximises long-term return. Used in games, robotics, recommendation and fine-tuning language models from feedback.
Learns the value of each state-action pair by bootstrapping from the best next action. Works with a table when states are few.
Replace the Q-table with a neural network, stabilised with experience replay and a target network; the approach behind the Atari results.
Optimise the policy directly by following the gradient of expected return, as in REINFORCE and PPO. Handles continuous actions naturally.
An actor proposes actions while a critic estimates value to reduce gradient variance; A2C, PPO and SAC are in this family.
Measuring how well a model will perform on data it has not seen, using held-out data and metrics that reflect the real-world cost of mistakes.
Training scores always look good; only honest evaluation reveals overfitting, leakage and bias against subgroups. It is also how you decide whether a new model is worth shipping over the current one.
Pick metrics that match the problem: accuracy misleads on imbalanced data, threshold-free metrics compare rankers, and probabilistic metrics reward calibration. Report more than one.
Share of correct predictions. Fine for balanced classes, useless when 99% of cases are one class.
Of everything predicted positive, how much really was. Optimise it when false alarms are expensive.
Of all real positives, how many were found. Optimise it when missing a case is costly, such as fraud or disease screening.
Harmonic mean of precision and recall; a single number for imbalanced problems. Use average= carefully in multi-class settings.
Area under the true-positive vs false-positive curve across all thresholds; the chance a random positive ranks above a random negative. Prefer PR-AUC under heavy imbalance.
Penalises confident wrong probabilities heavily, so it measures calibration as well as ranking. It is also the training loss of logistic regression.
Counts of true and false positives and negatives per class; every classification metric above is derived from it. Plot it to see which classes get confused.
Ways of splitting data so the score you report reflects unseen data. Resampling gives a mean and spread rather than one lucky number.
Split into k folds, train on k−1 and validate on the rest, rotating. Use StratifiedKFold for classification, GroupKFold when rows share an entity and TimeSeriesSplit for time data.
Leave-one-out: every single sample is the validation set once. Nearly unbiased but costly and high-variance; only sensible for very small datasets.
Layers of weighted sums followed by non-linearities, trained by gradient descent on a loss. Understanding the forward pass, backpropagation and how activations and losses are chosen explains most training failures.
A perceptron is one linear unit with a threshold; stacking layers of units with non-linear activations gives an MLP that can approximate complex functions.
Pass inputs through each layer in order, computing activations, up to the output and the loss. In PyTorch this is the forward method of an nn.Module.
Apply the chain rule backward from the loss to get every weight's gradient, then update with an optimiser. Frameworks do this with loss.backward().
Non-linearities such as ReLU, GELU, sigmoid, tanh and softmax. Without them a deep network collapses into one linear layer; saturating ones cause vanishing gradients.
The quantity training minimises: mean squared error for regression, cross-entropy for classification, and specialised losses for ranking or contrastive learning.
Network designs that build in assumptions about the data: convolutions for spatial grids, recurrence for sequences, attention for relations between any positions, and encoder-decoder or adversarial setups for generation.
Frameworks that give you tensors on GPUs, automatic differentiation and ready-made layers. PyTorch dominates research and much of industry; pick one and learn it well.
Define models as Python classes, write explicit training loops and debug with ordinary Python. torch.compile speeds up models without rewriting them.
Google's framework with a strong deployment story through TF Serving and TensorFlow Lite (now LiteRT) for mobile and edge.
A high-level API where model.fit handles the training loop. Keras 3 runs on TensorFlow, JAX or PyTorch backends.
CNNs slide small learned filters across an image, sharing weights so the same pattern is detected anywhere. Stacked layers build from edges to textures to objects with far fewer parameters than dense layers.
A filter multiplied element-wise with each patch of the input and summed, producing a feature map. Channels let each layer learn many filters at once.
Downsamples feature maps by taking the max or average over small windows, adding some translation tolerance and cutting computation.
Adds border values (usually zeros) so filters can cover the edges and output size can match input size (padding="same").
How many pixels the filter moves each step. A stride above one shrinks the output and can replace pooling.
Most real vision work starts from a pretrained backbone and fine-tunes it on your data. The same building blocks also apply to audio spectrograms and other grid-like signals.
Assign one label per image. Fine-tune a pretrained ResNet or EfficientNet with data augmentation rather than training from scratch.
Label every pixel, either by class (semantic) or per object (instance). U-Net and Mask R-CNN are the classic architectures.
Detect and locate objects with bounding boxes, track them across frames and recognise actions in video clips.
Rank items for users from interaction history and content features; CNNs contribute by embedding images and other item content.
RNNs process a sequence one step at a time while carrying a hidden state. Largely replaced by Transformers for language, they remain useful for small streaming and time-series models.
The plain recurrent cell. Training through many steps causes vanishing or exploding gradients, so it struggles with long-range dependencies.
Adds a cell state with input, forget and output gates so information can persist across long sequences.
A lighter gated cell with update and reset gates; often matches LSTM accuracy with fewer parameters.
Attention lets each position weigh every other position by learned relevance instead of squeezing a sequence through one hidden state. It is the core of modern language, vision and multimodal models.
The original idea from machine translation: a decoder looks back at all encoder states and takes a weighted average based on query-key similarity.
Queries, keys and values all come from the same sequence, computed as softmax(QKᵀ/√d)V. Cost grows quadratically with sequence length.
Runs several attention heads in parallel on different learned projections, then concatenates them, letting the model track different relations at once.
Stacks of self-attention and feed-forward blocks with residual connections and layer norm. Encoder-only (BERT), decoder-only (GPT-style) and encoder-decoder (T5) variants cover most NLP.
An encoder compresses input to a small latent code and a decoder reconstructs it; training on reconstruction error learns useful representations. Used for non-linear dimensionality reduction, denoising and anomaly detection, and in variational form for generation.
A generator makes fake samples and a discriminator tries to tell them from real ones; competing pushes the generator toward realistic output. Training is unstable (mode collapse), and diffusion models have overtaken GANs for most image generation.
Turning text into something models can use and back. Classic pipelines normalise and count words; modern ones tokenise into subwords and feed pretrained Transformers.
Splitting text into units. Word tokenisers handle classic models; subword schemes like BPE and WordPiece keep vocabularies small and handle unseen words.
Chops words to a crude root with rules (Porter, Snowball), so "running" becomes "run". Fast but can produce non-words.
Reduces words to their dictionary form using vocabulary and part of speech, so "better" becomes "good". Slower than stemming but more accurate.
Dense vectors where similar meanings sit close together, from word2vec and GloVe to contextual Transformer embeddings used for search and clustering.
Techniques that show why a model made a prediction, for debugging, trust and regulatory needs. Start with permutation importance and partial dependence, then SHAP for per-prediction attributions.