A mathematical and algorithmic journey through the systems that learn from data, from linear models to deep neural architectures.
July 2026
Machine learning allows computers to learn from experience rather than explicit developer rules. Formally, a program learns from experience with respect to a class of tasks and performance measure , if its performance at tasks in , as measured by , improves with experience .
Algorithms are structured by their learning feedback:
Learning is formulated as empirical risk minimization. Given a hypothesis space and a loss function , we solve for a hypothesis that minimizes the average loss over the training set:
A model’s generalization error on unseen data is decomposed into three components:
Generalization is evaluated by training parameters on a training set and testing performance on an independent test set.
The following example demonstrates splitting data and verifying shapes to ensure proper evaluation setup:
Partition a dataset into independent training and test sets using scikit-learn. Adjust test_size to observe how split shapes change.
Validate your understanding of generalization error trade-offs:
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.
Binary classification performance is tabulated in a Confusion Matrix:
| Predicted Positive | Predicted Negative | |
|---|---|---|
| Actual Positive | True Positive (TP): 80 | False Negative (FN): 20 |
| Actual Negative | False Positive (FP): 10 | True Negative (TN): 90 |
In this disease-screening example with 200 samples:
The ROC curve plots True Positive Rate (Recall) against False Positive Rate () across decision thresholds. The Area Under the Curve (AUC) ranges from (random) to (perfect).
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 (). 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).
The score represents the proportion of variance explained by the model:
Proper validation is crucial for an iterative ML workflow to prevent overfitting and ensure model generalization.
The following example demonstrates calculating classification metrics using a confusion matrix in scikit-learn:
Compute Precision, Recall, and F1 Score using scikit-learn metrics. Modify the ground truth labels or predictions to see how the scores change.
Validate your knowledge of classification metric trade-offs:
Preprocessing transforms raw data into numerical matrices optimized for training.
Real-world datasets are rarely perfect. Data may be missing due to sensor failures, non-responses, or unrecorded events.
Outliers are extreme values that can significantly skew statistical measures and models like Linear Regression. Depending on the context, we can:
Boxplots are visual tools commonly used to identify outliers. They display the interquartile range (IQR) of data, with points falling outside typically flagged as outliers.
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:
Models require numerical inputs. Categorical and textual data must be encoded:
Disparate scales bias distance-based models (KNN, SVM). We scale features via:
Linear relationships are analyzed using a Correlation Matrix of Pearson coefficients in the range . Below is an example mapping features from a real estate dataset:
| House Size | Num Bedrooms | Distance to Center | |
|---|---|---|---|
| House Size | 1.00 | 0.85 | -0.60 |
| Num Bedrooms | 0.85 | 1.00 | -0.45 |
| Distance to Center | -0.60 | -0.45 | 1.00 |
The diagonal represents self-correlation. The coefficient indicates a strong positive relationship between size and bedrooms, while shows a negative relationship with center distance (further houses tend to be smaller).
The following example demonstrates categorical one-hot encoding and standardization:
Scale continuous features using standardization and encode categorical features using one-hot encoding.
Evaluate your understanding of data preprocessing constraints:
Preprocessing parameters must fit only on training data. Fitting on all data leaks test set statistics, inflating validation scores.
Machine learning development is an iterative lifecycle accommodating data variability.
The development lifecycle consists of sequential phases and feedback loops:
Developing machine learning systems involves three distinct architectural flows depending on the operational stage:
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.
Focused on automation and scalability. Notebook experiments are codified into structured, reproducible pipelines:
Deployment layouts depend on latency and throughput constraints:
Scikit-learn Pipeline objects bundle preprocessing steps and estimators, preventing data leakage during validation:
Chain imputation, standard scaling, and logistic regression into a single pipeline.
Test your understanding of ML pipeline architectures:
Linear Regression models a continuous target as a linear combination of input features :
where is the model parameter vector (including the intercept or bias ), and is the observation vector containing the features (with ).
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.
To train the model, we find parameters that minimize the Mean Squared Error (MSE) over the dataset:
To minimize the cost function, we solve analytically using the Normal Equation:
If the matrix is singular (non-invertible) due to redundant, highly correlated features, standard inversion fails. Solvers compute the pseudo-inverse using Singular Value Decomposition (SVD) for stability.
Computing requires inverting an matrix. The computational complexity is between and , making the Normal Equation expensive when the number of features is large.
The following example demonstrates computing model coefficients using the Normal Equation:
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.
Test your understanding of the analytical parameter estimation limits:
Logistic Regression is a classifier that computes a weighted sum of inputs and maps the output to a probability between and .
The model feeds its linear output into the Sigmoid Function :
The prediction rule for binary classes is:
The prediction decision boundary is linear where .
To optimize parameters , we minimize the convex Log Loss (binary cross-entropy):
It penalizes confident incorrect predictions with infinite cost (if and , then ).
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:
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.
The following example demonstrates calculating predictions using a trained Logistic Regression classifier:
Perform logistic regression inference. Calculate the predicted class and class probabilities for a sample point near the decision boundary.
Test your knowledge of the Logistic Regression model boundary behavior:
Regularization restricts model complexity to prevent overfitting. It penalizes large model weights during training, forcing parameters to stay small.
Three common regularized versions of linear regression modify the MSE cost function:
Ridge Regression adds a penalty equal to the sum of squared weights to the cost function:
The hyperparameter controls regularization strength. If , it behaves like Ordinary Least Squares. Note that the bias term is not regularized.
Lasso adds a penalty equal to the sum of absolute weights:
Lasso regression performs feature selection by forcing less important feature weights to exactly .
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.
Elastic Net combines Ridge and Lasso regularizations, controlled by a mix ratio :
It acts as a compromise, stabilizing selection when features are highly correlated.
The following example demonstrates how Lasso regularizes weights to zero compared to Ridge:
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.
Test your understanding of regularized cost functions:
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.
Naive Bayes is a probabilistic classifier based on Bayes’ Theorem. It assumes conditional independence between features given the class.
We predict the class probability for an input feature vector using:
Estimating directly requires massive datasets. The Naive Bayes classifier assumes that features are conditionally independent given the class:
Thus, the classification rule predicts the class that maximizes the numerator:
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.
Naive Bayes is a generative model because it models the joint distribution , unlike discriminative models (e.g., Logistic Regression) which model directly.
If a feature value never occurs with class in training, the probability is . Since we multiply feature probabilities, this zeroes out the entire class probability. We prevent this using Laplace Smoothing:
where is the number of possible values for , and is the smoothing parameter.
The following example demonstrates training a Gaussian Naive Bayes model on continuous features:
Fit a Gaussian Naive Bayes classifier on continuous physical features and predict class probability distributions.
Test your understanding of the independence assumption:
Priors reflect baseline class rates, acting as regularizers that bias predictions toward dominant classes.
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 training examples that are closest to it in the feature space and assigns a label based on the majority class among those neighbors.
The kNN algorithm for classification follows these steps:
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.
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 and , the Euclidean distance is defined as:
Manhattan distance (also known as 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.
Minkowski distance is a generalized metric that encompasses both Euclidean and Manhattan distances. It introduces a parameter :
When , it is equivalent to the Manhattan distance, and when , it reduces to the Euclidean distance.
The parameter 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.
In binary classification problems (where there are only two possible classes), it is critical to choose an odd value for . If an even is selected, there is a possibility of a tie in the majority voting process. An odd 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 , but they are significantly less frequent.
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.
By ensuring all features contribute equally to the distance calculation, scaling significantly improves the performance and reliability of the kNN algorithm.
Evaluate your understanding of kNN properties:
A Support Vector Machine (SVM) is a supervised algorithm that finds the decision boundary (hyperplane) that maximizes the margin between classes.
In linear classification, we find a hyperplane that separates classes.
To allow for noise and misclassifications, we introduce slack variables . The objective minimizes:
subject to:
The parameter controls the trade-off: a small allows more margin violations (regularized), while a large forces a hard margin (sensitive to noise).
By reformulating the optimization problem using Lagrange multipliers, we express the decision function using inner products of training instances:
The coefficients are non-zero only for instances on the margin boundaries. These are the Support Vectors that determine the decision boundary.
The kernel trick replaces the dot product with a kernel function , avoiding mapping data to high-dimensional spaces explicitly.
The parameter controls the RBF width: a larger makes the boundary narrower and more irregular, fitting specific instances.
The following example demonstrates training an SVM with an RBF kernel:
Train an RBF kernel SVM to solve the non-linear XOR problem. Inspect the support vectors selected by the model.
Test your understanding of SVM margin constraints:
Decision Trees are non-parametric models that recursively partition the feature space, predicting targets using simple hierarchical decision rules.
The CART algorithm builds binary trees by searching for a feature and threshold that minimize the weighted impurity of child nodes.
where represents the impurity of a node, and is the number of samples.
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.
For regression trees, CART minimizes Mean Squared Error (MSE), and leaves predict the average target value.
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.The following example demonstrates calculating Gini impurity and Information Gain:
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.
Test your understanding of Decision Tree scaling requirements:
Ensemble methods combine predictions from multiple base models to build a stronger predictor with improved generalization.
Ensemble models aggregate individual predictions using different consensus rules:
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:
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.
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.
The following example demonstrates building a Voting Classifier:
Train individual estimators (Logistic Regression, Decision Tree) and combine them into a soft Voting Classifier ensemble to observe performance updates.
Test your understanding of bootstrap aggregation:
Boosting methods train predictors sequentially, with each model attempting to correct its predecessor’s errors.
AdaBoost focuses on misclassified instances by adjusting their weights:
Unlike AdaBoost, Gradient Boosting trains models on the residual errors of the previous predictor.
For regression with squared error loss, the target for predictor is the residual:
The final prediction aggregates all estimators:
In classification, Gradient Boosting fits new trees to minimize the pseudo-residuals of the loss function, which are the negative gradients of the loss.
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 to , speeding up training on large datasets.
The following example demonstrates fitting successive decision trees to residual errors:
Fit sequential regression trees to residual errors to simulate a simple Gradient Boosting step-by-step pipeline.
Test your understanding of the boosting process:
In gradient boosting, learning rate is also known as shrinkage. A low learning rate (e.g., ) paired with more trees allows the model to converge smoothly, increasing generalization performance on tabular data.
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.
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 into three matrices:
The matrix contains the unit vectors that define the principal components:
To project the training set down to dimensions, we multiply the design matrix by the matrix containing the first principal components:
Alternatively, PCA can be computed by performing an eigendecomposition on the Sample Covariance Matrix of the centered data. The covariance matrix captures the variance and correlation of features:
By solving the characteristic equation, we decompose into its eigenvalues () and eigenvectors ():
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 as .
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 that preserve a target percentage of variance (e.g., 95%).
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.
The following example demonstrates projecting data using PCA and calculating the explained variance ratio:
Reduce a synthetic 3D dataset to 2D using Principal Component Analysis (PCA) and examine the explained variance ratios.
Evaluate your understanding of PCA projection logic:
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.
Clustering partitions unlabeled data into groups (clusters) of similar instances.
K-Means partitions data into clusters by minimizing the Within-Cluster Sum of Squares (Inertia):
K-Means++ initialization spreads centroids far apart during initialization, reducing the risk of converging to sub-optimal local minima.
DBSCAN groups points based on local density, classifying them into three categories:
MinPts neighbors within a radius of .DBSCAN detects the number of clusters automatically and handles outliers effectively by marking them as noise.
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.
The decision of which clusters to merge depends on the defined distance (linkage) between clusters:
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.
The following example demonstrates clustering using scikit-learn:
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.
Test your understanding of clustering paradigms:
Choosing the parameter in K-Means is challenging. We use two main validation methods:
Training models requires finding parameters that minimize a cost function by updating them iteratively.
SGD updates parameters using the gradient calculated from a single random instance (or a mini-batch) at each step:
While computationally efficient, SGD’s updates can oscillate, slowing convergence.
Momentum accelerates SGD by adding a fraction of the previous update vector , acting like a physical ball rolling down a hill:
NAG calculates the gradient ahead of the current position () to stabilize convergence.
Adaptive algorithms adjust the learning rate per parameter based on historical gradients:
Bias correction is applied: and .
AdamW improves on Adam by applying weight decay directly to the parameters rather than incorporating it into the gradient update step.
The following example demonstrates parameter optimization using Adam in PyTorch:
Minimize a quadratic function using the Adam optimizer in PyTorch. Observe how w converges toward zero over 5 gradient update steps.
Test your understanding of adaptive optimization updates:
Artificial Neural Networks (ANNs) are computational models inspired by biological neural networks, structured as layers of interconnected nodes.
The Perceptron is the simplest ANN architecture, computing a weighted sum of inputs plus a bias, and applying a step function:
A single Perceptron is a linear classifier, meaning it cannot solve non-linearly separable problems (like the XOR problem).
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.
For layer , the activations are computed using the weight matrix and bias vector :
where is the activation function.
Non-linear activation functions prevent stacked layers from collapsing into a single linear model:
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:
The error term is computed recursively from the output error using matrix multiplications.
The following example demonstrates calculating the forward pass of a single neuron using NumPy:
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.
Test your understanding of activation functions:
Convolutional Neural Networks (CNNs) are specialized neural architectures designed to process grid-structured data, such as images, by exploiting spatial hierarchies.
Unlike fully connected layers where neurons connect to all inputs, convolutional layers connect only to a local receptive field.
A layer applies learnable filters (kernels). As a filter slides, it computes dot products, producing a feature map.
Given input height , filter size , padding , and stride , the output height is:
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 reduce the spatial size of feature maps to decrease parameter counts and build translation invariance.
Deep CNNs suffer from vanishing gradients. ResNet resolves this using Residual Connections (skip connections) that bypass layers:
This allows gradients to flow directly backward, enabling the training of deep networks.
The following example calculates the output dimensions of a convolutional layer:
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.
Test your understanding of CNN operations:
Early layers detect simple edges, while deeper layers combine these features to recognize complex shapes and objects, building a hierarchical spatial representation.
Natural Language Processing (NLP) focuses on translating text sequences into mathematical representations that algorithms can learn from.
TF-IDF (Term Frequency-Inverse Document Frequency) measures how important a word is to a document in a corpus:
While effective for classification, TF-IDF ignores word order and semantic similarity.
To handle sequential context, Recurrent Neural Networks (RNNs) maintain a hidden state vector that updates at each step:
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.
The Transformer architecture replaces recurrent loops with Self-Attention. For queries , keys , and values , attention weights are computed in parallel:
where 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.
The following example demonstrates tokenizing and vectorizing text using TF-IDF:
Tokenize and vectorize a small text corpus using Term Frequency-Inverse Document Frequency (TF-IDF) in scikit-learn.
Validate your understanding of text vectorization properties:
MLOps standardizes the automation, deployment, and monitoring of production ML systems.
Unlike traditional software, ML models decay in production as real-world data distributions drift:
Production MLOps pipelines introduce Continuous Training (CT) alongside CI/CD:
The following example demonstrates a basic drift detection agent comparing production feature means with the training baseline:
Simulate feature drift detection by comparing incoming production means against training baselines.
Test your understanding of concept and data drift mechanisms:
Recommender systems suggest items to users based on historical interaction patterns and profile attributes.
Collaborative filtering recommends items based on the behavior of similar users.
We measure the similarity between user rating vectors and via:
Predictions are weighted averages of ratings from similar users.
Matrix Factorization decomposes the sparse user-item rating matrix of shape into two lower-rank matrices: of shape and of shape , representing user and item latent factor embeddings:
We find matrices and by minimizing the squared error over observed ratings, applying regularization to prevent overfitting:
where is the set of user-item pairs with observed ratings, is the global average rating, and are user and item bias parameters. Biases isolate systematic offsets (e.g., users who always rate critically, or items that are universally liked).
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).
The following example demonstrates calculating the cosine similarity between item latent embeddings:
Calculate the cosine similarity between item latent factor vectors (embeddings) to evaluate collaborative recommendation links.
Test your understanding of matrix factorization limits:
The L2 regularizer parameter prevents user/item embedding parameters from growing too large during updates, mitigating overfitting.
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.
An MDP provides a formal mathematical framework for modeling decision-making under uncertainty, defined by:
The objective is to find a policy that maximizes the expected discounted return , where is the discount factor.
The optimal action-value function satisfies the Bellman Optimality Equation:
When transition probabilities are unknown, the agent learns -values through experience using temporal difference updates:
where is the learning rate, and is the immediate reward.
In large state spaces, we replace the lookup table with a neural network parameterized by weights . We train the network by minimizing the loss against a target value:
where 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.
The following example demonstrates a single Q-learning update step:
Perform a Temporal Difference (TD) Q-learning update calculation for a single state transition, updating its action-value rating.
Test your understanding of the discount factor parameter:
Tabular Q-learning is limited to small discrete environments. Continuous, high-dimensional spaces require deep neural network function approximators (DQNs).
As machine learning systems are increasingly deployed to automate high-stakes decisions, it is critical to address algorithmic bias and ensure fairness.
Algorithmic bias arises at multiple pipeline stages:
Fairness is defined mathematically, but different metrics are often mutually exclusive. Let be a sensitive attribute (e.g., race, gender), be the remaining features, be the true label, and be the model prediction.
The likelihood of receiving a positive prediction is independent of the sensitive attribute:
The true positive rate (recall) is equal across all demographic groups:
The precision (positive predictive value) is equal across all demographic groups:
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.
The following example calculates demographic parity difference between two groups:
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.
Test your understanding of mathematical fairness constraints: