Notes
All notes

Machine Learning: from math to models

Traditional software encodes rules: you write the if statements and the program applies them. Machine learning inverts that. You show the program examples — inputs and the answers you wanted — and it learns the rules that map one to the other. That inversion is powerful and treacherous: a learned function can fit the training data perfectly and still be wrong on everything else, and the whole discipline is about controlling that gap.

This post follows the roadmap.sh/machine-learning path in one guide. It is theory-first: the math (linear algebra, calculus, probability), the learning problem, the algorithms, the evaluation theory, and the deep-learning building blocks that explain why the code works. Code is interleaved throughout, and self-test question blocks follow each section. For the applied LLM side, see the AI Engineering course.

What machine learning is

Tom Mitchell’s definition is the clearest: a program learns from experience E with respect to a task T and a performance measure P if its performance at T, measured by P, improves with E. Spam filtering: T = classify email, E = labeled emails, P = accuracy on unseen emails.

The shift from classical programming is the direction of the arrows:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=1.9cm, minimum height=0.66cm, font=\small\ttfamily},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (d1) at (0,0.8) {data};
  \node[b, fill=green!14] (r1) at (2.6,0.8) {rules};
  \node[b, fill=orange!16] (a1) at (5.0,0.8) {answers};
  \node[b, fill=blue!10] (d2) at (0,-0.8) {data};
  \node[b, fill=green!14] (r2) at (2.6,-0.8) {?};
  \node[b, fill=orange!16] (a2) at (5.0,-0.8) {answers};
  \draw[a] (d1) -- (r1); \draw[a] (r1) -- (a1);
  \draw[a] (d2) -- (r2);
  \draw[a, dashed] (a2) to[bend right=25] node[below, font=\scriptsize] {learn} (r2);
  \node[font=\small, anchor=east] at (-0.2,0.8) {classical:};
  \node[font=\small, anchor=east] at (-0.2,-0.8) {ML:};
\end{tikzpicture}

ML engineer vs AI engineer. An ML engineer trains, tunes, evaluates, and deploys models built from data — the subject of this post. An AI engineer composes frozen foundation models (APIs, RAG, agents) into products, and is covered by the AI Engineering course. The skills overlap heavily in evaluation and deployment, and less in training and math.

The core subfields, which organize the rest of this post:

QQuestionWhat is machine learning, formally?
ASolution

Mitchell’s definition: a program learns from experience E with respect to a task T and performance measure P if its performance at T, measured by P, improves with E. Informally, it infers a mapping from data instead of having rules written by hand.

QQuestionWhat is the difference between an ML engineer and an AI engineer?
ASolution

An ML engineer trains, evaluates, tunes, and deploys models built from data (the subject of this post). An AI engineer composes frozen foundation models — prompts, retrieval, agents, evals — into products. They overlap most in evaluation and deployment and least in training and math.

The mathematical foundations

You do not need to derive everything, but you need the vocabulary, because every algorithm is stated in it.

Linear algebra is the language of data. A dataset is a matrix \(X \in \mathbb{R}^{n \times d}\) (\(n\) samples, \(d\) features); a model’s parameters are vectors; a prediction is a matrix product. The operations that matter are matrix multiplication, transpose, inverse, eigenvalues/eigenvectors, and singular value decomposition (SVD) — PCA and recommender systems are SVD in disguise. A dot product measures alignment, which is why it appears in similarity, projections, and attention.

\[ X w = \sum_j X_{:,j} w_j \quad \text{(a weighted sum of columns)} \]

Calculus is how models learn. The gradient \(\nabla f\) points in the direction of steepest increase; training moves against it. The Jacobian is the matrix of first derivatives for vector-valued functions; the Hessian is the matrix of second derivatives, describing curvature and used by second-order optimizers. The chain rule is the entire basis of backpropagation.

\[ \theta \leftarrow \theta - \eta \nabla_\theta L(\theta) \]

Probability models uncertainty. Random variables have distributions — Bernoulli (yes/no), binomial (counts), Gaussian (the bell curve), Poisson (rare events). Expectation is the long-run average; variance is the spread. Bayes’ theorem updates a prior belief with evidence and underlies naive Bayes and much of statistics.

