Back
In print settings: Save as PDF, turn headers and footers off, turn background graphics on.

Machine Learning

A mathematical and algorithmic journey through the systems that learn from data, from linear models to deep neural architectures.

Official Documentation

July 2026

Contents

Introduction & Foundations

  • Foundations of Machine Learning
  • Model Evaluation
  • Feature Engineering

Machine Learning Workflows

  • Machine Learning Workflows

Supervised Learning

  • Linear Regression
  • Logistic Regression
  • Regularization Theory
  • Naive Bayes
  • k-Nearest Neighbors (kNN)
  • Support Vector Machines
  • Decision Trees
  • Ensemble Learning
  • Gradient Boosting Systems

Unsupervised Learning

  • Principal Component Analysis
  • Clustering Algorithms

Deep Learning

  • Numerical Optimization
  • Neural Networks Foundations
  • Convolutional Neural Networks
  • Natural Language Processing

MLOps & System Deployment

  • Machine Learning Operations
  • Recommender Systems
  • Reinforcement Learning
  • Ethics in Machine Learning

Introduction & Foundations

Section Detail

Foundations of Machine Learning

Foundations of Machine Learning

Machine learning allows computers to learn from experience rather than explicit developer rules. Formally, a program learns from experience EE with respect to a class of tasks TT and performance measure PP, if its performance at tasks in TT, as measured by PP, improves with experience EE.

Taxonomy of Machine Learning Systems

Algorithms are structured by their learning feedback:

  1. Supervised Learning: trained on labeled data (xi,yi)(x_i, y_i) to map inputs to continuous (regression) or discrete (classification) targets.
  2. Unsupervised: identifies patterns in unlabeled data (e.g., clustering).
  3. Semi-Supervised: combines few labeled and many unlabeled samples.
  4. Reinforcement: learns optimal actions via environment rewards.

Mathematical Formulation: ERM

Learning is formulated as empirical risk minimization. Given a hypothesis space H\mathcal{H} and a loss function L(y,h(x))L(y, h(x)), we solve for a hypothesis h^H\hat{h} \in \mathcal{H} that minimizes the average loss over the training set:

h^=argminhH1ni=1nL(yi,h(xi))\hat{h} = \arg\min_{h \in \mathcal{H}} \frac{1}{n} \sum_{i=1}^{n} L(y_i, h(x_i))

Generalization and the Bias-Variance Trade-off

A model’s generalization error on unseen data is decomposed into three components:

  • Bias: error due to overly simplistic assumptions, causing underfitting.
  • Variance: error due to high sensitivity to small training set fluctuations, causing overfitting.
  • Irreducible Noise: inherent variance in the data distribution.

Generalization is evaluated by training parameters on a training set and testing performance on an independent test set.

Example: Train-Test Splitting

The following example demonstrates splitting data and verifying shapes to ensure proper evaluation setup:

python

Interactive Lab

Partition a dataset into independent training and test sets using scikit-learn. Adjust test_size to observe how split shapes change.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Validate your understanding of generalization error trade-offs:

What is the consequence of selecting a hypothesis space that is too complex for the training data size?

References & Further Reading

Section Detail

Model Evaluation

Model Evaluation Metrics

Evaluating model performance requires task-specific metrics. Accuracy is misleading on imbalanced datasets: if a rare disease affects 1% of the population, a dummy classifier predicting “healthy” achieves 99% accuracy. Generalization error must be measured on independent data to evaluate utility.

Classification Metrics and Confusion Matrix

Binary classification performance is tabulated in a Confusion Matrix:

Predicted PositivePredicted Negative
Actual PositiveTrue Positive (TP): 80False Negative (FN): 20
Actual NegativeFalse Positive (FP): 10True Negative (TN): 90

In this disease-screening example with 200 samples:

  • Precision: positive prediction accuracy. Out of 90 predicted positive cases, 80 were correct. Precision=TPTP+FP=8080+100.889\text{Precision} = \frac{\text{TP}}{\text{TP} + \text{FP}} = \frac{80}{80 + 10} \approx 0.889
  • Recall (Sensitivity): detection rate of actual positives. Out of 100 actual diseased patients, 80 were detected. Recall=TPTP+FN=8080+20=0.800\text{Recall} = \frac{\text{TP}}{\text{TP} + \text{FN}} = \frac{80}{80 + 20} = 0.800
  • F1 Score: harmonic mean of precision and recall, penalizing extreme values. F1=2×Precision×RecallPrecision+Recall=2×0.889×0.80.889+0.80.842F_1 = 2 \times \frac{\text{Precision} \times \text{Recall}}{\text{Precision} + \text{Recall}} = 2 \times \frac{0.889 \times 0.8}{0.889 + 0.8} \approx 0.842

ROC Curve and AUC

The ROC curve plots True Positive Rate (Recall) against False Positive Rate (FPR=FPTN+FP\text{FPR} = \frac{\text{FP}}{\text{TN} + \text{FP}}) across decision thresholds. The Area Under the Curve (AUC) ranges from 0.50.5 (random) to 1.01.0 (perfect).

Code
import os
import matplotlib.pyplot as plt
plt.figure(figsize=(5, 3.5))
plt.plot([0, 1], [0, 1], 'k--', label='Random (AUC=0.5)')
plt.plot([0, 0.25, 1], [0, 0.75, 1], 'b-', label='Model (AUC=0.75)')
plt.xlabel('FPR')
plt.ylabel('TPR')
plt.title('ROC Curve')
plt.legend()
plt.tight_layout()
plt.savefig(os.environ["LIBREUNI_OUTPUT"], format="svg")
2026-07-12T18:15:55.443839 image/svg+xml Matplotlib v3.6.3, https://matplotlib.org/
Receiver Operating Characteristic (ROC) Curve

Regression Metrics

While classification relies on counting correct assignments, regression predicts continuous values. Typical metrics include Mean Squared Error (MSE), Root Mean Squared Error (RMSE), and Mean Absolute Error (MAE).

A normalized evaluation metric is the Coefficient of Determination (R2R^2). The total variance in the data is captured by the Total Sum of Squares (SST). The variance explained by the model is the Sum of Squares due to Regression (SSR), and the unexplained variance is the Sum of Squared Errors (SSE).

SST=i=1n(yiyˉ)2\text{SST} = \sum_{i=1}^n (y_i - \bar{y})^2 SSE=i=1n(yiy^i)2\text{SSE} = \sum_{i=1}^n (y_i - \hat{y}_i)^2 SSR=i=1n(y^iyˉ)2\text{SSR} = \sum_{i=1}^n (\hat{y}_i - \bar{y})^2

The R2R^2 score represents the proportion of variance explained by the model:

R2=1SSESSTR^2 = 1 - \frac{\text{SSE}}{\text{SST}}

Validation Methods

Proper validation is crucial for an iterative ML workflow to prevent overfitting and ensure model generalization.

  • Train-test split: Uses a portion of data for training and a held-out test set purely for final evaluation.
  • Train-val-test split: Introduces a validation set. The training set updates model parameters, the validation set is used for evaluation and hyperparameter tuning, and the test set is reserved exclusively for final evaluation.
  • Stratification: When splitting non-representative training data (especially imbalanced classification datasets), stratification ensures the class distribution in all splits mirrors the original dataset.

Cross-Validation

  • Cross-validation (CV): Splits the training data into kk folds. The model trains on k1k-1 folds and validates on the remaining one, rotating iteratively. This provides a more robust estimate of performance than a single validation set.
  • Leave-one-out cross-validation (LOO CV): An extreme form of CV where kk equals the number of samples (NN). The model trains on N1N-1 samples and is validated on the single remaining point. While computationally expensive, it maximizes training data usage and provides unbiased performance estimates.

Example: Calculating Metrics

The following example demonstrates calculating classification metrics using a confusion matrix in scikit-learn:

python

Interactive Lab

Compute Precision, Recall, and F1 Score using scikit-learn metrics. Modify the ground truth labels or predictions to see how the scores change.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Validate your knowledge of classification metric trade-offs:

In a disease detection system where missing a positive case has fatal consequences, which metric should be prioritized?

References & Further Reading

