Gaussian Mixture Models and Support Vector Machines
Prerequisite Knowledge
This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.
Previously Covered in This Subject
- K-Means Clustering — covered in Lecture 15. GMM is a direct extension of K-means into a probabilistic framework. The E-step/M-step structure carries forward directly from K-means to GMM.
- Gaussian Mixture Model Preview — covered in Lecture 15. The soft vs. hard clustering distinction and the basic idea of mixture models were introduced.
- Binary Classification (Logistic Regression) — covered in Lecture 7. SVM solves the same classification task but with a different principle: finding the maximum-margin separator instead of fitting a sigmoid.
- Optimization Fundamentals — covered in Lectures 3–6. The SVM primal problem is a constrained quadratic optimization; familiarity with gradient-based optimization and Lagrangian multipliers from earlier lectures is assumed.
Gaussian Mixture Models and Support Vector Machines
16.1 Context — From K-Means to Gaussian Mixture Models
16.1.1 Recap of K-Means Clustering
K-means is a clustering algorithm. It groups data objects into clusters by allocating every data object to exactly one cluster — "this point belongs to cluster one, that point belongs to cluster two." This assignment may change across iterations, but at every moment the algorithm declares a definite, exclusive cluster membership for each point.
This is called hard clustering. Each point gets a binary label: in or out. There is no middle ground.
The K-means algorithm works by minimizing a distortion measure: the sum of squared distances from each point to its assigned cluster center. It alternates between two steps: (E-step) assign each point to the nearest center, and (M-step) recompute each center as the mean of its assigned points. This two-stage iteration repeats until assignments stop changing. The same E-step/M-step language carries forward to GMM, which is why the professor introduces it: "It is exactly K-means extension. That is why we learned K-means first."
16.1.2 Why Remove Duplicates Before Clustering
If you have 100 copies of one record and 100 unique records, the mean gets pulled toward the repeated values. That one repeated record gains disproportionately large influence. The statistical description — the mean, the spread — gets warped, and from there it influences everything downstream: cluster centers, variance estimates, and ultimately the cluster assignments themselves. The professor emphasized: "The statistical description itself gets warped, and from there it influences everything downstream."
16.1.3 Introducing Gaussian Mixture Models (GMM)
A Gaussian Mixture Model (GMM) is a probabilistic model for clustering. Unlike K-means, which groups points by distance, GMM assumes that all data points are generated from a mixture of several Gaussian (bell-curve) distributions with unknown parameters.
The professor's central analogy is reverse engineering:
"If I had to recreate this exact dataset using a few bell curves, where would I place those bell curves? How wide would they be?"
If you try to draw a single Gaussian through the entire dataset, it will not capture the underlying structure. But if the data has distinct groups, you can place one Gaussian over each group. The question GMM answers is: where should these Gaussians go, how wide should they be, and how much does each one contribute?
16.1.4 Why Not a Single Gaussian?
Imagine a dataset of adult heights in a city. The data comes from two underlying distributions — men's heights (mean ~175 cm) and women's heights (mean ~162 cm). A person who is 168 cm tall could be a tall woman or an average-height man. A single Gaussian would smear both groups into one blob, losing this structure. You need two overlapping bell curves.
This height example is not just pedagogical — it is a classic real-world use of GMM: discovering latent groups (male/female) from unlabeled data without ever knowing the gender labels. GMM captures this by modeling the data as coming from multiple distributions, each with its own mean, variance, and weight.
16.2 Gaussian Mixture Model — Core Concepts
16.2.1 Hard Clustering vs. Soft Clustering
| Type | Algorithm | Behavior | Analogy |
|---|---|---|---|
| Hard clustering | K-means | A point belongs to cluster A OR cluster B — definite, exclusive | A passport: you are a citizen of exactly one country |
| Soft clustering | GMM | A point can be 85% cluster A, 10% cluster B, 5% cluster C | A pie chart of your ancestry: you can be part Italian, part Irish |
In GMM, the same data point can belong to multiple clusters with different probabilities. This is especially useful for points near the boundaries of overlapping Gaussians, where forcing a binary assignment would be arbitrary. The professor phrased it this way: "What if a point has equal probability of belonging to two clusters? It's very unlikely that probability is exactly equal, but if it happens, you decide. It doesn't matter."
16.2.2 Flexibility in Cluster Shape
K-means only cares about the Euclidean distance from each center. It assumes equal variance in all directions — clusters are circles (in 2D) or spheres (in higher dimensions). If you have two elongated, cigar-shaped clusters that overlap, K-means cannot identify them correctly. It will cut through them with a straight bisector and produce wrong assignments.
GMM is more flexible because it models three things per component:
- Mean — the center of each Gaussian (same idea as K-means centroids).
- Variance — how much a single variable spreads around the mean. Large variance = wide bell curve.
- Covariance — how two variables move together. If height and weight are positively correlated (taller people tend to be heavier), the covariance captures that tilt.
The covariance matrix encodes both variances and covariances:
- Diagonal entries (): variance along each axis — controls spread.
- Off-diagonal entries (): covariance between axes — controls tilt and shape.
Together, these parameters allow GMM to form elliptical clusters of arbitrary orientation, not just circles. The bell curve can be stretched, squeezed, and rotated to fit the data.
Visual intuition: Imagine looking down from above at the bell curves (the professor's "top view"). For a circular cluster, the contour lines are concentric circles — like a target. For an elliptical cluster, the contours are concentric ellipses — like a tilted stretched target. GMM can produce either shape depending on the covariance matrix.
16.2.3 The Core Idea — Data as a Mixture of Gaussians
If the data has three distinct groups, GMM assumes three separate underlying Gaussians. The final dataset is a combination (mixture) of points drawn from these three curves. Some points come from Gaussian 1, some from Gaussian 2, some from Gaussian 3. The mixing coefficient tells you what fraction of all data points come from Gaussian .
The professor contrasted this with models that assume all data comes from a single distribution: "This is fundamentally different from models that assume all data comes from a single distribution or a single group."
16.3 The GMM Algorithm — Expectation-Maximization
- Input: Dataset of points; number of components .
- Output: For each component : mean , variance , mixing weight . Plus soft assignments (responsibilities ) for every point.
16.3.1 Algorithm Overview (Conceptual)
The EM algorithm for GMM alternates between two steps. The professor described them with a coloring analogy that captures the intuition perfectly:
- Initialization — Start with random Gaussians. Pick values for the mean () and standard deviation () for each Gaussian you assume exists. If , pick .
- E-step (Expectation) — "Color the points." For every data point, calculate what percentage it belongs to each Gaussian. A point may be 99% blue (component 1) and 1% green (component 2). No point is ever 100% one cluster — that is the fundamental difference from K-means.
- M-step (Maximization) — "Recalculate the Gaussians." Using the points now assigned (with their percentage weights), recompute the mean, variance, and mixing weight for each Gaussian. The Gaussians shift closer to the data they represent.
- Repeat until convergence — when assignments stop changing between two consecutive iterations.
16.3.2 Visual Analogy — The "Coloring" Process
The professor drew concentric circles to represent each Gaussian — these are the "top view" of bell curves, as if looking down from above. The circles represent contours of equal probability density.
Initially, the Gaussians are placed randomly. Points closer to Gaussian 1 get colored mostly blue. Points closer to Gaussian 2 get colored mostly green. Points equally close get half-and-half.
After coloring, the Gaussians are recalculated — they move to better fit the points assigned to them. Then the coloring changes because the Gaussians moved. This cycle continues until stable.
"If you understood the concept, it is very easy, but if you simply try to by-heart the formula 100 percentage, you will miss one or other step. What is that coloring example? Keep in mind, we can do that. You'll be able to solve any given problem."
16.3.3 Formal Algorithm Steps
Choose the number of Gaussians . Randomly initialize parameters for each Gaussian :
- Mean (in 1D; or vector in multivariate)
- Variance (in 1D; or covariance matrix in multivariate)
- Mixing coefficient (start with equal weights)
In practice, Python libraries like scikit-learn run K-means first to get good initial centers, then use the resulting cluster means, covariances, and proportions as the starting GMM parameters.
The responsibility is the probability that data point belongs to component :
What each part means:
- Numerator: — "prior weight of cluster " times "how likely point is under Gaussian ."
- Denominator: sum of the same quantity over ALL clusters — normalizes so that for each point .
- Result: For each point , you get a probability distribution over the clusters. always.
This formula is Bayes' theorem in action: it computes the posterior probability of cluster membership given the data. In Bishop's notation (§9.2), this is , the responsibility of component for data point .
Why each update makes sense:
- New mean: A weighted average of all data points, where each point's contribution is weighted by — how strongly it belongs to cluster . Points that are 95% in cluster pull the mean much harder than points that are 5% in cluster .
- New variance: A weighted variance — same weighting logic. Measures the spread of points around the new mean, weighted by membership strength.
- New mixing coefficient: The average responsibility across all points. If many points belong strongly to cluster , will be large; if cluster is tiny, will be small. This is exactly: total effective points in cluster divided by .
Stop when the log-likelihood of the data stops improving significantly:
where is the log-likelihood of the observed data under the current GMM parameters, and is a small threshold (e.g., ).
Equivalent stopping conditions: parameters change by less than ; no point changes its most-likely cluster assignment between iterations. All three are practically telling the same thing — the model has stopped improving.
Consider points: with .
Initialization: ; .
E-step (Iteration 1): Compute for each point using the responsibility formula.
- Point 0: close to , far from → ,
- Point 3: close to , far from → ,
M-step (Iteration 1): Recompute means using weighted averages.
— shifted right toward its data.
shifts left toward . The Gaussians tighten around their respective clusters.
Convergence: In the next E-step, the cluster assignments (0,1 → C1; 2,3 → C2) do not change, so the algorithm stops after 2 iterations. The full worked example is in §16.5.
- Local optima: EM is not guaranteed to find the global maximum of the likelihood. Different random initializations can lead to different final clusterings. In practice, run EM multiple times with different starting points and keep the best result (highest log-likelihood).
- Singularities: If a Gaussian component collapses onto a single data point, its variance can shrink to zero and the likelihood can blow up to infinity. This is a known issue with maximum-likelihood GMM (Bishop §9.2.1). Using a small regularization on the covariance or a Bayesian approach avoids this.
- Slow convergence: EM can take many iterations when clusters overlap heavily. The log-likelihood often improves rapidly in early iterations and then plateaus — don't mistake the plateau for convergence.
16.4 GMM — Mathematical Foundation
16.4.1 1D Gaussian Probability Density Function
Every symbol named:
- (mu) — the mean, the center of the bell curve. "The average height."
- (sigma) — the standard deviation, controls the spread. Larger = wider, flatter bell.
- — the variance, the square of the standard deviation. "The spread of the heights."
- — the normalization constant. Ensures the total area under the curve equals 1.
- — the exponential kernel. Measures how far is from , scaled by the variance. When , this equals 1 (maximum). When is far from , this drops toward 0.
The professor's plain-language summary: "The average height is the mean. The spread of the heights is the variance."
In 1D: the parameter is variance (). In multivariate: the parameter is covariance ().
16.4.2 Multivariate Gaussian Probability Density Function
Every symbol named:
- — number of dimensions (features). For 2D data like height and weight, .
- — a data point, a vector of length .
- — the mean vector, also length . The center in -dimensional space.
- — the covariance matrix. Replaces the scalar from 1D. Its diagonal holds variances; off-diagonals hold covariances.
- — the inverse of the covariance matrix (the precision matrix).
- — the determinant of . A scalar measuring the "volume" of the covariance ellipsoid.
- — the squared Mahalanobis distance. This is the multivariate generalization of . It measures distance from to in units of the covariance, accounting for correlations between dimensions.
Visual intuition: In 2D, determines the shape of equal-probability contours. When (scaled identity), contours are circles. When has different diagonal values, contours are axis-aligned ellipses. When has non-zero off-diagonals, contours are rotated ellipses. The Mahalanobis distance is constant along each contour.
16.4.3 The GMM Probability Density Function
Why these constraints? is the prior probability that a randomly chosen data point comes from component . As probabilities, they must sum to 1 and each must be non-negative.
The professor emphasized: "This is the formula you need to remember." is the probability density at position — it tells you how likely you are to find a data point at that location. represents the weight or relative size of each cluster. If cluster 1 is large (more data points), might be 0.7 and might be 0.3.
Derivation from the latent-variable viewpoint (Bishop §9.2): Each data point has an unobserved (latent) variable indicating which component generated it. uses a 1-of- encoding: if point came from component , 0 otherwise. The joint distribution is . Marginalizing over gives the mixture: . This latent-variable formulation is what makes the EM algorithm possible.
16.4.4 Symbol Registry — GMM (1D)
| Symbol | Meaning | Type | Domain |
|---|---|---|---|
| Number of Gaussian components (clusters) | integer | ||
| Mixing coefficient (weight) of component | scalar | , | |
| Mean of Gaussian | scalar | ||
| Variance of Gaussian | scalar | ||
| Responsibility — probability point belongs to component | scalar | , | |
| Number of data points | integer | ||
| Gaussian PDF evaluated at | scalar |
16.5 GMM — Worked Example
16.5.1 Problem Setup
Data: Four points: , , ,
Goal: Fit a mixture of Gaussian components. Run one full iteration of EM (E-step + M-step).
16.5.2 Step 1 — Initialization
- Component 1 (C1): (mean of ), ,
- Component 2 (C2): (mean of ), ,
The professor noted: "It's not completely random. Python has its own ways of calculating the initial mean. Variance we assume as 1." This is akin to K-means initialization — picking sensible starting points based on domain knowledge.
16.5.3 Step 2 — E-step: Compute Responsibilities
For each point , compute the Gaussian likelihood under each component, then the responsibility .
Gaussian PDF formula:
With :
For :
For :
For (by symmetry with ):
For (by symmetry with ):
Summary of responsibilities (using the approximate values shown in lecture):
| Point | (C1) | (C2) | Dominant cluster |
|---|---|---|---|
| 0 | 0.95 | 0.05 | C1 (strong) |
| 1 | 0.80 | 0.20 | C1 (moderate-to-strong) |
| 2 | 0.20 | 0.80 | C2 (moderate-to-strong) |
| 3 | 0.05 | 0.95 | C2 (strong) |
Sense check: Points 0 and 1 are closer to → mostly C1. Points 2 and 3 are closer to → mostly C2. The boundary points (1 and 2) have more mixed responsibilities than the extremes (0 and 3). The probabilities for each point sum to 1. ✓
16.5.4 Step 3 — M-step: Update Parameters
Update (weighted average):
Using the precise responsibilities:
Using the lecture's approximate values (0.95, 0.80, 0.20, 0.05):
Update :
By symmetry,
With approximate values:
Update (weighted variance):
Using and precise responsibilities:
The variance has shrunk from 1.0 to ~0.62 — the cluster is tightening around its data.
Update mixing coefficients:
The mixing coefficients stay at 0.5 because the responsibilities are symmetric.
Parameter movement after iteration 1:
| Parameter | Initial | After Iteration 1 | Direction |
|---|---|---|---|
| 0.5 | ~0.68–0.71 | → shifted right toward its data | |
| 2.5 | ~2.29–2.33 | ← shifted left toward its data | |
| 1.0 | ~0.62 | ↓ tightened around cluster | |
| 1.0 | ~0.62 | ↓ tightened around cluster | |
| 0.5 | 0.5 | unchanged (symmetric data) | |
| 0.5 | 0.5 | unchanged (symmetric data) |
16.5.5 Step 4 — Repeat Until Convergence
The E-step and M-step are repeated. In this example, after one iteration the most-likely cluster assignments are already correct (0,1 → C1; 2,3 → C2). Running the E-step again with the updated parameters produces the same hard assignments, so the algorithm converges.
For larger datasets with more overlap, multiple iterations are needed. In general, stop when:
- The log-likelihood change (e.g., ), or
- Parameter changes are below threshold, or
- Cluster assignments stop changing.
The mixing coefficients stayed at 0.5 each for this symmetric example, but in asymmetric real datasets, values shift to reflect the relative sizes of the discovered clusters.
16.6 GMM — Practical Considerations
16.6.1 Choosing the Number of Components
Methods shared with K-means:
- Elbow method — Run GMM for and plot the log-likelihood (or BIC/AIC). The curve typically rises sharply at first, then bends like an elbow. Pick the at the bend — after that point, adding more components gives diminishing returns.
- Silhouette analysis — For each point, compute the silhouette score: , where is the mean distance to points in the same cluster, and is the mean distance to points in the nearest other cluster. Values range from (wrong cluster) to (well-clustered). Average across all points and pick the that maximizes the average silhouette.
- Cross-validation — Split the data, train GMM on folds, evaluate log-likelihood on held-out data. Pick the that gives the best held-out likelihood.
Methods specific to GMM:
- — the maximized likelihood of the model (how well it fits). Larger = better fit, so is smaller for better fit.
- — the total number of free parameters. For GMM with components in dimensions: means (), covariances ( for full covariance), and mixing coefficients (, since they sum to 1).
- — number of data points.
- Lower BIC or AIC is better.
The difference: BIC penalizes complexity more heavily ( vs. 2), so it favors simpler models for large . AIC tends to select slightly more complex models.
Procedure: Run GMM for . For each , record the BIC and AIC scores. Plot them. Pick the that minimizes the score. The scores come directly from the GMM fitting output — Python's sklearn.mixture.GaussianMixture provides both .bic() and .aic() methods.
16.6.2 Initialization Strategies
- Random initialization — Pick random and . Simple but unreliable. Run multiple times with different seeds and keep the best result (highest log-likelihood).
- Hierarchical splitting — Start with (a single Gaussian over all data). Find the component with the largest variance and split it into two. Repeat until you reach the desired . Analogous to choosing the two farthest centroids in K-means initialization.
- K-means first, then GMM (recommended) — This is what scikit-learn does by default:
- Run K-means with the desired .
- Set initial = centroid of K-means cluster .
- Set initial = sample covariance of points in cluster .
- Set initial = (points in cluster ) / (total points).
16.6.3 Convergence Criteria
All three are equivalent in practice — they detect when the model has stopped improving:
- Parameter change below threshold — Stop when , , and for all .
- Log-likelihood change below threshold — The most principled approach. Stop when: where is the log-likelihood. Typical .
- Assignment stability — Stop when no point changes its most-likely cluster between iterations (or when fewer than a tolerance fraction change).
16.7 Support Vector Machines — Core Concept
16.7.1 The Classification Problem
Consider predicting whether a student gets admission into their top-choice IIT. Two features matter: CGPA and JEE score. Plot each student as a point on a 2D graph:
- Blue triangles ▲ = students who got in → label
- Red circles ● = students who did not → label
The task: draw a line that separates these two classes. In higher dimensions, this becomes a hyperplane.
Visual intuition: The x-axis is CGPA, the y-axis is JEE score. Blue points cluster in the top-right (high CGPA, high JEE). Red points cluster in the bottom-left. The separator is a straight line cutting diagonally between them.
16.7.2 Which Line Is Best?
The professor showed three candidate lines:
- L₁: Separates the data but is dangerously close to the red points. A new red observation slightly different from the training data could easily fall on the wrong side. No safety margin.
- L₃: Separates the data but is dangerously close to the blue points. Same problem — no breathing room on the blue side.
- L₂: Sits squarely in the middle, giving breathing room to both classes. Even if new observations vary slightly from the training data, they are likely to stay on the correct side.
"If I ask you — you don't know machine learning — which among these three lines will you be choosing to differentiate these two classes? You would pick L₂ because it gives breathing space. That is SVM."
16.7.3 Decision Boundary, Margin, and Support Vectors
Decision boundary (the dashed middle line):
At this line, the prediction is 50-50 — we cannot decide the class. Points exactly on this line are equally likely to be either class.Margin — The distance from the decision boundary to the nearest data point of each class. The total gap between the two outer margin lines is . The SVM's goal is to make this as wide as possible.
Support vectors — The data points that lie exactly on the margin boundaries (or are closest to the decision boundary). These are the hardest points to classify — the ones that constrain how wide the margin can be. They are the only points that matter for determining and .
The "namaste" analogy: The professor gave a vivid physical metaphor:
"When you're doing namaste, how much can you move your hands apart so that you don't touch the people on both sides? I want to move my hands as far as possible. When you touch somebody on one side, that much only we will take on the other side also — that is the maximum."
Your hands are the margin lines. The people on either side are the support vectors. You spread your hands until they touch the nearest person on each side. That equal distance on both sides defines the maximum margin. The decision boundary runs exactly halfway between your hands.
16.7.4 SVM as an Optimization Problem
- Goal: Maximize the margin = .
- Constraint: Every training point must lie on or outside its respective margin line (for hard-margin SVM).
In different dimensions, the separator has different names:
- 2D: find the best line.
- 3D: find the best plane.
- 4D and higher: find the best hyperplane.
The math treats all cases uniformly — even a line is a "hyperplane" in the formalism: only the first weight term is non-zero, and the rest vanish. The professor noted: "In literature, even a line is called a hyperplane because the hyperplane equation is used."
SVM is a supervised classification algorithm. Unlike GMM (unsupervised clustering), SVM requires labeled training data: you must know which points are and which are .
16.7.5 Hard Margin vs. Soft Margin
Hard margin SVM: No misclassifications allowed. Every training point must be on the correct side of (or exactly on) its margin line. Problem: if there is an outlier — say, a red point deep in blue territory — SVM is forced to draw the boundary near that outlier, producing a terrible classifier.
The professor's example: "Consider some student who got a very high JEE score but due to some issue (say CGPA problem, or some malpractice identified later), even though the student seems like a top candidate, they were not selected. The data point sits in blue territory but is actually red. SVM will draw the boundary near that outlier, creating a wrong boundary."
Soft margin SVM: Allows some misclassifications. The algorithm tolerates a few points on the wrong side of the margin, paying a penalty proportional to the violation. This makes the model more generalizable and less sensitive to outliers. Soft margin SVM (with slack variables ) is covered in the next class and is what is used in virtually all real-world applications.
| Hard margin | Soft margin | |
|---|---|---|
| Misclassifications | Zero tolerance | Tolerated, with penalty |
| Outlier sensitivity | Extremely sensitive | Robust |
| Data requirement | Must be linearly separable | Works with overlapping classes |
| Real-world usage | Mostly theoretical | Used everywhere |
16.8 SVM — Mathematical Formulation
16.8.1 Setup and Notation
- — a vector of features (e.g., CGPA and JEE score, so ).
- — the class label.
- : positive class (got admission, blue triangle ▲)
- : negative class (did not get admission, red circle ●)
- If → predict
- If → predict
16.8.2 Hyperplane Equations
Decision boundary (dashed middle line):
Right margin line (positive side, prediction = ):
Left margin line (negative side, prediction = ):
Where:- — the weight vector. Like the slope coefficients in a line equation. .
- — the bias (intercept). A scalar. Shifts the hyperplane away from the origin.
- — a feature vector.
Any point with is classified . Any point with is classified . Points in between () lie inside the margin.
What about 2D? For a line in 2D, the equation is . This is exactly the hyperplane equation with . The professor emphasized: "Even though it is lower dimension, they use the hyperplane equation itself."
16.8.3 The Normal Vector
Why this matters: To measure the margin, we need the shortest distance from a point to the hyperplane. The shortest path is always along the normal direction — the direction of . This is why the margin width ends up being .
16.8.4 Deriving the Margin Size
Start on the decision boundary: . Walk units in the direction of (perpendicular to the boundary) until you hit the line .
The unit vector in the direction of is . So your new position is:
Plug this into the line equation:
Distribute the dot product:
Since you started on the decision boundary, . Substitute:
Now (definition of the squared norm):
So the distance from the decision boundary to one margin line is . The total margin (gap between the and lines) is:
Sense check: As gets smaller, the margin gets larger. If , the margin (but then the hyperplane would classify everything as one class — the constraints prevent this). ✓
16.8.5 The Optimization Problem (Primal Form)
Maximizing is equivalent to minimizing . For mathematical convenience, we minimize instead. The factor makes the derivative clean: .
Subject to the constraint that every point is correctly classified and lies on or outside its margin:
Why does one inequality cover both classes?
- For : We need . Multiply by : . ✓
- For : We need . Multiply both sides by (flipping the inequality): . Since : . ✓
Both cases reduce to the same inequality. This elegant trick is what makes the SVM formulation so compact.
The professor: "From where did the ½ come? Nowhere. It is just a mathematical convenience so that when we take the gradient later it will be easier. You remember in linear regression also we used to add ½ so that the derivative becomes easy."
This is a quadratic programming problem: minimize a quadratic objective subject to linear inequality constraints. For this class of problems, any local minimum is also a global minimum — a crucial property that makes SVM optimization reliable.
16.8.6 Symbol Registry — Linear SVM
| Symbol | Meaning | Type | Domain |
|---|---|---|---|
| Weight vector (normal to hyperplane) | vector | ||
| Bias (intercept) | scalar | ||
| Feature vector for data point | vector | ||
| Class label for data point | scalar | ||
| Number of data points | integer | ||
| Number of features (dimensions) | integer | ||
| Euclidean norm (magnitude) of | scalar | ||
| Margin | Total width between margin lines | scalar |
16.9 From Primal to Dual — The Lagrangian Approach
16.9.1 Why Convert to a Dual Problem?
In the primal problem, we minimize over . The computation involves dot products for every data point. When is large — think image data with 10,000+ pixels per image but only a few hundred images — this is expensive.
The dual formulation transforms the problem so that:
- We optimize over Lagrangian multipliers instead of the -dimensional .
- Only the for support vectors are non-zero. All other .
- The data appears only as dot products between pairs of points (), not between weights and features.
- When , the dual is far cheaper to solve.
The professor's own words: "In large dimension data, the number of records are much smaller than the number of columns. So this calculation will be reduced a lot. That's the reason we are doing all of this gimmick."
16.9.2 Lagrangian Function
16.9.3 KKT Conditions and Stationarity
The Karush-Kuhn-Tucker (KKT) conditions are necessary conditions for optimality in constrained optimization. The professor noted they are covered in the Mathematical Foundations for ML course. The key condition for the dual derivation is stationarity: set the partial derivatives of the Lagrangian to zero.
Derivative with respect to :
Wait — let's compute carefully. The term inside the sum is . Taking derivative with respect to : . So:
This is a constraint on the values: the weighted sum of labels must be zero.16.9.4 The Dual Problem
Substitute and the constraints into the Lagrangian:
The bias term vanishes because . The two double sums combine (they're the same sum since ), giving .
The dual maximization problem:
Subject to: and for all .Equivalently, as a minimization (negate the objective, which is what most solvers use):
This is the standard dual form from Bishop §7.1 (equation 7.10). The primal and dual are equivalent — solving one gives the solution to the other via .16.9.5 Why the Dual Is More Efficient
In the dual, data appears only as dot products . The are non-zero only for support vectors (a consequence of the KKT complementary slackness condition: ).
So the double sum is effectively only over support vectors — a small fraction of the training data. This makes the dual dramatically more efficient when .
KKT complementary slackness (the reason for sparsity): For every data point, either (point is irrelevant — not a support vector) or (point lies exactly on its margin boundary — it IS a support vector). Most points have and can be discarded after training.
16.9.6 The Classification Function
- If → classify as
- If → classify as
The weight vector is recovered as .
Computing (the bias): For any support vector (a point with ), we know . Solving for :
Since , multiply through by :
For numerical stability, average over all support vectors (Bishop §7.1, equation 7.18):
- Classification:
- Weight vector:
- Bias: computed from any support vector as above.
16.10 SVM — Worked Example
16.10.1 Problem Setup
Three data points, each with features augmented by a bias column of 1:
| Point | Features (with bias) | Label |
|---|---|---|
The third component "1" is the bias term added manually — the same technique used in linear regression when adding a column of ones for the intercept. This absorbs into the weight vector: the third component of will be .
Visual intuition: Plot these in 2D (ignoring the bias column). is the lone negative point at the bottom. and are the two positive points at the top, symmetrically placed. The decision boundary should be a horizontal line somewhere between and .
16.10.2 Step 1 — Write the System of Linear Equations
For support vectors (all three points will turn out to be support vectors), the classification condition is:
For ():
Compute the dot products:
- →
- →
- →
For ():
- →
- →
- →
For ():
- →
- →
- →
16.10.3 Step 2 — Solve the System of Linear Equations
Subtract Eq 3 from Eq 2:
Let . Substitute into Eq 1:
Substitute into Eq 2:
Therefore:
All three → all three points are support vectors.
16.10.4 Step 3 — Compute and
So . The third component is the negative of the bias: .
16.10.5 Step 4 — Write the Decision Boundary
The decision boundary: .
The decision boundary is the horizontal line .
The margin lines:
- Right side (): → →
- Left side (): → →
Verification — check that support vectors lie on margin lines:
- : ✓ (on margin)
- : ✓ (on margin)
- : ✓ (on margin)
Margin width: . The effective margin in the 2D projection is the distance between the margin lines: .
16.10.6 Interpretation
- Any point with (on or above ) → class
- Any point with (below ) → class
Sense check: The two positive points and are at the same height, symmetrically placed at and . The single negative point is at , . The maximum-margin line should indeed be horizontal at — the midpoint. The -coordinate doesn't matter because both positive points share the same -value, making the problem effectively 1D in the direction. ✓
16.11 Student Questions and Answers
The following questions capture distinct confusion points raised during the lecture. Repetitive questions have been merged into the clearest canonical version. Frequency noted where multiple students asked the same thing.
16.12 Exam Guidance
16.12.1 Mark Distribution
16.12.2 Problem Types
- Compute responsibilities in the E-step using
- Update parameters in the M-step:
- Check convergence (assignments stop changing or log-likelihood stabilizes)
SVM exam problems — Expect to be given 3-4 data points with labels. You must:
- Write the system of linear equations: for each
- Solve the system for
- Compute and extract
- Write the decision boundary equation and margin lines
- State the classification rule
16.12.3 What to Know (and What Not To)
- GMM: Responsibility formula, mean update, variance update, mixing coefficient update
- SVM: Classification function , weight vector , bias formula from a support vector
- SVM: How to write the system of linear equations from data points
Derivations are for understanding only:
- Lagrangian function, KKT conditions, and derivation of the dual problem
- The professor: "Derivations you can take from the slide. Nobody may ask, but ML maybe will not ask."
Open book: Formulas will be available in the slides. The common slides are what you can take into the exam. But you must know which formula to apply when — memorizing the structure is more important than memorizing every symbol.
16.12.4 Study Advice
- Concept first, formulas second. If you understand the "coloring" process for GMM and the "margin maximization" idea for SVM, the formulas become easy. The professor warned: "If you simply try to by-heart the formula 100 percentage, you will miss one or other step."
- For SVM: "These three equations — (classification function), equation, and equation — you just use those three equations for problem solving."
- For GMM: The E-step = coloring example. Keep that picture in mind: "You'll be able to solve any given problem."
- Practice solving systems of linear equations. The SVM exam problem reduces to exactly this skill. The professor: "Just please study solving system of linear equations."
- The professor will upload a complete worked SVM example with all solving steps — use it to practice.
16.13 Key Industry Applications and Real-World Connections
- GMM for unsupervised discovery — height data and beyond. The classic example: adult heights in a city come from two underlying distributions (men and women). GMM discovers these latent groups without ever seeing gender labels. This same pattern applies to several real-world tasks: customer segmentation (discovering spending-personality types from transaction data), anomaly detection (flagging points with low probability under the fitted GMM as outliers), and image segmentation. For image segmentation, the technique is known as vector quantization — each pixel is represented by its closest cluster center (Bishop §9.1.1).
- SVM for binary classification — admissions, medicine, and finance. The motivating example uses CGPA and JEE scores for admission prediction — a realistic binary classification scenario. The same framework applies to: loan default prediction (will this borrower repay?), medical diagnosis (malignant vs. benign tumor from imaging features), spam detection (spam vs. not-spam from email features), and face detection (face vs. non-face from pixel intensities).
- Large-dimensional data — why SVM's dual shines. The professor emphasized image data as the motivating case for the dual formulation. Images have thousands of pixels (features) but training sets may have only hundreds of images. In this regime, the dual form reduces computation dramatically by working with dot products between data points rather than dot products with the weight vector. The same advantage applies to text classification with bag-of-words features (vocabulary size = ).
- Python implementations — K-means initializes GMM. scikit-learn's
GaussianMixtureuses K-means to initialize cluster centers, covariances, and mixing weights before running EM. This gives faster, more reliable convergence. Similarly,sklearn.svm.SVCimplements both linear and kernel SVMs with efficient solvers (SMO, libsvm). - Nonlinear SVM — the kernel trick (next lecture). The professor previewed that nonlinear SVM handles data that is not linearly separable. By replacing dot products with kernel functions , the SVM can learn nonlinear decision boundaries while keeping the same optimization framework. The popular Gaussian (RBF) kernel is the default in most libraries.
- Soft margin SVM — the practical default. Virtually all real-world SVM applications use soft margin (with slack variables and a regularization parameter ) because real data always has noise and overlapping classes. Hard margin is primarily a theoretical building block that leads to the more practical soft-margin formulation.
16.14 Professor Pedagogical Highlights
The professor used several memorable analogies and teaching strategies throughout this lecture. These are preserved here as they capture the intuitive core of each concept.
Reverse engineering analogy for GMM:
"It's like reverse engineering. We are going to look at the data set and we are going to ask: if I have to recreate this particular data set using a few Gaussian distributions, where will I put those bell curves? How wide would they be?"
Namaste analogy for margin:
"When you're doing namaste... how much you can move your hands apart so that you don't touch the people on both sides? I want to move my hands as far as possible. When you touch somebody on one side, that much only we will take on the other side also — that is the maximum."
Top-view visualization for Gaussians:
The concentric circles in GMM plots are the top view of bell curves — "You are standing here and looking at this... You're at the sky. Imagine and you're looking at this."
Heads-up on difficulty — GMM:
"Don't panic if you're not understanding in the beginning. By the end, once we complete that, you will be able to connect the dots or stitch the parts together. It is how everyone is going to feel it. So don't think that only I'm not understanding or only I'm not able to make sense."
Heads-up on difficulty — SVM dual:
"Whatever I'm going to explain to you in the next 10 minutes, none of you are going to make sense, but listen. Listen it once, listen it twice, listen it thrice. You will get an idea."
Formula memorization warning:
"If you understood the concept, it is very easy, but if you simply try to by-heart the formula 100 percentage, you will miss one or other step. What is that coloring example? Keep in mind, we can do that. You'll be able to solve any given problem."
On GMM as K-means extension:
"It is exactly K-means extension. That is why we learned K-means first."
On the ½ in SVM objective:
"From where did it come? Nowhere. It is just a mathematical convenience so that when we take gradient later it will be more easy for us. You remember in linear regression also we used to add ½ so that the derivative becomes easy."
On SVM as an idea:
"If I ask you — you don't know machine learning — which among these three lines will you be choosing to differentiate these two classes? You would pick L₂ because it gives breathing space. That is SVM. That's the end of SVM."
ML Lecture 16 notes · Gaussian Mixture Models and Support Vector Machines
Sections Breakdown
Bridges from hard K-means clustering to the soft, probabilistic GMM framework, covering the limitations of hard clustering and the reverse-engineering analogy for mixture models.
Hard vs. soft clustering comparison, flexibility in cluster shape via covariance matrices, and the core idea of data as a weighted sum of Gaussian distributions.
The EM algorithm steps: initialization, E-step (compute responsibilities), M-step (update parameters), and convergence check. Includes the coloring analogy and formal algorithm statements.
1D and multivariate Gaussian PDFs, the GMM probability density function as an additive mixture, and a complete symbol registry for 1D GMM.
Full step-by-step EM on a 4-point dataset with K=2: E-step responsibility calculations, M-step parameter updates, and convergence analysis.
Choosing K via BIC/AIC/elbow method, initialization strategies (K-means first recommended), and convergence criteria.
The margin maximization intuition, decision boundary/hyperplane, support vectors and their sparsity property, the namaste analogy, and hard vs. soft margin comparison.
Setup and notation, hyperplane equations, normal vector concept, step-by-step margin width derivation, and the primal optimization problem.
Why convert to dual, Lagrangian function, KKT stationarity conditions, complete dual derivation, and the classification function with the three key exam equations.
Full 3-point SVM example with bias column: system of linear equations, solving for alpha values, computing w and b, writing the decision boundary.
Consolidated student questions covering duplicate removal, random initialization, 50-50 splits, dot product computation, overlapping points, margin behavior, and Lagrangian derivations.
Mark distribution, GMM and SVM problem types, what to memorize vs. what to understand, and study advice from the professor.
Real-world applications of GMM (customer segmentation, anomaly detection) and SVM (admissions, medicine, finance, image/text classification).
Memorable analogies: reverse engineering for GMM, namaste for SVM margins, top-view for Gaussians, and key teaching strategies.
Exam Revision Notes
Below is the distilled, exam-ready core of this lecture. Every entry is built from the full textbook notes above. Use this section for rapid review — but if something doesn't make sense, go back to the full explanation in the main content.
Gaussian Mixture Models — Soft Clustering and Mixture Concept
Must-know: GMM is a probabilistic clustering model that assigns each data point a soft membership — a probability distribution over clusters — rather than a hard binary assignment. The model assumes data is generated from a weighted sum (mixture) of K Gaussian distributions, each with its own mean , variance , and mixing coefficient (where ).
⚠️ Top pitfall: Forgetting the mixing coefficient constraint . Students often treat as free parameters — they are probabilities and must sum to 1.
Self-check: How does GMM differ from K-means in terms of (a) cluster assignment and (b) cluster shape?
Connects to: K-means clustering (hard assignment counterpart), EM algorithm (the fitting method), covariance matrices (enabling elliptical clusters).
Expectation-Maximization Algorithm for GMM
Must-know: The EM algorithm alternates between two steps. E-step: Compute responsibilities — the probability that point belongs to component . M-step: Update parameters using weighted averages. Repeat until log-likelihood stabilizes. Every point always has fractional membership — no point is ever 100% in one cluster.
⚠️ Top pitfall: Confusing the E-step and M-step formulas. The responsibility formula (E-step) uses the current parameters. The M-step formula uses the responsibilities just computed in the E-step. Also: forgetting that EM can converge to local optima.
Self-check: If and with and equal mixing coefficients, what is the approximate responsibility of for component 1?
Connects to: GMM model definition, convergence criteria (log-likelihood threshold ), K-means EM analogy, local optima problem.
GMM Worked Example — 4-Point Dataset
Must-know: The canonical exam problem: fit Gaussians to points . Initialize: . Run one full EM iteration. After E-step, responsibilities approximately: . After M-step, –, –, shrink to ~0.62. Both means move toward their natural clusters — variances tighten.
⚠️ Top pitfall: Using the updated mean in the variance formula but forgetting to use it in the squared deviation term . Also: not checking that responsibilities sum to 1 for each point.
Self-check: After the first M-step, why do the mixing coefficients stay at 0.5 for this symmetric dataset?
Connects to: EM algorithm steps, Gaussian PDF evaluation, convergence check, choosing K (BIC/AIC), initialization strategies.
GMM Practical Considerations — Choosing K, Initialization, and Convergence
Must-know: Choosing K: Use BIC () or AIC () — lower is better. BIC penalizes complexity more heavily. Initialization: K-means first (scikit-learn default) gives reliable starting positions. Convergence: Stop when (typically ).
⚠️ Top pitfall: Using BIC/AIC with too few candidate K values (just K=2,3,4). Always test a range and look for the minimum. Also: confusing which is lower-is-better — both BIC and AIC are lower-is-better.
Self-check: For a dataset with n=1000 points, which criterion (BIC or AIC) would favor a simpler model? Why?
Connects to: Elbow method, silhouette analysis, cross-validation for K selection, EM local optima, K-means initialization strategy.
Support Vector Machines — Margin Maximization Concept
Must-know: SVM finds the hyperplane that maximizes the margin between two classes. The margin is . The support vectors are the data points closest to the decision boundary — they are the only points that determine and . Moving any non-support-vector point does NOT change the boundary. This sparsity is the key computational property of SVMs.
⚠️ Top pitfall: Confusing the decision boundary () with the margin lines (). Also: thinking hard-margin SVM works when data is not linearly separable — it doesn't.
Self-check: How many support vectors does a hard-margin SVM typically have relative to the total number of training points?
Connects to: Binary classification, hard vs. soft margin, optimization constraints, Lagrangian dual formulation, kernel trick (next lecture).
SVM Mathematical Formulation — Primal Problem
Must-know: The SVM primal problem minimizes subject to for all . The factor is for derivative convenience. The elegant constraint trick covers both classes in one inequality. The margin is derived by walking units along the normal direction from the decision boundary to either margin line.
⚠️ Top pitfall: Forgetting that the constraint uses (not ). The 1 comes from the margin line equations . Also: not understanding why is perpendicular to the hyperplane — this is fundamental to the margin derivation.
Self-check: Derive why the distance from the decision boundary to one margin line is .
Connects to: Margin width derivation, normal vector concept, quadratic programming, KKT conditions, dual formulation.
SVM Lagrangian Dual — From Primal to Dual
Must-know: The dual formulation transforms the problem from optimizing over to optimizing over Lagrangian multipliers . The key result: . Only support vectors have (all others are zero). The dual is more efficient when . For classification: .
⚠️ Top pitfall: Forgetting the constraint . This comes from setting and is an essential constraint on the values. Also: thinking Lagrangian derivations are required for the exam — they are for understanding only.
Self-check: Why are most after solving the SVM dual? What condition makes an non-zero?
Connects to: Primal optimization, KKT complementary slackness, support vector sparsity, kernel trick (next lecture), bias computation.
SVM Worked Example — 3-Point Dataset with Bias Column
Must-know: The canonical exam problem: 3 points with augmented bias column of 1. ; ; . Solve the system for each . Solution: . Result: , decision boundary .
⚠️ Top pitfall: Forgetting to include the bias column of 1 in the feature vectors when computing dot products. The third component "1" absorbs into so that the decision boundary equation becomes instead of . Also: arithmetic errors in solving the 3×3 linear system — practice this.
Self-check: Verify that each support vector lies exactly on its respective margin line ( for negative, for positive).
Connects to: Classification function, system of linear equations, support vector identification, margin verification, bias extraction from augmented weight vector.
Was this lecture useful?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.