\[ P(\theta \mid D) = \frac{P(D \mid \theta)\, P(\theta)}{P(D)} \]

Statistics turns data into conclusions: descriptive summaries, sampling, the central limit theorem (sample means become Gaussian), confidence intervals, hypothesis tests, and the warning that correlation is not causation.

import numpy as np
X = np.random.randn(100, 3)          # 100 samples, 3 features
w = np.array([1.0, -2.0, 0.5])
y = X @ w + 0.1 * np.random.randn(100)   # a linear relationship plus noise
# gradient of MSE loss (1/n)||Xw - y||^2 is (2/n) X^T (Xw - y)
grad = 2 / len(y) * X.T @ (X @ w - y)

Vectorization matters: the @ products above replace Python loops and are orders of magnitude faster because they run in optimized C.

QQuestionWhy is linear algebra central to machine learning?
ASolution

Data is represented as matrices (\(n\) samples × \(d\) features), model parameters as vectors, and predictions as matrix products. Similarity is a dot product, PCA and recommenders are built on eigenvalues/SVD, and gradients are vectors/matrices — so nearly every algorithm is stated in linear-algebra terms.

QQuestionWhat is a gradient, and why do we move against it?
ASolution

The gradient \(\nabla_\theta L\) is the vector of partial derivatives pointing in the direction of steepest increase of the loss. Training steps in the opposite direction, \(\theta \leftarrow \theta - \eta \nabla_\theta L\), to reduce the loss. The chain rule is what makes backpropagation possible.

QQuestionState Bayes’ theorem and one ML use.
ASolution

\(P(\theta \mid D) = P(D \mid \theta)\,P(\theta) / P(D)\): the posterior is the likelihood times the prior, normalized. It underlies naive Bayes classifiers, Bayesian inference, and updating beliefs with evidence.

Data: sources, formats, and preprocessing

Models are only as good as the data. The pipeline is collect → clean → preprocess → split → train → evaluate, and most of the work is in the first half.

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer

df = pd.read_parquet("data.parquet")
df = df.dropna(subset=["target"]).fillna({"age": df["age"].median()})

X, y = df.drop(columns=["target"]), df["target"]
pre = ColumnTransformer([
    ("num", StandardScaler(), ["age", "income"]),
    ("cat", OneHotEncoder(handle_unknown="ignore"), ["plan", "country"]),
])
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)

Data leakage is the cardinal sin: any information about the test set that reaches training inflates scores and destroys generalization. Fit scalers and encoders on the training split only — the Pipeline in the next section is how you enforce that mechanically. Splitting time-series data randomly is also leakage; split by time.

QQuestionWhat is data leakage, and how do you prevent it?
ASolution

Leakage is any information about the test set (or the target) leaking into training, which inflates validation scores and destroys real performance. Examples: fitting scalers/encoders on all data, using future information, or splitting time series randomly. Prevent it by fitting preprocessing inside a Pipeline on the training fold only and by splitting time series chronologically.

QQuestionWhat is the difference between normalization and standardization?
ASolution

Normalization (min–max) rescales features to a fixed range such as \([0,1]\); standardization maps each feature to zero mean and unit variance. Standardization is the usual default for gradient- and distance-based models; tree-based models need neither.

The learning problem

Supervised learning assumes the data comes from an unknown distribution \(P(x, y)\) and seeks a function \(f\) minimizing expected loss:

\[ R(f) = \mathbb{E}_{(x,y) \sim P}\big[ L(y, f(x)) \big] \]

We cannot compute \(R\) (we do not know \(P\)), so we minimize the empirical risk on the training sample instead. Generalization — doing well on unseen data — is the whole game, and the gap between training and test error is what everything else in this post tries to control.

Two theoretical anchors:

QQuestionWhat is the difference between empirical risk and true risk?
ASolution