Section Detail

Feature Engineering

Feature Engineering

Preprocessing transforms raw data into numerical matrices optimized for training.

Handling Missing Data and Outliers

Real-world datasets are rarely perfect. Data may be missing due to sensor failures, non-responses, or unrecorded events.

  • Imputation: Replaces missing values using training statistics (e.g., mean, median, mode) or algorithms (e.g., kNN imputation).
  • Removal: Dropping rows or irrelevant columns with too many missing values.

Handling Outliers

Outliers are extreme values that can significantly skew statistical measures and models like Linear Regression. Depending on the context, we can:

  • Keep: If the outliers represent genuine, important anomalies (e.g., fraud detection).
  • Delete: If the outliers are clearly errors or irrelevant.
  • Impute: Treat outliers as missing data and impute a central value.
  • Transform: Apply mathematical transformations to reduce their impact.

Boxplots are visual tools commonly used to identify outliers. They display the interquartile range (IQR) of data, with points falling outside 1.5×IQR1.5 \times \text{IQR} typically flagged as outliers.

Skewed Data and Transformations

When data is highly skewed (e.g., income distribution with a long right tail), it can negatively impact model performance. We apply transformations to make the distribution more Gaussian-like:

  • Logarithmic Transformation: x=log(x)x' = \log(x) (useful for right-skewed data).
  • Square Root Transformation: x=xx' = \sqrt{x}.
  • Box-Cox Transformation: A parameterized family of power transformations.

Handling String and Text Data

Models require numerical inputs. Categorical and textual data must be encoded:

  • Ordinal Encoding: Maps categories to ordered integers (e.g., “Low”, “Medium”, “High” to 1, 2, 3).
  • One-Hot Encoding: Creates separate binary columns for each category, preventing the model from assuming a false ordinal relationship between nominal categories (e.g., colors).
  • Bag of Words (BoW): For free-text data, BoW creates a vocabulary of all unique words and represents each document as a vector indicating the frequency of each word.

Feature Scaling

Disparate scales bias distance-based models (KNN, SVM). We scale features via:

  1. Min-Max Scaling: maps to [0,1][0, 1]: xscaled=xxminxmaxxminx_{\text{scaled}} = \frac{x - x_{\text{min}}}{x_{\text{max}} - x_{\text{min}}}.
  2. Standardization: centers by mean and variance: xscaled=xμσx_{\text{scaled}} = \frac{x - \mu}{\sigma}.

Feature Selection and Correlation

Linear relationships are analyzed using a Correlation Matrix of Pearson coefficients in the range [1,1][-1, 1]. Below is an example mapping features from a real estate dataset:

House SizeNum BedroomsDistance to Center
House Size1.000.85-0.60
Num Bedrooms0.851.00-0.45
Distance to Center-0.60-0.451.00

The diagonal 1.001.00 represents self-correlation. The coefficient 0.850.85 indicates a strong positive relationship between size and bedrooms, while 0.60-0.60 shows a negative relationship with center distance (further houses tend to be smaller).

Code
import os, pandas as pd, numpy as np, matplotlib.pyplot as plt
d = pd.DataFrame(np.random.randn(50, 3), columns=list('ABC'))
d['B'] = d['A'] * 0.7 + np.random.randn(50) * 0.3
plt.figure(figsize=(3.5, 2.8))
plt.imshow(d.corr(), cmap='coolwarm', vmin=-1, vmax=1)
plt.colorbar()
plt.xticks(range(3), d.columns)
plt.yticks(range(3), d.columns)
plt.tight_layout()
plt.savefig(os.environ["LIBREUNI_OUTPUT"], format="svg")
2026-07-12T18:15:56.623025 image/svg+xml Matplotlib v3.6.3, https://matplotlib.org/
Correlation Matrix Heatmap

Example: Scaling and Encoding

The following example demonstrates categorical one-hot encoding and standardization:

python

Interactive Lab

Scale continuous features using standardization and encode categorical features using one-hot encoding.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Evaluate your understanding of data preprocessing constraints:

Why is standardization preferred over Min-Max scaling when features contain significant outliers?

Data Leakage

Preprocessing parameters must fit only on training data. Fitting on all data leaks test set statistics, inflating validation scores.

References & Further Reading

Machine Learning Workflows

Section Detail

Machine Learning Workflows

Machine Learning Workflows

Machine learning development is an iterative lifecycle accommodating data variability.

Lifecycle Architecture

The development lifecycle consists of sequential phases and feedback loops:

Code
skinparam backgroundColor transparent
start
:Data Collection;
repeat
:Exploratory Data Analysis (EDA);
:Data Preprocessing & Cleaning;
:Model Training & Selection;
backward:Refine Features or Architecture;
repeat while (Meets Performance Goal?) is (no) not (yes)
:Final Validation;
:Model Deployment;
stop
Data CollectionExploratory Data Analysis (EDA)Data Preprocessing & CleaningModel Training & SelectionyesMeets Performance Goal?noRefine Features or ArchitectureFinal ValidationModel Deployment

Three Core Workflows

Developing machine learning systems involves three distinct architectural flows depending on the operational stage:

1. The Experimental Flow (Exploration & Prototyping)

Focused on data discovery. Data scientists work in interactive environments (e.g., notebooks) to query raw sources, perform Exploratory Data Analysis (EDA) to locate distributions and outliers, engineer prototype features, and evaluate baseline hypotheses.

2. The Production Pipeline (Continuous Training)

Focused on automation and scalability. Notebook experiments are codified into structured, reproducible pipelines:

  1. Validation: load and validate incoming data schemas.
  2. Preprocessing: fit and execute transformations.
  3. Training: automate hyperparameter search.
  4. Registry: evaluate targets and register valid binaries.

3. The Inference Flow (Batch vs. Real-time)

Deployment layouts depend on latency and throughput constraints:

  • Batch: offline, scheduled predictions on large datasets, maximizing throughput.
  • Real-time: on-demand predictions (e.g., via APIs) with minimal latency (under 100ms).

Example: Chaining Workflows via Pipelines

Scikit-learn Pipeline objects bundle preprocessing steps and estimators, preventing data leakage during validation:

python

Interactive Lab

Chain imputation, standard scaling, and logistic regression into a single pipeline.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Test your understanding of ML pipeline architectures:

Why must preprocessing parameters (like scaling means) fit only on the training dataset?

References & Further Reading

Supervised Learning

Section Detail

Linear Regression

Linear Regression and the Normal Equation

Linear Regression models a continuous target yy as a linear combination of input features xx:

y^=θTx\hat{y} = \theta^T \mathbf{x} where θ\theta is the model parameter vector (including the intercept or bias θ0\theta_0), and x\mathbf{x} is the observation vector containing the features (with x0=1x_0 = 1).

Simple vs. Multiple Linear Regression

  • Simple Linear Regression: Models the relationship between a single feature x1x_1 and the target yy. The equation simplifies to finding the best line with a specific slope (θ1\theta_1) and intercept (θ0\theta_0): y^=θ0+θ1x1\hat{y} = \theta_0 + \theta_1 x_1
  • Multiple Linear Regression: Extends the concept to multiple features, where each feature gets its own weight (slope) in a multidimensional space.

Polynomial Regression

If the data is more complex than a simple straight line, we can still use linear models to fit nonlinear data. By adding powers of each feature as new features, we can train a linear model on this extended set of features. This is called Polynomial Regression. Despite fitting a curve to the data, it is still considered a linear model because the prediction is still a linear combination of the (now polynomial) features.

Parameter Estimation: Ordinary Least Squares

To train the model, we find parameters θ\theta that minimize the Mean Squared Error (MSE) over the dataset:

MSE(X,hθ)=1mi=1m(θTx(i)y(i))2\text{MSE}(X, h_{\theta}) = \frac{1}{m} \sum_{i=1}^{m} (\theta^T \mathbf{x}^{(i)} - y^{(i)})^2

The Closed-Form Normal Equation

To minimize the cost function, we solve analytically using the Normal Equation:

θ^=(XTX)1XTy\hat{\theta} = (X^T X)^{-1} X^T y

  • XX: The design matrix of shape (m,n+1)(m, n+1) containing all features.
  • yy: The target vector of shape (m,1)(m, 1).

