Machine Learning
A concise guide to machine learning.
このノートの改善点や、新しく欲しいノートを提案できます。
PDFを見る
Overview. This complete note surveys the foundations and practice of machine learning at the undergraduate level. It moves from the conceptual framing of learning problems (data, loss, generalization) through mathematical foundations, classical methods, deep learning, generative models, and reinforcement learning, concluding with practical deployment and ethics. Each section contains definitions, algorithms, key equations, and review guidance. The note is designed as a comprehensive review resource: study it holistically or jump to individual sections for targeted revision.
The Questions of ML: Data, Loss, Generalization, and Evaluation
Core ideas
Machine learning (ML) constructs algorithms that improve on task , with respect to performance metric , based on experience . In statistical ML, this is formalized as selecting a function from a hypothesis class to minimize expected error.
Problem Setup: [nosep]
- Data: Drawn from an unknown joint distribution over inputs and targets . A training set is sampled i.i.d.\ from .
- **Hypothesis Class (\mathcal{H**)}: The set of all possible models the learning algorithm can consider (e.g., all linear functions, or neural networks of a fixed architecture).
- Loss Function: measures the cost of a prediction.
Risk and Generalization: [nosep]
- Expected Risk: The true objective, . Since is unknown, we cannot directly minimize .
- Empirical Risk Minimization (ERM): We approximate using the training data: . ERM selects .
- Generalization Gap: The difference . A large gap indicates overfitting (low empirical risk but high expected risk, often due to high capacity in ). Conversely, underfitting occurs if is too restrictive, leading to high training and test errors.
Learning paradigms: [nosep]
- Supervised: Learn given fully labeled pairs.
- Unsupervised: Discover structure (clusters, manifolds, density) from unlabeled data .
- Self-supervised: Formulate supervised tasks from unlabeled data (e.g., predicting masked words or geometric transformations).
- Reinforcement learning (RL): Learn a policy to maximize cumulative rewards in sequential environments.
Evaluation Metrics: Held-out test sets estimate . Common empirical metrics include: Accuracy, Precision/Recall, and F1 for classification; Mean Squared Error (MSE) and Mean Absolute Error (MAE) for regression; and Area Under the ROC Curve (AUC-ROC) for binary confidence scores.
For review, be able to: define task, performance, and experience; contrast expected and empirical risk; explain the ERM principle and the role of the hypothesis class ; and classify tasks into paradigms.
Section summary. ML formalizes learning as optimization: we seek a hypothesis that minimizes empirical risk on training data while generalizing to the true distribution. Controlling the complexity of to balance underfitting and overfitting is the central challenge.
Mathematical Foundations: Linear Algebra, Calculus, Probability, and Optimization
Core ideas
Linear algebra provides the language for representing data and models. [nosep]
- A vector is an ordered -tuple; the inner product measures similarity.
- A matrix represents data points each with features.
- The transpose ; the identity ; the inverse satisfies .
- Eigendecomposition: for square . Symmetric positive-definite matrices have orthogonal eigenvectors and positive eigenvalues.
- Singular value decomposition (SVD): for any , where are orthogonal and is diagonal with singular values .
- Norms: norm ; norm ; Frobenius norm .
Calculus enables optimization. [nosep]
- The gradient is the vector of partial derivatives; it points in the direction of steepest ascent.
- The chain rule: if , then .
- Hessian encodes curvature; positive-definite Hessian local minimum.
- Taylor expansion: .
Probability quantifies uncertainty. [nosep]
- Random variable with distribution ; expectation (discrete) or (continuous).
- Conditional probability ; Bayes’ rule: .
- Variance ; covariance .
- Common distributions: Bernoulli, Binomial, Gaussian , Multinomial, Exponential.
- Law of large numbers: sample mean converges to expectation. Central limit theorem: sum of i.i.d.\ variables is approximately Gaussian.
Optimization finds parameters minimizing a loss. [nosep]
- Convex functions: . Convex problems have no local minima other than the global minimum.
- Gradient descent: where is the learning rate.
- Stochastic gradient descent (SGD): uses a minibatch estimate of the gradient for efficiency.
- First-order methods (SGD, momentum, Adam) scale to high dimensions; second-order methods (Newton) use curvature but are costly.
For review, be able to: compute gradients via the chain rule; apply Bayes’ rule; derive the normal equations; explain SVD; implement gradient descent; and recognize convex functions.
Section summary. ML rests on linear algebra (representing data and models), calculus (optimizing via gradients), probability (modeling noise and uncertainty), and optimization (finding parameters). The normal equations solve linear regression analytically; for most models we use iterative gradient-based methods.
Linear Models: Regression, Classification, and Regularization
Core ideas
Linear regression models the target as a continuous function . Under squared error loss, the empirical risk is:
By appending to each to absorb , the closed-form normal equations yield . This requires to be invertible (full column rank).
Logistic regression is for binary classification, modeling the probability of the positive class using the logistic sigmoid function :
Log-odds interpretation: It models the log-odds as a linear function: . Optimized via gradient descent or Newton’s method using the binary cross-entropy (log-loss):
Softmax regression (multinomial logistic regression) generalizes to classes:
Loss is the categorical cross-entropy: .
Generalized Linear Models (GLMs) unify these approaches by assuming the target follows a distribution from the Exponential Family (e.g., Gaussian for linear regression, Bernoulli for logistic, Poisson for counts) and modeling the natural parameter as a linear combination of features .
Regularization prevents overfitting by penalizing large weights: [nosep]
- (Ridge): Penalty . Closed-form: . Shrinks all weights.
- (Lasso): Penalty . Induces sparsity (some weights become exactly zero), acting as feature selection.
- Elastic Net: Combines and penalties .
Assumptions: Ordinary least squares assumes is linear, errors are i.i.d.\ homoscedastic (constant variance) and normally distributed, and no perfect multicollinearity.
For review, be able to: derive the normal equations; explain the log-odds interpretation of logistic regression; formulate linear and logistic regression as GLMs; compare vs regularization geometrically; and diagnose multicollinearity.
Section summary. Linear models are the simplest parametric models: regression via least squares, classification via logistic/softmax with cross-entropy. They can be unified under GLMs. Regularization controls overfitting by penalizing weight magnitudes. These models are strictly convex and serve as fundamental baselines.
Evaluation: Cross-Validation, Overfitting, and Bias-Variance Tradeoff
Core ideas
Overfitting occurs when a model learns noise in the training data, achieving low training error but high test error. It happens with: [nosep]
- Too many parameters relative to sample size ().
- Training too long (over-optimization).
- No regularization or too much capacity.
Underfitting occurs when the model is too simple to capture the underlying pattern.
Bias—variance decomposition (for squared error):
Bias measures how much the model’s average prediction deviates from the truth. Variance measures how much predictions fluctuate across different training sets. Simple models have high bias, low variance; complex models have low bias, high variance. The tradeoff guides model selection.
Cross-validation estimates generalization without wasting data: [nosep]
- -fold CV: split data into folds, train on , test on the held-out fold, repeat times, average metrics. Typical or .
- Leave-one-out CV (LOOCV): , expensive but nearly unbiased.
- Stratified CV: preserves class proportions in each fold.
- Train/validation/test split: hold out a test set at the very end, use validation set(s) for model selection.
Hyperparameter tuning: model capacity (degree of polynomial, in -NN, in ridge), learning rate, network architecture. Use validation performance (not test performance) for selection.
Learning curves: plot training and validation error vs.\ dataset size or training epochs. Gaps indicate overfitting; convergence to high error indicates underfitting.
Diagnostics: [nosep]
- Training error validation error overfitting (increase regularization, get more data, reduce capacity).
- Both errors high underfitting (increase capacity, reduce regularization, add features).
For review, be able to: derive the bias—variance decomposition; explain why cross-validation is needed; choose in -fold CV; interpret learning curves; and design a model selection pipeline.
Section summary. Generalization is the central concern of ML. The bias—variance tradeoff explains why we need regularized, capacity-controlled models. Cross-validation provides a reliable estimate of test performance for model selection. Always keep a separate test set for final evaluation.
Classical ML: Trees, SVMs, PCA, Clustering, and Ensembles
Core ideas
Decision trees recursively partition the feature space into hyper-rectangles: [nosep]
- Splitting criterion: At each node, select a feature and threshold to maximize information gain (decrease in impurity): .
- Impurity measures (): Entropy or Gini impurity for classification; Mean Squared Error (MSE) for regression.
- Regularization: Trees easily overfit. Mitigated by setting max depth, minimum samples per leaf, or cost-complexity pruning.
Support vector machines (SVMs) find the maximum-margin separating hyperplane. [nosep]
- Primal formulation: subject to , where are slack variables for non-separable data (soft-margin). controls the margin vs.\ misclassification penalty.
- Dual formulation: , with . The solution depends only on support vectors (points where ).
- Kernel trick: By the Representer Theorem, the optimal weights lie in the span of the data: . We can replace inner products with a kernel function . Common kernels: Polynomial , RBF .
PCA (principal component analysis) finds an orthogonal projection of data onto a lower dimensional linear space that maximizes variance. [nosep]
- Center the data: .
- Compute SVD: ; columns of are the principal components (eigenvectors of the covariance matrix ).
- Projection: maps into .
- Often used as an unsupervised preprocessing step to reduce dimensionality and mitigate the curse of dimensionality.
Clustering partitions data into distinct groups: [nosep]
- -means: Minimizes within-cluster variance . Alternates between assigning points to the nearest centroid and recomputing centroids (Lloyd’s algorithm). Highly sensitive to initialization; use -means++.
- DBSCAN: Density-based, groups points closely packed together, robust to noise/outliers, automatically determines .
Ensemble methods combine multiple base models to improve generalization: [nosep]
- Bagging (Bootstrap Aggregating): Train independent high-variance models (e.g., deep decision trees) on bootstrap samples and average them. It significantly reduces variance without increasing bias. Random Forest improves this by also using random feature subsets at each split to de-correlate trees.
- Boosting: Sequentially train high-bias models (e.g., shallow trees/stumps), where each new model corrects the errors of the ensemble so far. It primarily reduces bias. Gradient Boosting Machines (XGBoost, LightGBM) fit new trees to the negative gradient of the loss function.
For review, be able to: compute information gain for a split; derive the SVM dual; explain the kernel trick and Representer Theorem; perform PCA via SVD; run -means; and analytically compare how bagging and boosting affect bias and variance.
Section summary. Classical ML offers a mathematically grounded toolkit: decision trees (interpretable non-linear splits), SVMs (maximum-margin with kernels for infinite-dimensional feature spaces), PCA (unsupervised dimensionality reduction), and clustering. Ensembles (Random Forests, Gradient Boosting) dominate tabular data by systematically trading off bias and variance.
Statistical Learning: Estimation, Bayes, Causality, and Uncertainty
Core ideas
Statistical estimation: we observe data i.i.d.\ from . We estimate parameters of a model .
Maximum likelihood estimation (MLE):
MLE is consistent (converges to true as ) and asymptotically efficient (achieves Cram’{e}r—Rao lower bound).
Maximum a posteriori (MAP) adds a prior :
regularization on weights corresponds to a Gaussian prior; corresponds to a Laplace prior.
Bayesian inference computes the full posterior:
Prediction: (posterior predictive). For most models the integral is intractable; approximation via MCMC (sampling) or variational inference (optimization).
Causality goes beyond correlation. Key concepts: [nosep]
- Structural causal models (SCMs): where are parents of and are exogenous noise.
- Interventions vs.\ conditioning . The do-operator removes incoming edges to .
- Confounders: affects both and ; conditioning on blocks the backdoor path.
- Randomized controlled trials (RCT) are the gold standard for causal inference.
- Methods: propensity score matching, instrumental variables, difference-in-differences.
Uncertainty quantification: [nosep]
- Aleatoric uncertainty: irreducible noise in data (e.g., measurement error). Cannot be reduced with more data.
- Epistemic uncertainty: uncertainty about model parameters due to limited data. Decreases with more data.
- Calibration: a model is calibrated if among predictions with confidence , the true fraction correct is .
For review, be able to: derive MLE for Gaussian and Bernoulli; explain MAP as regularized MLE; describe Bayesian vs.\ frequentist approaches; define confounding; distinguish aleatoric and epistemic uncertainty.
Section summary. Statistical learning provides the probabilistic foundation: MLE for point estimates, Bayesian inference for full uncertainty, and causal reasoning for interventional questions. Understanding estimation properties (bias, consistency, efficiency) is essential for diagnosing models.
Probabilistic ML: Generative Models, Latent Variables, and Graphical Models
Core ideas
Generative vs.\ discriminative models: [nosep]
- Discriminative: , e.g., logistic regression, neural networks.
- Generative: , e.g., naive Bayes, GMMs.
- Generative models can produce new samples and handle missing data naturally.
- Naive Bayes assumes conditional independence: . Despite the strong assumption, it works well for text classification.
Gaussian mixture models (GMMs):
Latent variable indicates which component generated . The log-likelihood is non-convex; use expectation—maximization (EM): [nosep]
- E-step: compute responsibilities .
- M-step: update , , .
EM monotonically increases the marginal log-likelihood.
Probabilistic graphical models represent conditional independence: [nosep]
- Bayesian networks (DAG): . Factorization according to graph structure.
- Markov random fields (undirected): where is the partition function.
- Hidden Markov models (HMMs): latent states evolve as a Markov chain , observations depend on . Forward-backward algorithm computes ; Viterbi finds the most likely sequence.
Latent variable models (LVMs) assume the observed data is generated from unobserved latent variables: [nosep]
- Factor analysis, probabilistic PCA (, ).
- Topic models (LDA): documents are mixtures of topics, topics are distributions over words.
Variational inference: approximate intractable posterior with a simpler by minimizing KL divergence:
Maximizing the evidence lower bound (ELBO) is equivalent to minimizing KL.
For review, be able to: derive EM for GMMs; explain the difference between generative and discriminative models; factorize a joint distribution from a DAG; derive the ELBO; and implement the forward-backward algorithm.
Section summary. Probabilistic ML models the full data distribution. GMMs cluster with soft assignments via EM. Graphical models encode structure and enable efficient inference. Variational inference approximates intractable posteriors, forming the foundation for modern deep generative models.
Fundamentals of Deep Learning: MLPs, Backpropagation, and Optimization
Core ideas
Multilayer perceptrons (MLPs) (feedforward neural networks) stack affine transformations with elementwise nonlinearities to learn hierarchical representations. A network of depth computes:
Hidden units act as learned feature extractors, circumventing the need for manual feature engineering.
Activation functions inject essential nonlinearity (without them, the network collapses to a single affine transform): [nosep]
- ReLU (Rectified Linear Unit): . Piecewise linear, cheap to compute, mitigates vanishing gradients. Default choice for hidden layers.
- Sigmoid: . Maps to . Prone to vanishing gradients in saturated regions; mostly used for binary classification outputs.
- Tanh: . Maps to . Zero-centered, generally preferred over sigmoid for hidden units.
- Leaky ReLU / GELU: Address the “dying ReLU” problem and provide smooth gradients, common in modern architectures like Transformers.
Backpropagation efficiently computes gradients of the loss with respect to all parameters using the chain rule. It is a specific application of reverse-mode automatic differentiation: [nosep]
- Forward pass: Compute and cache hidden activations for , and the loss .
- Backward pass: Propagate the error signal backwards. Compute the gradient w.r.t.\ activations: .
- Parameter gradients: .
Optimization algorithms train these highly non-convex objectives: [nosep]
- SGD (Stochastic Gradient Descent): , using a minibatch to estimate the true gradient.
- Momentum: Accumulates an exponentially decaying moving average of past gradients to dampen oscillations and accelerate convergence across flat regions.
- Adam: Adaptive learning rates per parameter, using running averages of the first moment (mean) and second moment (uncentered variance) of the gradients:
where $\hat{m}_t$ and $\hat{v}_t$ are bias-corrected estimates.
Numerical considerations & Regularization: [nosep]
- Vanishing/exploding gradients: Deep networks repeatedly multiply weight matrices, causing gradients to vanish or explode. Handled by careful initialization (Xavier/Glorot, He) and skip connections.
- Batch Normalization: Standardizes activations within a minibatch to zero mean and unit variance, smoothing the optimization landscape and allowing higher learning rates.
- Dropout: Randomly zeroes out neurons during training with probability . Acts as a regularizer by preventing feature co-adaptation, implicitly training an ensemble.
Universal Approximation Theorem: A feedforward network with at least one hidden layer of sufficient width and a non-polynomial activation function can approximate any continuous function on a compact subset of to arbitrary precision. However, it does not guarantee that the learning algorithm can find those weights, nor that the network will generalize well.
For review, be able to: derive backpropagation for a 2-layer MLP; explain why nonlinearities are necessary; implement SGD with momentum; diagnose vanishing gradients; and describe batch normalization.
Section summary. Deep learning stacks differentiable nonlinear layers to learn representations. Backpropagation leverages the chain rule for exact gradient computation. Due to non-convexity and high dimensionality, specialized optimizers (Adam, SGD+Momentum), careful initialization, and techniques like Batch Normalization and Dropout are vital for successful training.
Modern Deep Learning: CNNs, RNNs, Attention, and Transformers
Core ideas
Convolutional Neural Networks (CNNs) exploit the inherent spatial structure of data (e.g., images) through localized filter operations. [nosep]
- Definition (2D Convolution): Given an image and a filter (kernel) , the discrete convolution is defined as . This operation shares weights across all spatial locations, a property known as weight tying.
- Key Properties: [nosep]
- Translation Equivariance: Shifting the input shifts the output by the same amount, i.e., where is a translation operator.
- Local Connectivity: Each neuron only connects to a small local region of the input, defining its receptive field.
- Pooling: Operations like max or average pooling aggregate local features, providing spatial downsampling and local translation invariance (robustness to small shifts).
- Canonical Architectures: [nosep]
- AlexNet: Pioneered deep CNNs using ReLU activations, dropout, and extensive data augmentation.
- VGG: Standardized architecture using deep stacks of small convolutions.
- ResNet: Introduced residual (skip) connections to mitigate vanishing gradients in extremely deep networks.
Recurrent Neural Networks (RNNs) are designed to model sequential data by maintaining a hidden state across time steps:
[nosep]
- Backpropagation Through Time (BPTT): Unrolls the RNN computation graph over time to compute gradients. A canonical failure mode of standard RNNs is the vanishing/exploding gradient problem over long sequences due to repeated multiplication of the weight matrix .
Gated RNNs address long-range dependencies by regulating information flow: [nosep]
- Long Short-Term Memory (LSTM): Introduces a cell state regulated by forget (), input (), and output () gates:
- Gated Recurrent Unit (GRU): A simplified gated architecture merging the forget and input gates into a single update gate.
Attention Mechanisms overcome the bottleneck of compressing entire sequences into a fixed-length vector by allowing models to dynamically weigh the importance of all input elements. [nosep]
- Definition (Scaled Dot-Product Attention): For queries , keys , and values , attention is computed as:
Scaling by $1/\sqrt{d_k}$ prevents the dot products from growing excessively large, which would push the softmax function into regions with near-zero gradients.
Transformers (Vaswani et al., 2017) rely entirely on attention, dispensing with recurrence and convolutions. [nosep]
- Multi-Head Attention: Projects , , and into different representation subspaces (heads) in parallel. The independent attention outputs are then concatenated and linearly transformed.
- Positional Encoding: Since attention is permutation-invariant, positional encodings (e.g., fixed sinusoidal functions or learned embeddings) are added to input embeddings to inject sequence order information.
- Architecture Components: Comprises layer normalization, residual connections, and position-wise feedforward networks. The encoder uses full self-attention, whereas the decoder uses masked self-attention to prevent attending to future tokens (preserving the autoregressive property).
- Complexity: Standard attention has time and space complexity with respect to sequence length .
Large-Scale Pretraining leverages massive unannotated datasets to learn general representations: [nosep]
- BERT: Uses a bidirectional encoder pretrained via Masked Language Modeling (MLM).
- GPT: Employs a causal, autoregressive decoder architecture.
- Scaling Laws: Empirical observations that model performance scales power-law predictably with parameter count, dataset size, and training compute.
For review, be able to: explain the receptive field of a CNN; derive gradient flow in an RNN via BPTT; implement scaled dot-product attention; draw the standard Transformer encoder/decoder blocks; and describe masked language modeling.
Section summary. Modern deep learning is built upon specialized architectures for data modalities: CNNs utilize local connectivity and weight tying for spatial data; RNNs and LSTMs maintain hidden states for sequential data; and Transformers leverage self-attention for parallelizable, long-range sequence modeling. The paradigm has shifted strongly toward large-scale, self-supervised pretraining followed by task-specific fine-tuning.
Generative AI: VAEs, GANs, Diffusion, and Self-Supervised Learning
Core ideas
Variational Autoencoders (VAEs) combine deep learning with variational inference to learn continuous, structured latent spaces: [nosep]
- Definition: An architecture consisting of a probabilistic encoder mapping data to a latent distribution (typically Gaussian ), and a decoder reconstructing the data.
- ELBO Objective: Because exact marginal likelihood is intractable, VAEs maximize the Evidence Lower Bound (ELBO):
The first term minimizes reconstruction error, while the second acts as a regularizer, pulling the approximate posterior toward the prior $p(\mathbf{z}) = \mathcal{N}(0,\mathbf{I})$.
- Reparameterization Trick: To allow gradients to backpropagate through the stochastic sampling step, is reparameterized: sample , then compute .
Generative Adversarial Networks (GANs) frame generation as a two-player, zero-sum game: [nosep]
- Definition: A generator network maps noise to fake data , while a discriminator predicts whether a sample is real () or fake ().
- Minimax Objective:
- Training Pathologies: GANs are notoriously difficult to train, frequently suffering from mode collapse (the generator produces only a limited variety of outputs, ignoring parts of the data distribution) and vanishing gradients.
- Improvements: Wasserstein GAN (WGAN) addresses instability by minimizing the Earth Mover’s distance using a 1-Lipschitz discriminator constrained via gradient penalty. StyleGAN introduces mapping networks and adaptive instance normalization for high-fidelity synthesis.
Diffusion Models (and Score-Based Generative Models) generate data by learning to reverse a gradual noising process: [nosep]
- Forward Process (Diffusion): A Markov chain gradually corrupts data by adding Gaussian noise over steps: .
- Reverse Process (Denoising): A neural network learns the reverse transitions to synthesize data from pure noise .
- Training Objective: DDPM minimizes a reweighted variational bound, effectively training a U-Net to predict the injected noise :
- Score Matching Connection: The noise prediction objective is mathematically equivalent to score matching, learning the gradient of the log data density: . Latent Diffusion Models (e.g., Stable Diffusion) perform this process efficiently inside a frozen VAE latent space.
Self-Supervised Learning (SSL) extracts powerful representations from unannotated data by inventing pretext tasks: [nosep]
- Contrastive Learning: Pulls representations of positive pairs (e.g., augmented views of the same image) closer while pushing negative pairs apart. SimCLR uses the InfoNCE loss:
where $\tau$ is a temperature hyperparameter controlling the penalty strength on hard negatives.
- Non-contrastive Methods: Architectures like BYOL and SimSiam use momentum encoders and stop-gradient operations to prevent representation collapse without requiring negative pairs.
- Masked Autoencoders: Models like BERT (text) and MAE (vision) mask patches of input data and train a network to reconstruct the missing content, enforcing deep contextual understanding.
For review, be able to: mathematically derive the VAE ELBO from Jensen’s inequality; explain the necessity of the reparameterization trick; describe the GAN minimax game and optimal discriminator; outline the diffusion forward/reverse Markov chain; and define the InfoNCE contrastive loss.
Section summary. Generative AI models data distributions. VAEs provide stable training and smooth latent spaces via variational inference. GANs employ an adversarial minimax game to achieve high-fidelity generation. Diffusion models use iterative denoising equivalent to score matching, currently yielding state-of-the-art visual quality. Self-supervised learning (contrastive or masked) converts raw data into informative latent structures, serving as the backbone for modern foundation models.
Reinforcement Learning: MDPs, TD Learning, Q-Learning, and Policy Gradients
Core ideas
Markov Decision Process (MDP) formalizes sequential decision-making under uncertainty: [nosep]
- Definition: A tuple where is the state space, is the action space, is the transition probability, is the reward function, and is the discount factor.
- Markov Property: The future depends only on the present state, not on the sequence of events that preceded it: .
- Return: The cumulative discounted reward from time : .
- **Policy \pi(a|\mathbf{s**):} A mapping from states to a probability distribution over actions.
- Value Functions: [nosep]
- State-value: .
- Action-value: .
- Bellman Equations: Recursive relationships linking the value of a state to the values of its successors:
- Bellman Optimality: The optimal policy satisfies .
Dynamic Programming solves known MDPs exactly: [nosep]
- Policy Iteration: Alternate between evaluating and greedily improving .
- Value Iteration: Iteratively apply the Bellman optimality operator until convergence.
Model-Free RL learns optimal policies from environmental interaction without known or .
Temporal Difference (TD) Learning blends Monte Carlo methods and dynamic programming: [nosep]
- Mechanism: Bootstraps updates using current value estimates instead of waiting for episode completion.
- TD(0) Update: , where is the TD Error.
Q-Learning and SARSA are canonical TD control algorithms: [nosep]
- SARSA (On-Policy): Updates using the action actually taken by the behavior policy:
- Q-Learning (Off-Policy): Updates using the maximum possible value of the next state, uncoupling learning from the behavior policy:
- Deep Q-Network (DQN): Stabilizes Q-learning with neural networks via experience replay (breaking temporal correlations) and target networks (providing fixed bootstrap targets).
Policy Gradient Methods directly parameterize and optimize the policy : [nosep]
- Policy Gradient Theorem: Provides an analytic gradient for the expected return:
- REINFORCE: Uses sample returns as an unbiased (but high-variance) estimator of .
- Actor-Critic: Combines policy gradients (the actor) with a learned value function (the critic) serving as a baseline to reduce variance. Subtracting the state-value yields the advantage function .
- PPO (Proximal Policy Optimization): Clips the policy ratio to prevent destructively large policy updates.
Exploration vs. Exploitation Tradeoff: Algorithms must balance exploiting known rewards with exploring undiscovered states using strategies like -greedy, Boltzmann exploration, or Upper Confidence Bound (UCB).
For review, be able to: define the Markov Property; mathematically state the Bellman Optimality Equation; prove why Q-learning is off-policy while SARSA is on-policy; derive the REINFORCE update rule; and explain how Actor-Critic reduces variance.
Section summary. Reinforcement learning solves sequential decision-making governed by MDPs. Value-based methods (Q-Learning) learn optimal action-values off-policy. Policy gradient methods directly optimize a parameterized policy, overcoming limitations in continuous action spaces. Deep RL merges these frameworks with neural network function approximators (e.g., DQN, PPO), relying heavily on mechanisms like advantage estimation to stabilize learning.
Practice and Ethics: MLOps, Fairness, Explainability, and Safety
Core ideas
Machine Learning Operations (MLOps) standardizes the transition from experimental models to reliable, production-grade systems: [nosep]
- Data Pipeline & Versioning: Tracks dataset lineage (e.g., DVC), standardizes feature engineering via feature stores, and automates data quality monitoring.
- Experiment Tracking & CI/CD: Systematically logs hyperparameters, metrics, and artifacts (e.g., MLflow). Implements continuous integration for data validation and continuous deployment for model updates.
- Monitoring in Production: Detects degradation over time, primarily distinguishing between data drift (covariate shift: changes while remains constant) and concept drift (the underlying relationship changes, requiring retraining).
Fairness in ML systematically measures and mitigates discriminatory algorithmic behaviors: [nosep]
- Sources of Bias: Encompasses historical bias, representation bias (under-sampling minority groups), and measurement bias (using flawed proxies for target variables).
- Group Fairness Notions: For a sensitive attribute , target , and prediction : [nosep]
- Demographic Parity: The model’s positive prediction rate is independent of the sensitive attribute: .
- Equalized Odds: Both the True Positive Rate (TPR) and False Positive Rate (FPR) are identical across groups: for .
- Equal Opportunity: Requires equality only for the TPR ().
- Impossibility Theorem (Chouldechova et al.): It is mathematically impossible to simultaneously satisfy demographic parity and equalized odds unless the base rates of the groups are exactly equal or the predictor is perfectly accurate.
- Mitigation: Involves pre-processing (reweighing data), in-processing (adversarial debiasing, constrained optimization), or post-processing (group-specific thresholding).
Explainability and Interpretability open the “black box” of complex models: [nosep]
- Intrinsic Interpretability: Using transparent model classes natively (e.g., shallow decision trees, sparse linear models).
- Post-Hoc Feature Attribution: [nosep]
- SHAP (SHapley Additive exPlanations): Grounded in cooperative game theory, it uniquely satisfies desirable axioms (local accuracy, missingness, consistency) to assign a marginal contribution to each feature.
- LIME (Local Interpretable Model-agnostic Explanations): Fits a simple, interpretable surrogate model (e.g., linear regression) in the local neighborhood of a specific prediction.
- Saliency & Counterfactuals: Saliency maps visualize gradients w.r.t.\ input pixels (in vision). Counterfactual explanations highlight the minimal perturbation required to alter the model’s decision.
AI Safety, Robustness, and Privacy ensure models perform reliably under stress and adversarial conditions: [nosep]
- Adversarial Examples: Microscopic, carefully crafted perturbations that drastically flip model predictions. [nosep]
- Fast Gradient Sign Method (FGSM): A single-step attack: .
- Projected Gradient Descent (PGD): An iterative, multi-step application of FGSM representing a strong first-order attack.
- AI Alignment: The challenge of ensuring systems pursue intended human goals without exhibiting reward hacking (gaming the objective) or negative side-effects.
- Differential Privacy (DP): Provides a mathematical guarantee that the inclusion or removal of a single data point does not significantly alter the output distribution of a randomized algorithm . [nosep]
- Formal Definition (-DP): for all neighboring datasets differing by one record, bounding the privacy loss by .
- Federated Learning: Enables decentralized model training without aggregating raw data centrally, often combined with secure multi-party computation.
For review, be able to: describe the MLOps lifecycle; rigorously define demographic parity and equalized odds; compute SHAP values for a minimal cooperative game; derive adversarial examples via FGSM; and explain the formal bounds of differential privacy.
Section summary. The deployment of machine learning is constrained by practical and ethical requirements. MLOps ensures rigorous, automated pipelines for continuous monitoring and deployment. Mathematical fairness guarantees audit and mitigate algorithmic bias. Explainability methods like SHAP and LIME provide interpretability for black-box models. AI Safety enforces robustness against adversarial attacks and distribution shifts, while Differential Privacy and Federated Learning protect sensitive data.