True risk is the expected loss over the unknown data distribution; empirical risk is the average loss on the training sample. We minimize the empirical risk because the true distribution is unknown, and generalization is how well the empirical minimizer does on unseen data.

QQuestionWhat is inductive bias, and what does “No Free Lunch” mean?
ASolution

Inductive bias is the assumption a learner makes to generalize beyond the data (linearity, smoothness, locality). No Free Lunch says no single algorithm is best for all problems, because each algorithm’s bias helps on some distributions and hurts on others — so the choice depends on the data.

Supervised learning: regression

Regression predicts a continuous target. Linear regression fits \(f(x) = w^\top x + b\) by minimizing mean squared error:

\[ L(w) = \frac{1}{n} \sum_i (y_i - w^\top x_i)^2 \]

There is a closed-form solution (\(w = (X^\top X)^{-1} X^\top y\)) and an iterative one (gradient descent). Gradient descent is used more in practice because it scales and generalizes to non-linear models.

from sklearn.linear_model import LinearRegression, Ridge, Lasso
lin = LinearRegression().fit(X_tr, y_tr)
print(lin.coef_, lin.intercept_)

Polynomial features let a linear model fit curves, at the cost of overfitting. Regularization adds a penalty on the weights to control that:

Ridge(alpha=1.0).fit(X_tr, y_tr)   # alpha controls regularization strength
Lasso(alpha=0.01).fit(X_tr, y_tr)
QQuestionWhat is the difference between L1 and L2 regularization?
ASolution

L2 (Ridge) penalizes the sum of squared weights, shrinking them smoothly toward zero but rarely to exactly zero. L1 (Lasso) penalizes the sum of absolute weights and drives some weights to exactly zero, so it also performs feature selection. Elastic net combines them.

QQuestionWhy use gradient descent instead of the closed-form solution for linear regression?
ASolution

The closed form \(w=(X^\top X)^{-1}X^\top y\) needs a matrix inverse, which is \(O(d^3)\) and unstable when features are collinear or \(d\) is large. Gradient descent scales to large data, works for non-linear models, and needs only gradients.

Supervised learning: classification

Classification predicts a discrete label. The core algorithms, and the intuition for each:

Algorithm Idea Notes
Logistic regression linear score → sigmoid probability interpretable baseline
K-Nearest Neighbours vote of the \(k\) closest points no training, needs scaling
Decision tree recursive splits on features interpretable, overfits deep
Naive Bayes Bayes with feature independence fast, great for text
SVM maximum-margin boundary, kernels strong on small/medium data
Neural network learned non-linear features scales with data

Logistic regression models the log-odds as linear and squashes with the sigmoid; its loss is cross-entropy (log loss), not MSE, because the output is a probability:

\[ \hat{p} = \sigma(w^\top x), \qquad L = -\big[y \log \hat{p} + (1-y)\log(1-\hat{p})\big] \]

from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier

logreg = LogisticRegression(max_iter=1000).fit(X_tr, y_tr)
knn = KNeighborsClassifier(n_neighbors=5).fit(X_tr, y_tr)
tree = DecisionTreeClassifier(max_depth=4, random_state=0).fit(X_tr, y_tr)
print(logreg.predict_proba(X_te[:3]))

Multiclass is handled by expanding to the softmax over class scores, which turns a vector of logits into a probability distribution.

QQuestionWhy is cross-entropy used for classification instead of MSE?
ASolution

The model outputs probabilities via a sigmoid/softmax, and cross-entropy is the negative log-likelihood of the true class. It penalizes confident wrong predictions heavily and yields well-behaved gradients; MSE on a sigmoid gives vanishing gradients and poorer calibration.

QQuestionHow does K-Nearest Neighbours work, and what are its limitations?
ASolution

KNN stores the training data and predicts by a majority vote (or average) of the \(k\) nearest points. It is simple and non-parametric but slow at prediction (\(O(n)\) per query), needs feature scaling, suffers in high dimensions (the curse of dimensionality), and is sensitive to \(k\) and distance metric.

Model evaluation

You cannot improve what you do not measure, and the measurement theory is where most mistakes live.