Multicollinearity and SVD

If the matrix XTXX^T X is singular (non-invertible) due to redundant, highly correlated features, standard inversion fails. Solvers compute the pseudo-inverse X+X^+ using Singular Value Decomposition (SVD) for stability.

Computational Complexity

Computing (XTX)1(X^T X)^{-1} requires inverting an (n+1)×(n+1)(n+1) \times (n+1) matrix. The computational complexity is between O(n2.4)O(n^{2.4}) and O(n3)O(n^3), making the Normal Equation expensive when the number of features is large.

Example: Computing the Normal Equation

The following example demonstrates computing model coefficients using the Normal Equation:

python

Interactive Lab

Compute model parameters analytically using the Normal Equation. Alter the synthetic target equation coefficients to see if the equation adapts and finds the new parameters.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Test your understanding of the analytical parameter estimation limits:

If your dataset contains 100,000 features and 1,000 samples, what makes the Normal Equation less suitable than gradient descent?

References & Further Reading

Section Detail

Logistic Regression

Logistic Regression and Probability Estimation

Logistic Regression is a classifier that computes a weighted sum of inputs and maps the output to a probability between 00 and 11.

Probabilistic Formulation: The Sigmoid Function

The model feeds its linear output into the Sigmoid Function σ(t)\sigma(t):

p^=σ(θTx)=11+eθTx\hat{p} = \sigma(\theta^T \mathbf{x}) = \frac{1}{1 + e^{-\theta^T \mathbf{x}}}

The prediction rule for binary classes is:

