Machine Learning: a Lecture Note
Abstract: This lecture note is intended to prepare early-year master's and PhD students in data science or a related discipline with foundational ideas in machine learning. It starts with basic ideas in modern machine learning with classification as a main target task. These basic ideas include loss formulation, backpropagation, stochastic gradient descent, generalization, model selection as well as fundamental blocks of artificial neural networks. Based on these basic ideas, the lecture note explores in depth the probablistic approach to unsupervised learning, covering directed latent variable models, product of experts, generative adversarial networks and autoregressive models. Finally, the note ends by covering a diverse set of further topics, such as reinforcement learning, ensemble methods and meta-learning. After reading this lecture note, a student should be ready to embark on studying and researching more advanced topics in machine learning and more broadly artificial intelligence.
Summary
- The paper presents an energy function framework that unifies inference, learning, and various machine learning paradigms.
- The note details how gradient-based techniques like backpropagation and SGD optimize parameters in models including classifiers and neural networks.
- It explores probabilistic modeling and advanced topics such as VAEs, RBMs, and adaptive optimizers for scalable, efficient ML implementations.
This lecture note presents machine learning concepts through the lens of an energy function. An energy function e(x,z,θ) assigns a real value to a pair of observed instance x and latent instance z, parametrized by θ. Low energy indicates high compatibility or preference. This unifying perspective allows deriving various machine learning paradigms by minimizing this energy function with respect to different variables.
Inference: Given a partial observation, inference means minimizing the energy function with respect to the unobserved part. For instance, in supervised learning with observed pairs (x,y) and no latent variable z, predicting the output y^ for a new input x′ involves minimizing e([x′,y],∅,θ) over possible y. In clustering, with observed x and latent cluster assignment z, inference is finding z^=argminze(x,z,θ).
Learning: Estimating the parameter θ typically involves minimizing the expected energy on observed data, often with regularization to ensure high energy for undesirable inputs. When latent variables exist, learning requires simultaneously solving the inference problem. The lecture emphasizes that all algorithms are presented to work with scalable implementations, particularly stochastic gradient descent (SGD) and its variants.
The core machine learning problem is thus decomposed into three aspects:
- Defining the energy function e (parametrization).
- Estimating θ from data (learning).
- Inferring missing parts given partial observations (inference).
Classification
Classification is presented as a supervised learning problem where the output y is a discrete category. With no latent variable, inference is y^(x)=argy′∈Ymine([x,y′],∅,θ). A common parametrization uses a feature extractor f(x,θ) that outputs a vector of scores for each category, e([x,y],∅,θ)=1(y)⊤f(x,θ). A simple example is linear classification: f(x,θ)=Wx+b, where θ=(W,b).
Learning θ is framed as minimizing an average loss function over a training dataset.
- Zero-One Loss: $L_{0-1}([x, y], \theta) = \mathds{1}(y \neq \hat{y}(x))$. This loss is non-differentiable and piecewise constant, making gradient-based optimization difficult.
- Margin Loss (Hinge Loss): Lmargin([x,y],θ)=max(0,m+e([x,y],∅,θ)−e([x,y^′],∅,θ)), where y^′ is the second-best incorrect output. This loss encourages a margin m>0 between the true output's energy and the best incorrect output's energy. Perceptron loss is a special case with m=0. The gradient is non-zero only when the margin is violated.
- Softmax and Cross-Entropy Loss: This approach converts energy scores ay=e([x,y],∅,θ) into a probability distribution pθ(y∣x) using the softmax function: pθ(y∣x)=∑y′∈Yexp(−e([x,y′],∅,θ))exp(−e([x,y],∅,θ)). This derivation is shown to arise from maximizing entropy subject to normalization constraints. The learning objective is the negative log-likelihood or cross-entropy loss: Lce([x,y],θ)=−logpθ(y∣x). The gradient of the cross-entropy loss is ∇θe([x,y],∅,θ)−Ey′∣x;θ[∇θe([x,y′],∅,θ)]. This "Boltzmann machine learning" rule involves a "positive phase" (decreasing energy of the correct output) and a "negative phase" (increasing expected energy over all outputs, weighted by the model's probability). The cross-entropy loss is widely used in practice due to its differentiability and probabilistic interpretation.
Backpropagation
Backpropagation is presented as the method for computing gradients of the loss function with respect to model parameters, particularly for composite, differentiable energy functions (like neural networks). It's a form of reverse-mode automatic differentiation.
For a linear energy function e([x,y],θ)=−wy⊤x−by, the gradients are simple: ∇wye=−x and ∇bye=−1. Applying this to the perceptron loss shows updates that lower the energy of the correct output and raise the energy of the predicted incorrect output.
The core idea of backpropagation is shown by considering the gradient of the loss with respect to an intermediate transformation of the input, h=F(x,θ′). If the loss gradient w.r.t. h is ∇hL, then the gradient w.r.t. θ′ can be computed using the chain rule. This "back-propagation" of the gradient signal ∇hL through the transformation F (e.g., F(x)=σ(U⊤x+c)) allows computing gradients w.r.t. parameters U and c. For h=σ(U⊤x+c), ∇UL=x(∇hL⊙h′)⊤ and ∇cL=∇hL⊙h′, where h′=σ′(U⊤x+c). The term h′ accounts for the non-linearity's derivative. By stacking such differentiable transformations, the gradient can be propagated backward through the entire network. The feasibility of computing these gradients efficiently makes backpropagation the standard for training neural networks. Libraries like PyTorch and Jax automate this process.
Stochastic Gradient Descent
Minimizing the average loss f(θ)=N1∑i=1Nfi(θ) for large N and large ∣θ∣ is computationally expensive. SGD addresses this by using a stochastic gradient estimate git=∇fit(θt) based on a single example it (or a small minibatch) at each step: θt+1=θt−αtgit.
The Descent Lemma states f(y)≤f(x)+∇f(x)⊤(y−x)+2L∥y−x∥2 for L-Lipschitz gradients. For full gradient descent with step αt, this implies f(θt+1)≤f(θt)−(αt−2Lαt2)∥∇f(θt)∥2, suggesting an optimal step of $1/L$. For SGD, the expected value of the next loss step is E[f(θt+1)]≤f(θt)−αt∥∇f(θt)∥2+αt22LE∥git∥2. The variance of the stochastic gradient introduces a positive term. To ensure expected progress or convergence near a minimum, the learning rate αt typically needs to decrease over time.
Adaptive Learning Rate Methods: Instead of a fixed scalar learning rate, adaptive methods adjust the learning rate for each parameter dynamically based on past gradients.
- Adagrad (Tanaka et al., 2011) scales the learning rate for each parameter inversely to the square root of the sum of its past squared gradients. This helps parameters with small gradients take larger steps and vice versa. Limitation: Learning rates monotonically decay, potentially stopping training prematurely.
- Adam (Kingma et al., 2014) uses exponential moving averages of both the gradient (momentum, mt) and the squared gradient (variance, vt). The update rule is θti←θt−1i+αvti+ϵmti. Adam's per-parameter learning rates do not decay monotonically, often performing better in practice, especially for non-convex optimization. Adam or its variants are the de facto standard optimizers.
Generalization and Model Selection
The goal is to minimize the expected risk R(θ)=Edata[L([x,y],θ)], which is intractable. We minimize the empirical risk R^(θ)=N1n=1∑NL([xn,yn],θ) on a training set D. Generalization bounds quantify the likely gap ∣R(θ)−R^(θ)∣. Using Hoeffding's inequality, for a fixed θ, R(θ)<R^(θ)+2N1logδ2 with probability 1−δ. For a finite hypothesis space Θ of size ∣Θ∣, a union bound gives R(θ)<R^(θ)+2Nlog∣Θ∣−logδ with probability 1−δ for any θ∈Θ. This shows that the generalization gap increases with model complexity (size of Θ) and decreases with data size N. For infinite hypothesis spaces, concepts like VC dimension [cs/9901010] or PAC-Bayesian bounds are needed. PAC-Bayesian bounds [cs/9901010, cs/9807005] offer a more actionable perspective, relating the expected risk under a distribution of models Q(θ) to the empirical risk under Q, and the KL divergence between Q and a prior P. R(Q)≤R^(Q)+2N1(DKL(Q∥P)+logδN+1). This suggests minimizing empirical risk is important, but also keeping the learned model distribution Q close to a prior P helps generalization.
Bias, Variance, and Uncertainty: The expected squared error can be decomposed into irreducible error (noise in data, aleatoric uncertainty), bias2 (how well the average prediction across model variations matches the true mean), and variance (how much predictions vary across model variations, epistemic uncertainty). Complex models tend to have low bias but high variance; simple models have high bias but low variance. Learning involves balancing this tradeoff.
Uncertainty in Error Rate:
- Confidence Interval: Quantifies uncertainty in the test set error for a fixed model, assuming the test set is a random sample. Using the Central Limit Theorem (for large test sets), a confidence interval for accuracy can be estimated using the sample mean and variance of the per-instance loss.
- Credible Interval: Quantifies uncertainty in test error due to model variation (e.g., from different training runs, random initialization). This requires considering a distribution over models p(θ∣D).
- Training Set Variation: The uncertainty due to the specific training set realization can be assessed using methods like Bootstrap resampling, creating multiple "training sets" by sampling with replacement and training models on each.
Hyperparameter Tuning: Hyperparameters λ control the learning process itself. Tuning involves finding λ that minimizes the generalization error, typically estimated using a validation set Dval. Tune(Dval,D;ϵ′)=argλminEϵ[R^(Learn(D;λ,ϵ);Dval)]. Because the learning process Learn is often a blackbox function of λ, blackbox optimization methods are used:
- Random Search (Qadri et al., 2011): Sample λ from a prior distribution and evaluate them in parallel on the validation set.
- Sequential Model-Based Optimization (SMBO) [9807003, (Brandao et al., 2012)]: Build an uncertainty-aware model (e.g., Gaussian Processes, though not explicitly mentioned) that predicts the validation risk of λ given previously evaluated λ-risk pairs. Use this model's prediction and uncertainty to select the next promising λ to evaluate, often by maximizing an acquisition function like Expected Improvement.
A separate test set Dtest must be used for final, unbiased evaluation after hyperparameters are tuned, often by training the final model on D∪Dval with the best λ.
Building Blocks of Neural Networks
Beyond simple linear transformations, neural networks are built from various differentiable blocks:
- Normalization: Techniques applied within the network to normalize activations, improving optimization conditioning (making Hessian closer to identity).
- Batch Normalization (Batch Norm) (Ioffe et al., 2015): Normalizes inputs across the batch dimension (mean and variance are computed per feature across the batch). Has different behavior during training (uses batch stats) and inference (uses population stats, typically running averages).
- Layer Normalization (Layer Norm) (Ba et al., 2016): Normalizes inputs across feature dimensions within each instance. Avoids the training/inference discrepancy of Batch Norm but can break relationships between instances if not used carefully (e.g., magnitude-based classification).
- Convolutional Blocks: Leverage spatial (or temporal) structure by applying learned filters locally and repeatedly. This introduces translation equivariance (or invariance when combined with pooling/reduction) and is suitable for grid-like data (images, time series).
- Recurrent Blocks: Process sequential data by applying the same function iteratively, maintaining a hidden state (memory) that depends on previous inputs. Allows unbounded context size in principle. Examples like Gated Recurrent Units (GRUs) (Cho et al., 2014) use gating mechanisms to mitigate vanishing gradients [9402007].
- Attention Blocks: Operate on sets or sequences, allowing each output element to be computed by aggregating information from all input elements based on learned compatibility scores (attention weights). This provides permutation equivariance for sets. For sequences, positional encoding (additive or relative (Su et al., 2021)) is added to input features to inject position information. Masking (causal masking) is used for autoregressive sequence processing so output at position i only depends on inputs up to position i−1. Multi-headed attention allows learning different aggregation patterns.
Probabilistic Machine Learning and Unsupervised Learning
Probabilistic models explicitly define probability distributions. An energy function e(x,z,θ) can define a joint distribution p(x,z;θ)∝exp(−e(x,z,θ)). Directed models decompose p(x,z) as p(z)p(x∣z). Unsupervised learning focuses on modeling the data distribution p(x), often by marginalizing out latent variables z: p(x)=∫p(z)p(x∣z)dz.
Variational Inference (VI) [9803056]: Approximates the intractable true posterior p(z∣x) with a tractable distribution q(z;ϕ(x)) by minimizing their KL divergence DKL(q∥p). This minimization is equivalent to maximizing the Evidence Lower Bound (ELBO): logp(x;θ)≥Ez∼q[logp(x∣z;θ)]−DKL(q(z;ϕ(x))∥p(z)). Maximizing the ELBO jointly optimizes q (finding a better approximation to p(z∣x)) and θ (improving the model's fit to x).
- Variational Gaussian Mixture Models (MoG): With z as a discrete cluster ID, p(z) a categorical prior, and p(x∣z) a Gaussian, the ELBO can be optimized via Expectation-Maximization (EM). In this case, the optimal q(z∣x) is the true posterior, making the ELBO tight. This connects to K-Means clustering as a hard-assignment version of EM (or MoG at β→0).
- Continuous Latent Variable Models: With z as a continuous vector and p(x∣z) Gaussian with mean F(z;θ), the ELBO is Ez∼q[−21∥x−F(z;θ)∥2]−DKL(q(z;ϕ(x))∥p(z)). For linear F and Gaussian q,p, this relates to Probabilistic PCA [9905026]. Generally, gradients w.r.t. ϕ(x) are intractable.
- Variational Autoencoders (VAEs) (Kingma et al., 2013, Rezende et al., 2014): Address tractability for nonlinear F and Gaussian q by:
- 1. Amortized Inference: Using an inference network G(x;θG) to predict the parameters ϕ(x) of q(z∣x) (e.g., mean and variance for a Gaussian q). This avoids storing per-instance parameters and enables generalization to new data.
- 2. Reparametrization Trick: Sampling z∼q(z∣ϕ(x)) as z=g(ϵ;ϕ(x)) where ϵ is sampled from a fixed distribution (e.g., N(0,I) for Gaussian q). This makes the sample z a deterministic function of ϕ(x) and ϵ, allowing backpropagation through the sampling process.
- The VAE objective becomes maximizing Eϵ[−21∥x−F(G(x;θG)+σϵ;θ)∥2]−DKL(q∥p) (using the reparametrization). This can be trained end-to-end with SGD. The objective has a reconstruction term and a prior matching/regularization term for q.
- Importance Sampling: Provides an unbiased way to estimate the marginal likelihood p(x) from VAEs or other generative models after training. By sampling z from the learned approximate posterior q(z∣x) instead of the prior p(z) and re-weighting, Ez∼p(z)[p(x∣z)]=Ez∼q(z∣x)[q(z∣x)p(x∣z)p(z)]. The learned q serves as an effective proposal distribution for a low-variance estimate.
Undirected Generative Models
Undirected models (e.g., Boltzmann Machines) define a joint distribution p(x,z)∝exp(−e(x,z)) directly from an energy function, without assuming a causal direction. The challenge is the intractable normalization constant (partition function) in high dimensions.
- Restricted Boltzmann Machines (RBMs) [86] use a bipartite graph between observed x and binary latent z. The energy e(x,z)=−x⊤Wz−x⊤b−z⊤c. Marginalizing z yields p(x) as a Product of Experts (PoE) [0204345]. Training involves minimizing negative log-likelihood, requiring gradients ∇θe(x,θ)−Ex′∼p(x′;θ)[∇θe(x′,θ)]. The expectation over p(x′;θ) is intractable.
- MCMC Sampling [Hastings 1970] is used to approximate the expectation by drawing samples from p(x;θ). Gibbs sampling is tractable for RBMs' conditional distributions p(z∣x) and p(x∣z).
- Contrastive Divergence (CD) [0204345] approximates the negative phase using only a few steps of Gibbs sampling starting from training data.
- Persistent Contrastive Divergence (PCD) runs MCMC chains in the background, persisting samples across SGD steps, which helps the samples better track the evolving model distribution and converges asymptotically to exact log-likelihood gradients.
- Energy-Based Generative Adversarial Networks (GANs) (Zhao et al., 2016, Goodfellow et al., 2014) train a generator g(ϵ;θg) (a sampler from a simple distribution p(ϵ)) and an energy function e(x;θ) in an adversarial minimax game. The energy function is trained to assign low energy to training data and high energy to generated samples. The generator is trained to produce samples with low energy. This avoids MCMC sampling for training the energy function. The generator's objective may include terms like MMD (Oana et al., 2012) to encourage diversity. An autoencoder's reconstruction error can be used as an energy function.
Autoregressive Models
Instead of latent variables, autoregressive models factorize the joint distribution of an observation X=(x1,…,xd) using the chain rule: p(X)=∏i=1dp(xi∣x<i). A single neural network models all conditional distributions p(xi∣x<i).
- Implemented using recurrent networks (like GRUs) or masked attention networks (like Transformers (Vaswani et al., 2017) with causal masking (Sutskever et al., 2014)). Causal masking ensures p(xi∣x<i) only depends on elements x1,…,xi−1.
- Major advantages: Exact computation of log-probability for any X and exact, tractable sampling (by generating x1, then x2 conditioned on x1, etc.). This contrasts with the intractability in latent variable and undirected models. Used widely in sequence modeling (e.g., LLMs (Brown et al., 2020)).
Further Topics
- Reinforcement Learning (RL) (Mnih et al., 2016): Learning to maximize expected reward from actions taken in an environment. In a single-step setting, training a classifier to maximize expected reward involves the Policy Gradient: ∇θEy∣x;θ[R(y)]=Ey∣x;θ[R(y)∇θlogp(y∣x;θ)]. This can be estimated with a single sample (R(y~)−b(x))∇θlogp(y~∣x;θ), where b(x) is a learned baseline to reduce variance. For multi-step RL with a Markov environment and cumulative discounted reward, Temporal Difference (TD) learning trains a value function (critic) by minimizing the difference between the estimated value and a bootstrapped target using the immediate reward and the value of the next state. Actor-Critic methods train a policy (actor) using the value function (critic) to provide a low-variance estimate of the advantage.
- Ensemble Methods: Combining multiple models to improve performance and estimate uncertainty.
- Bagging [breiman1996bagging]: Average predictions from models trained on bootstrap resamples of the training data. Theory shows averaging reduces variance. Stochasticity in SGD training (initialization, minibatches) implicitly generates diverse models suitable for ensembling.
- Bayesian ML: Defines a posterior distribution p(θ∣D)∝p(θ)x∈D∏p(x∣θ). Prediction involves marginalizing θ (averaging predictions from p(x∣θ) weighted by the posterior). Sampling models from the posterior and averaging them corresponds to bagging. SGD, especially with appropriate learning rates or noise, can be seen as an approximate sampler of the posterior (Kamaraju et al., 2010).
- Gradient Boosting [0107107]: Iteratively trains weak learners to fit the negative gradient of the loss function w.r.t. the current ensemble's prediction.
- Regression (Mixture Density Networks - MDNs) [bishop1994mixture]: For continuous outputs y∈Rd, modeling p(y∣x) as a mixture of simple distributions (e.g., Gaussians) conditioned on x. A neural network predicts the parameters of the mixture components (means, variances, weights) based on x. This allows capturing multimodal predictive distributions, unlike standard regression. Training maximizes log-likelihood. Sampling from the learned distribution is easy, allowing estimation of credible regions.
- Causality: Most ML relies on association. Causal inference aims to understand relationships under intervention, which is crucial for robustness to distribution shifts (Out-of-Distribution generalization) and controlling systems. Examples like confounding (common unobserved causes) and selection bias (conditioning on a common effect) show how correlation arises without causation. This is a complex topic beyond standard ML.
The note concludes by highlighting that this lecture covers foundational machine learning concepts through the unifying lens of energy functions, optimization, and probabilistic modeling, providing a basis for understanding and implementing modern AI techniques.
Paper to Video (Beta)
No one has generated a video about this paper yet.
Whiteboard
No one has generated a whiteboard explanation for this paper yet.
Paper Prompts
Sign up for free to create and run prompts on this paper using GPT-5.
Top Community Prompts
Open Problems
We haven't generated a list of open problems mentioned in this paper yet.
Continue Learning
We haven't generated follow-up questions for this paper yet.
Related Papers
- The Curse of Recursion: Training on Generated Data Makes Models Forget (2023)
- Lecture Notes in Probabilistic Diffusion Models (2023)
- Pen and Paper Exercises in Machine Learning (2022)
- Deep Learning and Computational Physics (Lecture Notes) (2023)
- Distributional Diffusion Models with Scoring Rules (2025)
- LLM Post-Training: A Deep Dive into Reasoning Large Language Models (2025)
- Almost Bayesian: The Fractal Dynamics of Stochastic Gradient Descent (2025)
- Contextures: The Mechanism of Representation Learning (2025)
- Data-driven approaches to inverse problems (2025)
- Random Matrix Theory for Deep Learning: Beyond Eigenvalues of Linear Models (2025)
Authors (1)
Collections
Sign up for free to add this paper to one or more collections.
Tweets
Sign up for free to view the 10 tweets with 761 likes about this paper.
HackerNews
- Machine Learning: A Lecture Note (2 points, 0 comments)