Always split into train / validation / test. Train to fit parameters, validation to choose hyperparameters, test once at the end to estimate generalization. Tuning on the test set is leakage.

Classification metrics start from the confusion matrix — true/false positives/negatives:

\[ \text{precision} = \frac{TP}{TP+FP}, \qquad \text{recall} = \frac{TP}{TP+FN}, \qquad F_1 = 2\frac{P R}{P+R} \]

Regression metrics: MSE, RMSE (same units as the target), MAE (robust to outliers), and \(R^2\) (fraction of variance explained).

from sklearn.metrics import (confusion_matrix, classification_report,
                             roc_auc_score, mean_squared_error, r2_score)
pred = logreg.predict(X_te)
print(confusion_matrix(y_te, pred))
print(classification_report(y_te, pred))
print("AUC", roc_auc_score(y_te, logreg.predict_proba(X_te)[:, 1]))
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=1.7cm, minimum height=0.8cm, font=\small\ttfamily, align=center}]
  \node[c, fill=green!14] (tp) at (0,0) {TP};
  \node[c, fill=red!12] (fn) at (2.0,0) {FN};
  \node[c, fill=red!12] (fp) at (0,-1.0) {FP};
  \node[c, fill=green!14] (tn) at (2.0,-1.0) {TN};
  \node[font=\small, anchor=east] at (-1.1,0) {actual +};
  \node[font=\small, anchor=east] at (-1.1,-1.0) {actual --};
  \node[font=\small, anchor=south] at (0,0.5) {predicted +};
  \node[font=\small, anchor=south] at (2.0,0.5) {predicted --};
\end{tikzpicture}
QQuestionExplain precision, recall, and F1.
ASolution

Precision = TP/(TP+FP): of the items flagged positive, how many were correct. Recall = TP/(TP+FN): of the truly positive items, how many were found. F1 is their harmonic mean. Choose based on cost: precision matters for spam filtering, recall for disease screening.

QQuestionWhat does ROC-AUC measure?
ASolution

The area under the receiver-operating-characteristic curve, equal to the probability that a randomly chosen positive example is ranked above a randomly chosen negative one. It is threshold-independent and useful for ranking quality, but less informative under extreme class imbalance than the precision-recall curve.

QQuestionWhy is accuracy a bad metric on imbalanced data?
ASolution

Because predicting the majority class always gets a high score without learning anything. On a 1%-positive dataset, “always negative” is 99% accurate. Use precision, recall, F1, and AUC instead.

Bias, variance, and overfitting

The bias-variance decomposition explains the two ways a model fails. For squared error, expected test error splits into:

\[ \mathbb{E}\big[(y - \hat{f})^2\big] = \underbrace{\text{Bias}^2}_{\text{wrong assumptions}} + \underbrace{\text{Variance}}_{\text{sensitivity to data}} + \underbrace{\sigma^2}_{\text{irreducible noise}} \]

As model complexity grows, bias falls and variance rises; the total is U-shaped, and the minimum is the sweet spot.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  a/.style={->, thick, black!45}]
  \draw[a] (0,0) -- (7.2,0) node[below, font=\small] {model complexity};
  \draw[a] (0,0) -- (0,3.0) node[left, font=\small, align=right] {error};
  \draw[thick, blue!70!black] (0.2,2.6) .. controls (3,1.0) and (5,0.4) .. (7.0,0.25) node[right, font=\small] {bias$^2$};
  \draw[thick, orange!80!black] (0.2,0.25) .. controls (3,0.5) and (5,1.6) .. (7.0,2.8) node[right, font=\small] {variance};
  \draw[very thick, green!55!black] (0.2,2.7) .. controls (2.4,0.9) and (3.4,0.7) .. (7.0,3.0);
  \node[font=\small, text=green!45!black, anchor=north] at (2.9,0.55) {total};
\end{tikzpicture}

Learning curves diagnose which: if training and validation error converge to a high value, it is bias; if there is a large gap, it is variance. That tells you whether more data (variance) or a better model (bias) will help.

QQuestionExplain the bias-variance tradeoff.
ASolution