y^={1if p^0.50if p^<0.5\hat{y} = \begin{cases} 1 & \text{if } \hat{p} \ge 0.5 \\ 0 & \text{if } \hat{p} < 0.5 \end{cases}

The prediction decision boundary is linear where θTx=0\theta^T \mathbf{x} = 0.

Code
import os
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(-6, 6, 200)
sig = 1 / (1 + np.exp(-t))
plt.figure(figsize=(5, 3.5))
plt.plot(t, sig, "b-", linewidth=2, label=r"$\sigma(t) = \frac{1}{1 + e^{-t}}$")
plt.axhline(y=0.5, color="gray", linestyle="--")
plt.axvline(x=0, color="gray", linestyle="--")
plt.title("Sigmoid Curve")
plt.grid(True, alpha=0.3)
plt.legend()
plt.tight_layout()
plt.savefig(os.environ["LIBREUNI_OUTPUT"], format="svg")
2026-07-12T18:15:57.407715 image/svg+xml Matplotlib v3.6.3, https://matplotlib.org/
The Sigmoid Function

Parameter Optimization: Log Loss

To optimize parameters θ\theta, we minimize the convex Log Loss (binary cross-entropy):

J(θ)=1mi=1m[y(i)log(p^(i))+(1y(i))log(1p^(i))]J(\theta) = -\frac{1}{m} \sum_{i=1}^{m} \left[ y^{(i)} \log(\hat{p}^{(i)}) + (1 - y^{(i)}) \log(1 - \hat{p}^{(i)}) \right]

It penalizes confident incorrect predictions with infinite cost (if y=1y=1 and p^0\hat{p} \to 0, then log(p^)-\log(\hat{p}) \to \infty).

Multiclass Classification Strategies

While Logistic Regression is inherently a binary classifier, it can be extended to handle multiple classes (e.g., classifying images of digits 0-9) using specific strategies:

  • One-vs-Rest (OVR) (also called One-vs-All): Trains NN separate binary classifiers for an NN-class problem. Each classifier is trained to distinguish one specific class from all the rest combined. During prediction, the classifier that outputs the highest probability wins. This is the default approach in most ML libraries for logistic regression.
  • One-vs-One (OVO): Trains a binary classifier for every possible pair of classes, resulting in N×(N1)2\frac{N \times (N-1)}{2} classifiers. For a new data point, all classifiers are run, and the class that wins the most duels is selected. OVO is particularly useful for algorithms that scale poorly with dataset size (like SVMs), because each classifier is only trained on the subset of data belonging to the two classes.

Alternatively, Softmax Regression (Multinomial Logistic Regression) generalizes Logistic Regression to natively support multiple classes by normalizing raw logits into a direct probability distribution across all classes without training multiple binary models.

Example: Logistic Regression Inference

The following example demonstrates calculating predictions using a trained Logistic Regression classifier:

python

Interactive Lab

Perform logistic regression inference. Calculate the predicted class and class probabilities for a sample point near the decision boundary.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Test your knowledge of the Logistic Regression model boundary behavior:

Why does the Log Loss cost function lack a closed-form analytical solution like the Normal Equation?

References & Further Reading

Section Detail

Regularization Theory

Regularization Theory

Regularization restricts model complexity to prevent overfitting. It penalizes large model weights during training, forcing parameters to stay small.

Regularized Linear Regression Models

Three common regularized versions of linear regression modify the MSE cost function:

1. Ridge Regression (L2 Regularization)

Ridge Regression adds a penalty equal to the sum of squared weights to the cost function:

J(θ)=MSE(θ)+α12i=1nθi2J(\theta) = \text{MSE}(\theta) + \alpha \frac{1}{2} \sum_{i=1}^{n} \theta_i^2

The hyperparameter α\alpha controls regularization strength. If α=0\alpha = 0, it behaves like Ordinary Least Squares. Note that the bias term θ0\theta_0 is not regularized.

2. Lasso Regression (L1 Regularization)

Lasso adds a penalty equal to the sum of absolute weights:

J(θ)=MSE(θ)+αi=1nθiJ(\theta) = \text{MSE}(\theta) + \alpha \sum_{i=1}^{n} |\theta_i|

Lasso regression performs feature selection by forcing less important feature weights to exactly 00.

Geometric Intuition

L1 forms a diamond constraint boundary that tends to intersect coordinate axes at their corners, yielding sparse weights. L2 forms a spherical boundary, shrinking weights toward zero without setting them exactly to zero.

3. Elastic Net

Elastic Net combines Ridge and Lasso regularizations, controlled by a mix ratio rr:

J(θ)=MSE(θ)+rαi=1nθi+(1r)α12i=1nθi2J(\theta) = \text{MSE}(\theta) + r \alpha \sum_{i=1}^{n} |\theta_i| + (1 - r) \alpha \frac{1}{2} \sum_{i=1}^{n} \theta_i^2

It acts as a compromise, stabilizing selection when features are highly correlated.

Example: Parameter Sparsity

The following example demonstrates how Lasso regularizes weights to zero compared to Ridge:

python

Interactive Lab

Fit Ridge (L2) and Lasso (L1) regression estimators on a small dataset. Notice how Lasso sets weights exactly to zero while Ridge shrinks them close to zero.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Test your understanding of regularized cost functions:

Under what scenario is Elastic Net preferred over Lasso regression?

Early Stopping

Early stopping is a regularization technique where validation error is monitored during iterative training. We stop training as soon as the validation error reaches a minimum and starts to increase.

References & Further Reading

Section Detail

Naive Bayes

Naive Bayes Classifier

Naive Bayes is a probabilistic classifier based on Bayes’ Theorem. It assumes conditional independence between features given the class.

Probabilistic Foundation: Bayes’ Theorem

We predict the class probability P(Ckx)P(C_k | \mathbf{x}) for an input feature vector x=[x1,x2,,xd]T\mathbf{x} = [x_1, x_2, \dots, x_d]^T using:

P(Ckx)=P(xCk)P(Ck)P(x)P(C_k | \mathbf{x}) = \frac{P(\mathbf{x} | C_k) P(C_k)}{P(\mathbf{x})}

The Conditional Independence Assumption

Estimating P(xCk)P(\mathbf{x} | C_k) directly requires massive datasets. The Naive Bayes classifier assumes that features are conditionally independent given the class:

P(xCk)=j=1dP(xjCk)P(\mathbf{x} | C_k) = \prod_{j=1}^{d} P(x_j | C_k)

Thus, the classification rule predicts the class that maximizes the numerator:

y^=argmaxkP(Ck)j=1dP(xjCk)\hat{y} = \arg\max_{k} P(C_k) \prod_{j=1}^{d} P(x_j | C_k)

The “Naive” Limitation

Features are rarely independent in practice, making the model “naive” (e.g., “machine” and “learning” are highly correlated), but it performs remarkably well on tasks like spam filtering.

Generative vs. Discriminative

Naive Bayes is a generative model because it models the joint distribution P(x,Ck)=P(xCk)P(Ck)P(\mathbf{x}, C_k) = P(\mathbf{x} | C_k) P(C_k), unlike discriminative models (e.g., Logistic Regression) which model P(Ckx)P(C_k | \mathbf{x}) directly.

Laplace Smoothing

If a feature value xjx_j never occurs with class CkC_k in training, the probability P(xjCk)P(x_j | C_k) is 00. Since we multiply feature probabilities, this zeroes out the entire class probability. We prevent this using Laplace Smoothing:

P(xj=vCk)=count(xj=v,Ck)+αcount(Ck)+αNjP(x_j = v | C_k) = \frac{count(x_j = v, C_k) + \alpha}{count(C_k) + \alpha \cdot N_j}

where NjN_j is the number of possible values for xjx_j, and α\alpha is the smoothing parameter.

Example: Classification with Gaussian Naive Bayes

The following example demonstrates training a Gaussian Naive Bayes model on continuous features:

python

Interactive Lab

Fit a Gaussian Naive Bayes classifier on continuous physical features and predict class probability distributions.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Test your understanding of the independence assumption:

What is the main drawback of the Naive Bayes conditional independence assumption?

Prior Probabilities

Priors P(Ck)P(C_k) reflect baseline class rates, acting as regularizers that bias predictions toward dominant classes.

References & Further Reading

Section Detail

k-Nearest Neighbors (kNN)

k-Nearest Neighbors (kNN) is a non-parametric, instance-based learning algorithm. Unlike parametric models such as linear regression or logistic regression, kNN does not explicitly learn a mapping function from the training data during a training phase. Instead, it memorizes the training dataset and performs classification or regression on the fly when a new data point is presented. Because the computational work is deferred until the prediction phase, kNN is often referred to as a “lazy learning” algorithm.

The core principle of kNN is that similar data points exist in close proximity. To classify a new, unseen data point, the algorithm identifies the kk training examples that are closest to it in the feature space and assigns a label based on the majority class among those neighbors.

Classification of New Data Points

The kNN algorithm for classification follows these steps:

  1. Calculate Distances: Compute the distance between the new data point and all points in the training dataset.
  2. Identify Nearest Neighbors: Select the kk training points with the smallest calculated distances.
  3. Determine the Majority Class: Count the class labels among the kk nearest neighbors. The new data point is assigned the class that appears most frequently (majority vote). In the case of a tie, the algorithm may resolve it randomly or weight the votes by the inverse of their distances.

Distance Metrics

The choice of distance metric fundamentally defines what it means for two data points to be “close.” Depending on the data type and dimensionality, different metrics are appropriate.

Euclidean Distance

The most common distance metric for continuous variables is the Euclidean distance, which represents the straight-line distance between two points in Euclidean space. For two vectors x=(x1,x2,,xn)\mathbf{x} = (x_1, x_2, \dots, x_n) and y=(y1,y2,,yn)\mathbf{y} = (y_1, y_2, \dots, y_n), the Euclidean distance is defined as:

d(x,y)=i=1n(xiyi)2d(\mathbf{x}, \mathbf{y}) = \sqrt{\sum_{i=1}^{n} (x_i - y_i)^2}

Manhattan Distance

Manhattan distance (also known as L1L_1 norm or city block distance) calculates the distance between two points by summing the absolute differences of their Cartesian coordinates. It is often preferred in high-dimensional spaces because it is less susceptible to the curse of dimensionality than Euclidean distance.

d(x,y)=i=1nxiyid(\mathbf{x}, \mathbf{y}) = \sum_{i=1}^{n} |x_i - y_i|

Minkowski Distance

Minkowski distance is a generalized metric that encompasses both Euclidean and Manhattan distances. It introduces a parameter pp:

d(x,y)=(i=1nxiyip)1pd(\mathbf{x}, \mathbf{y}) = \left( \sum_{i=1}^{n} |x_i - y_i|^p \right)^{\frac{1}{p}}

When p=1p=1, it is equivalent to the Manhattan distance, and when p=2p=2, it reduces to the Euclidean distance.

The Hyperparameter kk

The parameter kk represents the number of nearest neighbors considered during the voting process. It is a crucial hyperparameter that dictates the complexity and generalization capability of the model.

Impact of kk

  • Small kk (e.g., k=1k=1): The model is highly sensitive to noise in the training data. The decision boundary becomes complex and jagged, leading to low bias but high variance (overfitting). With k=1k=1, a new data point is assigned the exact class of its single closest neighbor.
  • Large kk: The voting process incorporates a broader region of the feature space, resulting in smoother, more robust decision boundaries. However, if kk is too large, the model may suffer from high bias (underfitting), as it risks simply predicting the majority class of the entire dataset regardless of the specific input location.

Even or Odd kk

In binary classification problems (where there are only two possible classes), it is critical to choose an odd value for kk. If an even kk is selected, there is a possibility of a tie in the majority voting process. An odd kk inherently prevents tied votes, ensuring a definitive class assignment for every new data point. For multi-class problems, ties can still occur with an odd kk, but they are significantly less frequent.

The Importance of Scaling

kNN is highly sensitive to the scale of the features. Because the algorithm relies entirely on distance calculations, features with larger ranges will disproportionately influence the final distance metric.

Consider a dataset with two features: age (ranging from 18 to 80 years) and income (ranging from $20,000 to $150,000). If the Euclidean distance is calculated without scaling, the income feature will completely dominate the distance computation, rendering the age feature effectively irrelevant.

To prevent this, it is mandatory to normalize or standardize the data before applying kNN.

  • Min-Max Scaling (Normalization): Rescales features to a fixed range, typically [0,1][0, 1].
  • Standardization (Z-score scaling): Transforms features to have a mean of 0 and a standard deviation of 1.

By ensuring all features contribute equally to the distance calculation, scaling significantly improves the performance and reliability of the kNN algorithm.

Exercise

Evaluate your understanding of kNN properties:

Why is it important to use an odd value for k in binary classification?

References & Further Reading

Section Detail

Support Vector Machines

Support Vector Machines

A Support Vector Machine (SVM) is a supervised algorithm that finds the decision boundary (hyperplane) that maximizes the margin between classes.

Margin Maximization and Slack Variables

In linear classification, we find a hyperplane wTx+b=0w^T x + b = 0 that separates classes.

Primal Optimization Problem (Soft Margin)

To allow for noise and misclassifications, we introduce slack variables ξi0\xi_i \ge 0. The objective minimizes:

minw,b,ξ12w2+Ci=1mξi\min_{w, b, \xi} \frac{1}{2} ||w||^2 + C \sum_{i=1}^{m} \xi_i

subject to:

y(i)(wTx(i)+b)1ξiandξi0y^{(i)} (w^T x^{(i)} + b) \ge 1 - \xi_i \quad \text{and} \quad \xi_i \ge 0

The parameter CC controls the trade-off: a small CC allows more margin violations (regularized), while a large CC forces a hard margin (sensitive to noise).

The Dual Formulation and the Kernel Trick

By reformulating the optimization problem using Lagrange multipliers, we express the decision function using inner products of training instances:

h(x)=i=1mαiy(i)(x(i)x)+bh(x) = \sum_{i=1}^{m} \alpha_i y^{(i)} (x^{(i)} \cdot x) + b

The coefficients αi\alpha_i are non-zero only for instances on the margin boundaries. These are the Support Vectors that determine the decision boundary.

The Kernel Trick

The kernel trick replaces the dot product with a kernel function K(x(i),x(j))K(x^{(i)}, x^{(j)}), avoiding mapping data to high-dimensional spaces explicitly.

  • Polynomial Kernel: K(x,z)=(γxTz+r)dK(x, z) = (\gamma x^T z + r)^d
  • Radial Basis Function (RBF) Kernel: K(x,z)=exp(γxz2)K(x, z) = \exp(-\gamma ||x - z||^2)

The parameter γ\gamma controls the RBF width: a larger γ\gamma makes the boundary narrower and more irregular, fitting specific instances.

Example: Non-Linear Kernel SVM

The following example demonstrates training an SVM with an RBF kernel:

python

Interactive Lab

Train an RBF kernel SVM to solve the non-linear XOR problem. Inspect the support vectors selected by the model.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Test your understanding of SVM margin constraints:

What happens to the decision boundary if we increase the hyperparameter C to infinity?

References & Further Reading

Section Detail

Decision Trees

Decision Trees and the CART Algorithm

Decision Trees are non-parametric models that recursively partition the feature space, predicting targets using simple hierarchical decision rules.

Recursive Induction: The CART Algorithm

The CART algorithm builds binary trees by searching for a feature kk and threshold tkt_k that minimize the weighted impurity of child nodes.

J(k,tk)=mleftmIleft+mrightmIrightJ(k, t_k) = \frac{m_{\text{left}}}{m} I_{\text{left}} + \frac{m_{\text{right}}}{m} I_{\text{right}}

where II represents the impurity of a node, and mm is the number of samples.

Split Selection Logic

The CART algorithm is greedy: it searches for the best split at the current step rather than evaluating combinations globally. It does not guarantee finding the globally optimal tree.

Impurity Measures

  • Gini Impurity: Probability of a random element being misclassified. G=1i=1Cpi2G = 1 - \sum_{i=1}^{C} p_i^2
  • Entropy: Quantifies node disorder or uncertainty. H=i=1Cpilog2(pi)H = -\sum_{i=1}^{C} p_i \log_2(p_i)

For regression trees, CART minimizes Mean Squared Error (MSE), and leaves predict the average target value.

Regularization

Without constraints, decision trees grow until leaves are pure, causing overfitting. We regularize using stopping hyperparameters:

  • max_depth: Limits depth.
  • min_samples_split: Minimum samples required to split a node.
  • min_samples_leaf: Minimum samples a leaf must contain.
Code
skinparam backgroundColor transparent
rectangle "Is Feature X <= 2.5?" as Root
rectangle "Leaf: Class A" as Left
rectangle "Leaf: Class B" as Right
Root --> Left : Yes
Root --> Right : No
Is Feature X <= 2.5?Leaf: Class ALeaf: Class BYesNo

Example: Computing Impurity

The following example demonstrates calculating Gini impurity and Information Gain:

python

Interactive Lab

Compute the Gini Impurity of a mixed parent node and its child nodes after a split. Change the class split distributions to see how purity changes.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Test your understanding of Decision Tree scaling requirements:

Why do Decision Trees not require input feature scaling (e.g., Standardization)?

References & Further Reading

Section Detail

Ensemble Learning

Ensemble Learning and Random Forests

Ensemble methods combine predictions from multiple base models to build a stronger predictor with improved generalization.

Voting Classifiers

Ensemble models aggregate individual predictions using different consensus rules:

  • Hard Voting: predicts the class that receives the absolute majority of votes from the base estimators.
  • Soft Voting: averages the predicted class probabilities across all estimators, prioritizing confident predictions. This requires all estimators to support probability calculation.

Bagging and Pasting

Rather than using diverse algorithms, we can train multiple instances of the same base algorithm on different random subsets of the training set to construct homogeneous ensembles:

  • Bagging (Bootstrap Aggregating): sampling is performed with replacement, allowing the same data point to be selected multiple times across different subsets.
  • Pasting: sampling is performed without replacement, ensuring each subset contains unique data points.

Out-of-Bag (OOB) Evaluation

With bagging, statistical probability dictates that about 37% of the training instances are never sampled for any single estimator. These are known as Out-of-Bag (OOB) instances. Evaluating the ensemble’s performance on these OOB instances provides an unbiased validation score without requiring a separate validation dataset.

Random Forests

A Random Forest is an ensemble of decision trees trained via bagging. Tree splits are evaluated on random feature subsets to reduce estimator correlation and variance.

Example: Ensemble Voting Classifier

The following example demonstrates building a Voting Classifier:

python

Interactive Lab

Train individual estimators (Logistic Regression, Decision Tree) and combine them into a soft Voting Classifier ensemble to observe performance updates.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Test your understanding of bootstrap aggregation:

Why does bagging typically reduce model variance without increasing model bias?

References & Further Reading

Section Detail

Gradient Boosting Systems

Gradient Boosting Systems

Boosting methods train predictors sequentially, with each model attempting to correct its predecessor’s errors.

AdaBoost (Adaptive Boosting)

AdaBoost focuses on misclassified instances by adjusting their weights:

  1. Initialize all instance weights to w(i)=1/mw^{(i)} = 1/m.
  2. Train a base predictor and calculate its weighted error rate rjr_j.
  3. Compute the predictor weight αj=ηlog((1rj)/rj)\alpha_j = \eta \log((1-r_j)/r_j), where η\eta is the learning rate.
  4. Update instance weights: increase weights for misclassified instances and decrease them for correctly classified instances.
  5. Normalize weights and repeat.

Gradient Boosting

Unlike AdaBoost, Gradient Boosting trains models on the residual errors of the previous predictor.

For regression with squared error loss, the target for predictor ht(x)h_t(x) is the residual:

rt(i)=y(i)k=1t1ηhk(x(i))r_t^{(i)} = y^{(i)} - \sum_{k=1}^{t-1} \eta h_k(x^{(i)})

The final prediction aggregates all estimators:

y^(i)=t=1Tηht(x(i))\hat{y}^{(i)} = \sum_{t=1}^{T} \eta h_t(x^{(i)})

In classification, Gradient Boosting fits new trees to minimize the pseudo-residuals of the loss function, which are the negative gradients of the loss.

Histogram-Based Gradient Boosting

Modern implementations (like XGBoost, LightGBM, and scikit-learn’s HistGradientBoostingRegressor) bin continuous features into integer bins (e.g., 256 bins). This reduces the computational complexity of finding splits from O(300×nlogn)O(300 \times n \log n) to O(300×n bins)O(300 \times n \text{ bins}), speeding up training on large datasets.

Example: Residual Learning

The following example demonstrates fitting successive decision trees to residual errors:

python

Interactive Lab

Fit sequential regression trees to residual errors to simulate a simple Gradient Boosting step-by-step pipeline.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Test your understanding of the boosting process:

What happens if the learning rate parameter is set too high in a Gradient Boosting model?

Shrinkage and Estimator Limits

In gradient boosting, learning rate η\eta is also known as shrinkage. A low learning rate (e.g., η=0.01\eta = 0.01) paired with more trees allows the model to converge smoothly, increasing generalization performance on tabular data.

References & Further Reading

Unsupervised Learning

Section Detail

Principal Component Analysis

High-dimensional spaces suffer from the Curse of Dimensionality: points are sparse, distances become uniform, and models overfit. Dimensionality reduction compresses features, removes redundancies, and enables visualization. Principal Component Analysis (PCA) projects data onto a lower-dimensional subspace while maximizing variance preservation.

Matrix Factorization: SVD

PCA identifies the axis that accounts for the largest amount of variance in the training set. It finds principal components using Singular Value Decomposition (SVD), which decomposes the centered design matrix XX into three matrices:

X=UΣVTX = U \Sigma V^T

The matrix VV contains the unit vectors that define the principal components:

V=[v1,v2,,vn]V = [\mathbf{v}_1, \mathbf{v}_2, \dots, \mathbf{v}_n]

To project the training set down to dd dimensions, we multiply the design matrix by the matrix VdV_d containing the first dd principal components:

Xd-proj=XVdX_{d\text{-proj}} = X V_d

The Eigendecomposition Approach

Alternatively, PCA can be computed by performing an eigendecomposition on the Sample Covariance Matrix of the centered data. The covariance matrix CC captures the variance and correlation of features:

C=1m1XTXC = \frac{1}{m-1} X^T X

By solving the characteristic equation, we decompose CC into its eigenvalues (λ\lambda) and eigenvectors (v\mathbf{v}):

Cv=λvC \mathbf{v} = \lambda \mathbf{v}

  • The Eigenvectors represent the directions of the principal components (equivalent to the columns of VV from SVD). They are orthogonal to each other.
  • The Eigenvalues represent the magnitude of variance captured along each corresponding principal component.

The Trace of the covariance matrix (the sum of its diagonal elements) is equal to the total variance in the dataset. Consequently, the sum of all eigenvalues is also equal to the total variance, allowing us to compute the proportion of variance captured by any single principal component ii as λiλ\frac{\lambda_i}{\sum \lambda}.

Explained Variance Ratio

The explained variance ratio indicates the proportion of the dataset’s variance that lies along each principal component. We use it to choose the number of dimensions dd that preserve a target percentage of variance (e.g., 95%).

Incremental PCA

For large datasets that do not fit in memory, we use Incremental PCA (IPCA). The algorithm splits the training set into mini-batches and feeds them one by one, enabling dimensionality reduction on out-of-core data.

Example: Computing PCA

The following example demonstrates projecting data using PCA and calculating the explained variance ratio:

python

Interactive Lab

Reduce a synthetic 3D dataset to 2D using Principal Component Analysis (PCA) and examine the explained variance ratios.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Evaluate your understanding of PCA projection logic:

Why must the design matrix X be centered (zero mean) before applying SVD for PCA?

Choosing the Number of Components

Instead of selecting an arbitrary number of dimensions, we look at the cumulative explained variance plot. We choose the number of principal components that capture a target percentage (typically 95%) of the total variance. This ensures that we discard noise while preserving the essential geometric structure of the original data.

References & Further Reading

Section Detail

Clustering Algorithms

Clustering Algorithms

Clustering partitions unlabeled data into groups (clusters) of similar instances.

Centroid-Based: K-Means

K-Means partitions data into KK clusters by minimizing the Within-Cluster Sum of Squares (Inertia):

J=j=1KxCjxμj2J = \sum_{j=1}^{K} \sum_{x \in C_j} ||x - \mu_j||^2

Lloyd’s Algorithm

  1. Initialize KK centroids μj\mu_j randomly (or using K-Means++).
  2. Assign each instance to its closest centroid: c(i)=argminjx(i)μj2c^{(i)} = \arg\min_j ||x^{(i)} - \mu_j||^2.
  3. Update centroids: μj=1CjxCjx\mu_j = \frac{1}{|C_j|} \sum_{x \in C_j} x.
  4. Repeat steps 2-3 until convergence.

K-Means++ initialization spreads centroids far apart during initialization, reducing the risk of converging to sub-optimal local minima.

Density-Based: DBSCAN

DBSCAN groups points based on local density, classifying them into three categories:

  • Core Points: At least MinPts neighbors within a radius of ϵ\epsilon.
  • Border Points: Not core points, but within ϵ\epsilon of a core point.
  • Noise Points: Neither core nor border points.

DBSCAN detects the number of clusters automatically and handles outliers effectively by marking them as noise.

Hierarchical (Agglomerative) Clustering

Agglomerative clustering is a “bottom-up” approach. It begins by treating every single data point as its own cluster. It then iteratively merges the closest pairs of clusters until all points are merged into a single root cluster.

  • Dendrogram: This merging process is visualized as a tree-like diagram called a dendrogram. By analyzing the vertical height of the branches in the dendrogram, one can decide on an optimal number of clusters by cutting the tree horizontally.
  • WCSS: Within-Cluster Sum of Squares can also be used as a metric to evaluate cluster cohesion.

Linkage Criteria

The decision of which clusters to merge depends on the defined distance (linkage) between clusters:

  • Single Linkage: The distance between two clusters is defined by their two closest members.
  • Complete Linkage: The distance is defined by their two furthest members.
  • Average Linkage: The average distance between all points in the two clusters.
  • Ward’s Linkage: Merges clusters in a way that minimizes the total variance within all clusters.

Probabilistic: Gaussian Mixture Models

Gaussian Mixture Models (GMM) represent clusters as covariance ellipsoids rather than spheres, allowing for varying cluster shapes. GMM uses the Expectation-Maximization (EM) algorithm to assign “soft clustering” probabilities.

Example: Comparing Algorithms

The following example demonstrates clustering using scikit-learn:

python

Interactive Lab

Compare K-Means and DBSCAN clustering on non-linear crescent-shaped data. Observe how K-Means struggles with complex shapes while DBSCAN correctly groups them.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Test your understanding of clustering paradigms:

Which algorithm is most appropriate for a dataset where clusters have non-spherical, interlocking crescent shapes?

Selecting the Number of Clusters

Choosing the parameter KK in K-Means is challenging. We use two main validation methods:

  • The Elbow Method: Plotting inertia vs. KK and finding the point where the rate of decrease drops.
  • Silhouette Analysis: Computing the average silhouette coefficient for all points. A higher average coefficient indicates well-defined, dense clusters.

References & Further Reading

Deep Learning

Section Detail

Numerical Optimization

Optimization

Training models requires finding parameters θ\theta that minimize a cost function J(θ)J(\theta) by updating them iteratively.

Stochastic Gradient Descent (SGD)

SGD updates parameters using the gradient calculated from a single random instance (or a mini-batch) at each step:

θθηθJ(θ;x(i),y(i))\theta \leftarrow \theta - \eta \nabla_{\theta} J(\theta; x^{(i)}, y^{(i)})

While computationally efficient, SGD’s updates can oscillate, slowing convergence.

Momentum and Nesterov Accelerated Gradient

Momentum accelerates SGD by adding a fraction β\beta of the previous update vector mm, acting like a physical ball rolling down a hill:

mβm+ηθJ(θ)m \leftarrow \beta m + \eta \nabla_{\theta} J(\theta) θθm\theta \leftarrow \theta - m

NAG calculates the gradient ahead of the current position (J(θβm)J(\theta - \beta m)) to stabilize convergence.

Adaptive Learning Rates

Adaptive algorithms adjust the learning rate per parameter based on historical gradients:

  • RMSProp: Decays past squared gradients to focus on recent updates. sβs+(1β)(θJ(θ))2s \leftarrow \beta s + (1 - \beta) (\nabla_{\theta} J(\theta))^2 θθηs+ϵθJ(θ)\theta \leftarrow \theta - \frac{\eta}{\sqrt{s + \epsilon}} \nabla_{\theta} J(\theta)
  • Adam (Adaptive Moment Estimation): Tracks first (mean) and second (variance) moments of the gradients: mβ1m+(1β1)θJ(θ)m \leftarrow \beta_1 m + (1 - \beta_1) \nabla_{\theta} J(\theta) sβ2s+(1β2)(θJ(θ))2s \leftarrow \beta_2 s + (1 - \beta_2) (\nabla_{\theta} J(\theta))^2

Bias correction is applied: m^=m/(1β1t)\hat{m} = m/(1-\beta_1^t) and s^=s/(1β2t)\hat{s} = s/(1-\beta_2^t).

AdamW (Weight Decay)

AdamW improves on Adam by applying weight decay directly to the parameters rather than incorporating it into the gradient update step.

Example: Optimizing Parameters

The following example demonstrates parameter optimization using Adam in PyTorch:

python

Interactive Lab

Minimize a quadratic function using the Adam optimizer in PyTorch. Observe how w converges toward zero over 5 gradient update steps.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Test your understanding of adaptive optimization updates:

Why is bias correction necessary in the Adam optimizer?

References & Further Reading

Section Detail

Neural Networks Foundations

Neural Networks Foundations

Artificial Neural Networks (ANNs) are computational models inspired by biological neural networks, structured as layers of interconnected nodes.

The Perceptron

The Perceptron is the simplest ANN architecture, computing a weighted sum of inputs plus a bias, and applying a step function:

y^=step(z)=step(wTx+b)\hat{y} = \text{step}(z) = \text{step}(w^T x + b)

A single Perceptron is a linear classifier, meaning it cannot solve non-linearly separable problems (like the XOR problem).

Multilayer Perceptron (MLP)

An MLP consists of an input layer, one or more hidden layers, and an output layer. Hidden layers allow the model to learn non-linear representations.

Forward Propagation

For layer ll, the activations a(l)a^{(l)} are computed using the weight matrix W(l)W^{(l)} and bias vector b(l)b^{(l)}:

z(l)=W(l)a(l1)+b(l)z^{(l)} = W^{(l)} a^{(l-1)} + b^{(l)} a(l)=ϕ(z(l))a^{(l)} = \phi(z^{(l)})

where ϕ\phi is the activation function.

Activation Functions

Non-linear activation functions prevent stacked layers from collapsing into a single linear model:

  • Sigmoid: σ(z)=1/(1+ez)\sigma(z) = 1 / (1 + e^{-z}), squashing outputs to (0,1)(0, 1).
  • Tanh: tanh(z)=(ezez)/(ez+ez)\tanh(z) = (e^z - e^{-z}) / (e^z + e^{-z}), squashing to (1,1)(-1, 1).
  • ReLU: ReLU(z)=max(0,z)\text{ReLU}(z) = \max(0, z), preventing vanishing gradients.
  • ELU: ELU(z)=max(α(ez1),z)\text{ELU}(z) = \max(\alpha(e^z - 1), z), preventing dying neurons with small negative values.

Backpropagation

Backpropagation trains networks by computing the gradient of the loss function with respect to the weights using the chain rule of calculus, working backward from the output layer:

LW(l)=Lz(l)(a(l1))T\frac{\partial L}{\partial W^{(l)}} = \frac{\partial L}{\partial z^{(l)}} (a^{(l-1)})^T

The error term δ(l)=Lz(l)\delta^{(l)} = \frac{\partial L}{\partial z^{(l)}} is computed recursively from the output error using matrix multiplications.

Example: Forward Pass Calculations

The following example demonstrates calculating the forward pass of a single neuron using NumPy:

python

Interactive Lab

Compute the forward pass of a single neuron using weights, biases, and a ReLU activation function. Modify the input values to see if the neuron activates.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Test your understanding of activation functions:

Why did the deep learning community transition from Sigmoid activations to ReLU activations in hidden layers?

References & Further Reading

Section Detail

Convolutional Neural Networks

Convolutional Neural Networks

Convolutional Neural Networks (CNNs) are specialized neural architectures designed to process grid-structured data, such as images, by exploiting spatial hierarchies.

Convolutional Layers

Unlike fully connected layers where neurons connect to all inputs, convolutional layers connect only to a local receptive field.

Filters and Feature Maps

A layer applies learnable filters (kernels). As a filter slides, it computes dot products, producing a feature map.

Output Dimension Formula

Given input height HinH_{\text{in}}, filter size FF, padding PP, and stride SS, the output height HoutH_{\text{out}} is:

Hout=HinF+2PS+1H_{\text{out}} = \lfloor \frac{H_{\text{in}} - F + 2P}{S} \rfloor + 1

  • Padding (PP): Adding zero-pixels around the border to preserve spatial dimensions.
  • Stride (SS): The step size of the filter as it slides across the input.

Translation Invariance

CNNs build translation invariance: if a pattern (like a cat’s ear) is learned in one part of the image, the convolutional filters can recognize it anywhere else. This parameter sharing significantly reduces model parameter counts compared to MLPs.

Pooling Layers

Pooling layers reduce the spatial size of feature maps to decrease parameter counts and build translation invariance.

  • Max Pooling: Extracts the maximum value from each receptive patch.
  • Average Pooling: Computes the average value of each patch.

ResNet and Residual Connections

Deep CNNs suffer from vanishing gradients. ResNet resolves this using Residual Connections (skip connections) that bypass layers:

a(l)=ϕ(W(l)a(l1)+b(l)+a(l1))a^{(l)} = \phi(W^{(l)} a^{(l-1)} + b^{(l)} + a^{(l-1)})

This allows gradients to flow directly backward, enabling the training of deep networks.

Example: Output Shapes

The following example calculates the output dimensions of a convolutional layer:

python

Interactive Lab

Calculate the output dimensions of a Convolutional Layer based on input dimension, filter size, padding, and stride. Edit these parameters to see how layer sizes transition.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Test your understanding of CNN operations:

What is the primary purpose of pooling layers in a CNN?

Receptive Fields and Hierarchies

Early layers detect simple edges, while deeper layers combine these features to recognize complex shapes and objects, building a hierarchical spatial representation.

References & Further Reading

Section Detail

Natural Language Processing

Natural Language Processing

Natural Language Processing (NLP) focuses on translating text sequences into mathematical representations that algorithms can learn from.

Statistical Representation: TF-IDF

TF-IDF (Term Frequency-Inverse Document Frequency) measures how important a word is to a document in a corpus:

TF-IDF(t,d,D)=TF(t,d)×log(D1+{dD:td})\text{TF-IDF}(t, d, D) = \text{TF}(t, d) \times \log\left(\frac{|D|}{1 + |\{d \in D : t \in d\}|}\right)

While effective for classification, TF-IDF ignores word order and semantic similarity.

Sequence Modeling: RNNs and Attention

To handle sequential context, Recurrent Neural Networks (RNNs) maintain a hidden state vector hth_t that updates at each step:

ht=tanh(Whhht1+Wxhxt+bh)h_t = \tanh(W_{hh} h_{t-1} + W_{xh} x_t + b_h)

The Bottleneck of RNNs

RNNs struggle with long-term dependencies because gradients vanish over long sequence lengths. While LSTM (Long Short-Term Memory) and GRU (Gated Recurrent Unit) architectures use gating mechanisms to help, they still process tokens sequentially, which limits parallel training.

Self-Attention and the Transformer

The Transformer architecture replaces recurrent loops with Self-Attention. For queries QQ, keys KK, and values VV, attention weights are computed in parallel:

Attention(Q,K,V)=Softmax(QKTdk)V\text{Attention}(Q, K, V) = \text{Softmax}\left(\frac{Q K^T}{\sqrt{d_k}}\right) V

where dkd_k is the dimension of the key vectors. This allows the model to capture relationships between words regardless of their distance in the sequence. Positional encodings are added to the input embeddings to represent sequence order. Transformers process the entire sequence in parallel via multi-head attention, capturing complex relationships between distant words. This represents a significant advancement over sequential RNN processing.

Example: TF-IDF Vectorization

The following example demonstrates tokenizing and vectorizing text using TF-IDF:

python

Interactive Lab

Tokenize and vectorize a small text corpus using Term Frequency-Inverse Document Frequency (TF-IDF) in scikit-learn.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Validate your understanding of text vectorization properties:

Why does TF-IDF generally perform better than simple term count vectorization for keyword search tasks?

References & Further Reading

MLOps & System Deployment

Section Detail

Machine Learning Operations

Machine Learning Operations (MLOps)

MLOps standardizes the automation, deployment, and monitoring of production ML systems.

Model Decay and Drift

Unlike traditional software, ML models decay in production as real-world data distributions drift:

  • Data Drift: statistical properties of inputs change (P(Xprod)P(Xtrain)P(X_{\text{prod}}) \neq P(X_{\text{train}})) due to demographic or environment shifts.
  • Concept Drift: relationships between inputs and targets change (P(YXprod)P(YXtrain)P(Y|X_{\text{prod}}) \neq P(Y|X_{\text{train}})) due to structural changes (e.g., macroeconomics).

MLOps Core Architecture

Production MLOps pipelines introduce Continuous Training (CT) alongside CI/CD:

Code
skinparam backgroundColor transparent
rectangle "Feature Store" as Data
rectangle "CT Pipeline" as CT
rectangle "Model Registry" as Registry
rectangle "Production API" as Prod
rectangle "Drift Monitor" as Mon
Data --> CT : training data
CT --> Registry : registers binary
Registry --> Prod : rolls out model
Prod --> Mon : logs inference
Mon --> Data : triggers CT on drift
Feature StoreCT PipelineModel RegistryProduction APIDrift Monitortraining dataregisters binaryrolls out modellogs inferencetriggers CT on drift

Core Components

  • Feature Store: stores standardized features for training/inference, preventing serve skew.
  • Model Registry: catalogs model binaries, metadata, and version tags.
  • Metadata Store: logs hyperparameters and evaluation histories.
  • Data Versioning (DVC): tracks datasets using git-like hashes.

MLOps Maturity Levels

  • Level 0: manual training and deployment. No automated tracking.
  • Level 1: automated model retraining (CT) triggered by drift.
  • Level 2: automated CI/CD pipelines deploy both code and retraining steps.

Example: Simulating Drift Detection

The following example demonstrates a basic drift detection agent comparing production feature means with the training baseline:

python

Interactive Lab

Simulate feature drift detection by comparing incoming production means against training baselines.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Test your understanding of concept and data drift mechanisms:

Which of the following scenarios describes concept drift rather than data drift?

References & Further Reading

Section Detail

Recommender Systems

Recommender Systems

Recommender systems suggest items to users based on historical interaction patterns and profile attributes.

Collaborative Filtering

Collaborative filtering recommends items based on the behavior of similar users.

Cosine Similarity

We measure the similarity between user rating vectors u\mathbf{u} and v\mathbf{v} via:

Sim(u,v)=uvuv\text{Sim}(\mathbf{u}, \mathbf{v}) = \frac{\mathbf{u} \cdot \mathbf{v}}{||\mathbf{u}|| ||\mathbf{v}||}

Predictions are weighted averages of ratings from similar users.

Matrix Factorization (Latent Factor Models)

Matrix Factorization decomposes the sparse user-item rating matrix RR of shape (m,n)(m, n) into two lower-rank matrices: PP of shape (m,k)(m, k) and QQ of shape (n,k)(n, k), representing user and item latent factor embeddings:

RPQTR \approx P Q^T

We find matrices PP and QQ by minimizing the squared error over observed ratings, applying regularization to prevent overfitting:

minP,Q(u,i)K(rui(μ+bu+bi+puTqi))2+λ(pu2+qi2)\min_{P, Q} \sum_{(u,i) \in K} (r_{ui} - (\mu + b_u + b_i + \mathbf{p}_u^T \mathbf{q}_i))^2 + \lambda (||\mathbf{p}_u||^2 + ||\mathbf{q}_i||^2)

where KK is the set of user-item pairs with observed ratings, μ\mu is the global average rating, and bu,bib_u, b_i are user and item bias parameters. Biases isolate systematic offsets (e.g., users who always rate critically, or items that are universally liked).

Cold Start Problem

Latent factor models struggle when a new user or item joins because interaction data is missing. Hybrid systems mitigate this by utilizing content metadata (e.g., genre, age).

Example: Computing Embedding Similarity

The following example demonstrates calculating the cosine similarity between item latent embeddings:

python

Interactive Lab

Calculate the cosine similarity between item latent factor vectors (embeddings) to evaluate collaborative recommendation links.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Test your understanding of matrix factorization limits:

Why are biases (user bias and item bias) typically added to the prediction formula in Matrix Factorization?

Regularization

The L2 regularizer parameter λ\lambda prevents user/item embedding parameters from growing too large during updates, mitigating overfitting.

References & Further Reading

Section Detail

Reinforcement Learning

Reinforcement Learning and Q-Learning

Reinforcement Learning (RL) is a paradigm where an agent learns to make sequences of decisions in an environment to maximize its cumulative long-term reward.

Markov Decision Processes (MDP)

An MDP provides a formal mathematical framework for modeling decision-making under uncertainty, defined by:

  • States (SS): The set of all possible environmental states.
  • Actions (AA): The set of actions available to the agent.
  • Transition Probability P(ss,a)P(s' | s, a): The probability of transition to state ss' given action aa in state ss.
  • Reward Function R(s,a,s)R(s, a, s'): The immediate reward received after transitioning.

The Bellman Optimality Equation

The objective is to find a policy π(s)\pi(s) that maximizes the expected discounted return Gt=k=0γkRt+k+1G_t = \sum_{k=0}^{\infty} \gamma^k R_{t+k+1}, where γ[0,1)\gamma \in [0, 1) is the discount factor.

The optimal action-value function Q(s,a)Q^*(s, a) satisfies the Bellman Optimality Equation:

Q(s,a)=sP(ss,a)[R(s,a,s)+γmaxaQ(s,a)]Q^*(s, a) = \sum_{s'} P(s' | s, a) \left[ R(s, a, s') + \gamma \max_{a'} Q^*(s', a') \right]

Q-Learning (Model-Free Control)

When transition probabilities P(ss,a)P(s'|s,a) are unknown, the agent learns QQ-values through experience using temporal difference updates:

Q(s,a)Q(s,a)+α[r+γmaxaQ(s,a)Q(s,a)]Q(s, a) \leftarrow Q(s, a) + \alpha \left[ r + \gamma \max_{a'} Q(s', a') - Q(s, a) \right]

where α\alpha is the learning rate, and rr is the immediate reward.

Deep Q-Networks (DQN)

In large state spaces, we replace the lookup table Q(s,a)Q(s, a) with a neural network Q(s,a;θ)Q(s, a; \theta) parameterized by weights θ\theta. We train the network by minimizing the loss against a target value:

y=r+γmaxaQ(s,a;θ)y = r + \gamma \max_{a'} Q(s', a'; \theta^{-})

where θ\theta^{-} represents the weights of a separate target network updated periodically to stabilize training. We use an Experience Replay Buffer to store state transitions, breaking sample correlation and stabilizing updates.

Example: Q-Learning Update Step

The following example demonstrates a single Q-learning update step:

python

Interactive Lab

Perform a Temporal Difference (TD) Q-learning update calculation for a single state transition, updating its action-value rating.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Test your understanding of the discount factor parameter:

What happens to an RL agent's behavior if the discount factor gamma is set close to zero?

Dimensional Complexity

Tabular Q-learning is limited to small discrete environments. Continuous, high-dimensional spaces require deep neural network function approximators (DQNs).

References & Further Reading

Section Detail

Ethics in Machine Learning

Ethics in Machine Learning

As machine learning systems are increasingly deployed to automate high-stakes decisions, it is critical to address algorithmic bias and ensure fairness.

Sources of Algorithmic Bias

Algorithmic bias arises at multiple pipeline stages:

  • Historical Bias: training data reflects existing systemic human prejudices.
  • Representation Bias: sample underrepresents demographics, raising error rates for minorities.
  • Measurement Bias: collected features are noisy, poor proxies of the target task.

Mathematical Definitions of Fairness

Fairness is defined mathematically, but different metrics are often mutually exclusive. Let AA be a sensitive attribute (e.g., race, gender), XX be the remaining features, YY be the true label, and Y^=f(X)\hat{Y} = f(X) be the model prediction.

1. Demographic Parity (Statistical Parity)

The likelihood of receiving a positive prediction is independent of the sensitive attribute:

P(Y^=1A=0)=P(Y^=1A=1)P(\hat{Y} = 1 | A = 0) = P(\hat{Y} = 1 | A = 1)

2. Equal Opportunity

The true positive rate (recall) is equal across all demographic groups:

P(Y^=1A=0,Y=1)=P(Y^=1A=1,Y=1)P(\hat{Y} = 1 | A = 0, Y = 1) = P(\hat{Y} = 1 | A = 1, Y = 1)

3. Predictive Parity

The precision (positive predictive value) is equal across all demographic groups:

P(Y=1A=0,Y^=1)=P(Y=1A=1,Y^=1)P(Y = 1 | A = 0, \hat{Y} = 1) = P(Y = 1 | A = 1, \hat{Y} = 1)

These definitions are mathematically incompatible if the base rates differ between demographic groups, meaning a model cannot satisfy all of them simultaneously unless it makes perfect predictions.

Example: Evaluating Fairness

The following example calculates demographic parity difference between two groups:

python

Interactive Lab

Evaluate Demographic Parity by calculating the difference in selection rates between two demographic groups. Adjust the predictions to see if you can reduce the difference to zero.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Test your understanding of mathematical fairness constraints:

Why is it mathematically impossible to satisfy demographic parity, equal opportunity, and predictive parity simultaneously in a non-trivial predictor?

References & Further Reading