Expected squared error decomposes into bias² + variance + irreducible noise. Bias is error from wrong/simple assumptions (underfitting); variance is sensitivity to the particular training sample (overfitting). As complexity grows, bias falls and variance rises, giving a U-shaped total error with a sweet spot.

QQuestionHow do you diagnose and fix overfitting versus underfitting?
ASolution

Compare training and validation error. High both, small gap → underfitting (bias); add capacity, features, or reduce regularization. Low training error but a large gap → overfitting (variance); get more data, simplify, add regularization/dropout/early stopping, or ensemble. Learning curves make the diagnosis explicit.

QQuestionHow can you reduce overfitting?
ASolution

More data, a simpler model, regularization (L1/L2, dropout), early stopping, cross-validation for model selection, data augmentation, and ensembling (bagging/random forests reduce variance directly).

Validation techniques

Choosing hyperparameters and estimating performance requires holding data out correctly.

from sklearn.model_selection import cross_val_score, StratifiedKFold
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
print(cross_val_score(logreg, X_tr, y_tr, cv=cv, scoring="roc_auc").mean())
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.62cm, minimum height=0.5cm, font=\scriptsize}]
  \foreach \r in {0,1,2,3,4} {
    \foreach \i in {0,...,4} {
      \pgfmathparse{int(\i==\r)}
      \ifnum\pgfmathresult=1
        \node[c, fill=orange!35] at (\i*0.68,-\r*0.62) {};
      \else
        \node[c, fill=blue!10] at (\i*0.68,-\r*0.62) {};
      \fi
    }
  }
  \node[font=\small, anchor=west] at (3.6,-0.0) {orange = validation};
  \node[font=\small, anchor=west] at (3.6,-0.7) {blue = training};
\end{tikzpicture}
QQuestionWhat is k-fold cross-validation and why use it?
ASolution

Split the data into \(k\) folds; train on \(k-1\) and validate on the held-out fold, rotating so every fold is validation once, and average the scores. It gives a more stable performance estimate than a single split and uses all data for both training and validation (at \(k\)× the compute).

QQuestionWhen would you use LOOCV, stratified, or time-series splits?
ASolution

LOOCV (\(k=n\)) for very small datasets — unbiased but high-variance and expensive. Stratified k-fold to preserve class proportions, essential for imbalanced classification. Time-series splits to always validate on later data, never a random shuffle, because shuffling time leaks the future.

Scikit-learn and the ML workflow

Scikit-learn’s consistency is its superpower: every model is an estimator with fit, predict, and usually score, and preprocessing steps compose with models in a Pipeline.

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV

pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
grid = GridSearchCV(pipe, {"logisticregression__C": [0.01, 0.1, 1, 10]},
                    cv=5, scoring="roc_auc")
grid.fit(X_tr, y_tr)
print(grid.best_params_, grid.best_score_)

A Pipeline is not just convenience: it ensures the scaler is fit only on the training fold during cross-validation, which is exactly what prevents leakage.

QQuestionWhy put preprocessing and the model in a Pipeline?
ASolution

A Pipeline chains steps so the same transforms are applied at fit and predict time, and — crucially — during cross-validation each step is fit only on the training fold. That mechanically prevents leakage and makes the model a single estimator you can tune and deploy.

QQuestionWhat does GridSearchCV do?
ASolution

It exhaustively evaluates a grid of hyperparameters using cross-validation, refits the best combination on the full training set, and exposes best_params_ and best_estimator_. RandomizedSearchCV samples the space instead when it is large.

Ensembles

Combining models reduces variance and usually beats any single model.

from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
rf = RandomForestClassifier(n_estimators=300, random_state=0).fit(X_tr, y_tr)
gb = GradientBoostingClassifier(random_state=0).fit(X_tr, y_tr)

The trade: bagging reduces variance, boosting reduces bias, and both add training cost and reduce interpretability.

QQuestionWhat is the difference between bagging and boosting?
ASolution

Bagging trains models in parallel on bootstrap samples and averages them, mainly reducing variance (random forests). Boosting trains models sequentially, each correcting the previous one’s errors, mainly reducing bias (AdaBoost, gradient boosting, XGBoost/LightGBM).

QQuestionWhy do random forests reduce variance?
ASolution

Averaging many decorrelated trees cancels their individual noise; feature subsampling at each split decorrelates the trees, which is what makes the average much less sensitive to the training sample than a single deep tree.

Unsupervised learning

Without labels, the goal is structure.

Clustering groups similar points. K-means alternates assigning points to the nearest centroid and recomputing centroids; it needs \(k\) up front, assumes roughly spherical clusters, and is sensitive to initialization (use k-means++). Hierarchical clustering builds a dendrogram; DBSCAN finds density-based clusters and labels outliers as noise.

from sklearn.cluster import KMeans, DBSCAN
from sklearn.metrics import silhouette_score
km = KMeans(n_clusters=3, n_init=10, random_state=0).fit(X)
print(silhouette_score(X, km.labels_))

Dimensionality reduction compresses features. PCA finds orthogonal directions of maximum variance (eigenvectors of the covariance matrix); keep the components explaining most variance. It is linear, unsupervised, and the standard first compression. t-SNE and UMAP are non-linear and excellent for visualization, but the axes and distances are not meaningful — use them to look, not to cluster.

from sklearn.decomposition import PCA
X_pca = PCA(n_components=0.95).fit_transform(X)   # keep 95% of variance
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  a/.style={->, thick, black!45}]
  \draw[a] (-0.3,-0.3) -- (3.4,-0.3); \draw[a] (-0.3,-0.3) -- (-0.3,2.6);
  \foreach \x/\y in {0.4/0.6,0.8/1.1,1.2/0.9,1.6/1.6,2.0/1.4,2.4/2.0,2.8/1.9} {
    \fill[blue!55] (\x,\y) circle (2.2pt);
  }
  \draw[very thick, orange!80!black] (0.2,0.35) -- (3.0,2.25);
  \node[font=\small, text=orange!70!black, anchor=west] at (2.2,2.35) {PC1};
\end{tikzpicture}
QQuestionHow does k-means work, and what are its limitations?
ASolution

It alternates assigning each point to the nearest centroid and recomputing centroids, minimizing within-cluster squared distance. It requires \(k\) in advance, assumes roughly spherical equal-sized clusters, is sensitive to initialization (use k-means++), and can converge to local optima (run with multiple restarts).

QQuestionWhat is PCA, and when would you use it?
ASolution

Principal Component Analysis finds orthogonal directions of maximum variance (eigenvectors of the covariance matrix) and projects data onto the top components. Use it for compression, denoising, visualization, and fighting the curse of dimensionality — keeping the components that explain most variance (e.g. 95%). It is linear and unsupervised.

QQuestionk-means versus DBSCAN?
ASolution

k-means partitions everything into \(k\) spherical clusters and assumes you know \(k\); DBSCAN finds clusters of arbitrary shape based on density and labels sparse points as noise, without specifying \(k\), but is sensitive to its eps/min_samples parameters and struggles with varying densities.

Feature engineering, selection, and the curse of dimensionality

Good features beat clever models. Engineering creates informative columns (ratios, time since an event, aggregations, interactions) and encodes domain knowledge. Selection removes unhelpful ones: filter methods (correlation, mutual information), wrapper methods (recursive feature elimination), and embedded methods (Lasso, tree importances).

The curse of dimensionality is the reason: as dimensions grow, data becomes sparse, distances concentrate, and the samples needed to cover the space grow exponentially. More features mean more noise unless each earns its place. PCA, feature selection, and regularization are the countermeasures.

QQuestionWhat is the curse of dimensionality?
ASolution

As the number of features grows, data becomes sparse, distances between points concentrate (nearest and farthest neighbours become similar), and the samples needed to cover the space grow exponentially. Models then overfit or fail to find meaningful neighbours. Counter it with feature selection, PCA, and regularization.

QQuestionWhat are filter, wrapper, and embedded feature selection?
ASolution

Filter methods rank features by a statistic independent of the model (correlation, mutual information). Wrapper methods evaluate subsets with the model itself (recursive feature elimination). Embedded methods select during training (Lasso, tree importances).

Neural networks

A neural network stacks layers of linear transforms and non-linear activations. Without a non-linearity, stacked linear layers collapse to one linear layer — that is why ReLU, sigmoid, and tanh matter.

\[ a^{(l)} = \sigma\big(W^{(l)} a^{(l-1)} + b^{(l)}\big) \]

Training uses backpropagation (the chain rule applied layer by layer) and an optimizer (SGD, momentum, Adam). The output layer matches the task: sigmoid for binary, softmax for multiclass, linear for regression; the loss is cross-entropy or MSE. Regularization includes L2 weight decay, dropout (randomly zero activations), batch normalization, and early stopping.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.42cm, inner sep=0pt}]
  \foreach \i in {0,1,2} { \node[n, fill=blue!12] (i\i) at (0,\i*0.7-0.7) {}; }
  \foreach \i in {0,1,2,3} { \node[n, fill=orange!18] (h\i) at (1.6,\i*0.7-1.05) {}; }
  \foreach \i in {0,1} { \node[n, fill=green!16] (o\i) at (3.2,\i*0.7-0.35) {}; }
  \foreach \a in {0,1,2} \foreach \b in {0,1,2,3} \draw[gray!60] (i\a) -- (h\b);
  \foreach \a in {0,1,2,3} \foreach \b in {0,1} \draw[gray!60] (h\a) -- (o\b);
  \node[font=\small, anchor=north] at (0,-1.6) {input};
  \node[font=\small, anchor=north] at (1.6,-1.95) {hidden};
  \node[font=\small, anchor=north] at (3.2,-1.25) {output};
\end{tikzpicture}
import torch
model = torch.nn.Sequential(
    torch.nn.Linear(3, 16), torch.nn.ReLU(),
    torch.nn.Linear(16, 1), torch.nn.Sigmoid(),
)
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
loss_fn = torch.nn.BCELoss()
# loop: forward -> loss -> opt.zero_grad() -> loss.backward() -> opt.step()
QQuestionWhy are activation functions necessary in a neural network?
ASolution

Without a non-linearity between layers, a stack of linear transforms collapses into a single linear transform, so the network could only model linear functions. Non-linear activations (ReLU, sigmoid, tanh) give the network its expressive power.

QQuestionWhat is backpropagation?
ASolution

The algorithm that computes gradients of the loss with respect to every weight by applying the chain rule backward through the network, reusing intermediate results. Those gradients feed an optimizer (SGD, Adam) that updates the weights.

QQuestionWhat does dropout do?
ASolution

During training it randomly zeroes a fraction of activations each step, which prevents units from co-adapting and acts as regularization, improving generalization. At inference, dropout is disabled (or scaled) so the full network is used.

Deep learning architectures

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=1.35cm, minimum height=0.62cm, font=\small\ttfamily},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (img) at (0,0) {image};
  \node[b, fill=orange!16] (conv) at (2.0,0) {conv};
  \node[b, fill=orange!16] (pool) at (4.0,0) {pool};
  \node[b, fill=green!14] (fc) at (6.0,0) {dense};
  \node[b, fill=red!12] (out) at (8.0,0) {class};
  \draw[a] (img) -- (conv); \draw[a] (conv) -- (pool); \draw[a] (pool) -- (fc); \draw[a] (fc) -- (out);
\end{tikzpicture}
QQuestionHow does a CNN exploit image structure?
ASolution

Convolution layers slide learned filters over the input, sharing weights across positions so the model detects local patterns anywhere (translation equivariance) with far fewer parameters than a dense layer. Pooling down-samples to summarize regions, and strides control how far the filter moves, reducing resolution as depth grows.

QQuestionWhat is self-attention, and why did transformers replace RNNs?
ASolution

Self-attention lets every position compute a weighted combination of all other positions (\(\mathrm{softmax}(QK^\top/\sqrt{d})V\)), capturing long-range dependencies in one step. Unlike RNNs it is parallelizable over the sequence and does not forget distant tokens. Multi-head attention runs several such projections in parallel to capture different relationships.

QQuestionWhat is an autoencoder, and what is it used for?
ASolution

A network trained to reconstruct its input through a narrow bottleneck, learning a compressed representation. Uses include dimensionality reduction, denoising, and anomaly detection (high reconstruction error signals an outlier). A GAN instead pits a generator against a discriminator to synthesize realistic samples.

Reinforcement learning

An agent interacts with an environment, observes a state, takes an action, receives a reward, and transitions to a new state. Formally this is a Markov decision process; the agent seeks a policy maximizing expected discounted return.

\[ G_t = \sum_{k=0}^{\infty} \gamma^k r_{t+k+1}, \qquad Q(s,a) \leftarrow Q(s,a) + \alpha\big[r + \gamma \max_{a'} Q(s',a') - Q(s,a)\big] \]

The exploration–exploitation trade-off distinguishes RL: the agent must balance using what it knows with trying new actions to learn. Q-learning is off-policy value-based learning; policy gradient methods optimize the policy directly. RL is the right tool for sequential decisions (games, robotics, recommendation), not for standard prediction.

QQuestionWhat is the exploration-exploitation tradeoff?
ASolution

The agent must exploit known good actions to earn reward now while exploring new actions to discover better ones later. Pure exploitation gets stuck in a local optimum; pure exploration never capitalizes on what it learns. Strategies include ε-greedy, softmax, and UCB.

QQuestionWhat is a Markov decision process?
ASolution

The formal model of RL: states, actions, a transition function, a reward function, and a discount factor, with the Markov property that the next state depends only on the current state and action. The agent seeks a policy that maximizes expected discounted return.

NLP and explainable AI

NLP processes text: tokenization, embeddings (words as vectors), and, since transformers, contextual representations. The AI Engineering course covers embeddings and RAG in depth.

Explainable AI answers “why did the model predict that?” — essential for trust and compliance:

Explainability is not just a nice-to-have: in lending, hiring, and healthcare it is often a legal requirement, and it is how you catch a model keying on a spurious feature.

QQuestionWhat is the difference between global and local explanations?
ASolution

Global explanations describe which features matter for the model overall (e.g. permutation importance, SHAP summary); local explanations explain one specific prediction (SHAP force plots, LIME). Both matter: global builds trust in the model, local answers “why this decision?”

QQuestionWhat are SHAP and LIME?
ASolution

SHAP assigns each feature a contribution to a prediction using Shapley values from cooperative game theory, giving consistent additive attributions. LIME fits a simple interpretable surrogate model locally around the prediction. Both approximate a black-box model’s reasoning for humans.

Putting it into production

A model in a notebook is not a product. Production adds:

The AI Engineering course picks up where this leaves off for LLM-based systems; the evaluation discipline is the same.

QQuestionWhat is the difference between data drift and concept drift?
ASolution

Data (covariate) drift is a change in the input distribution \(P(x)\) while the input-to-label relationship stays fixed; concept drift is a change in \(P(y \mid x)\) itself. Both degrade a deployed model, and both require monitoring and likely retraining, but they are detected differently (feature statistics versus performance on fresh labels).

QQuestionHow do you monitor an ML model in production?
ASolution

Track prediction distributions, feature-statistic drift, latency, error rates, and business metrics — not just accuracy, which needs fresh labels that may arrive late. Version data and models for reproducibility, alert on drift, and have a retraining and rollback plan.

Pitfalls

QQuestionSelf-check

What does the bias-variance decomposition say, and how do you diagnose which one is hurting? Why is accuracy a poor metric on imbalanced data?

ASolution

Expected squared error = bias² + variance + irreducible noise. High bias (underfitting) shows high training and validation error; high variance (overfitting) shows low training error but a large validation gap. Accuracy hides the cost of missing the minority class: a 1%-positive dataset can be 99% accurate by always predicting the majority, so use precision, recall, F1, and ROC-AUC.