v9.1.1
Menu

Chapter 4: Model Fitting and Optimization

Week 5-6

Techniques for fitting models to data, handling outliers with RANSAC, and using regularization methods like Total Variation for robust computer vision.

Topics
3
Videos
3
Min read
19

Chapter Overview

Computer vision often requires finding mathematical models that explain observed data—whether it's a line through detected edge points, a transformation between images, or a surface representing an object. But real-world data is messy: sensors are noisy, features are misdetected, and outliers corrupt our measurements.

What is this chapter about? We study model fitting: given noisy, imperfect observations, how do we find the underlying model? This is fundamental to nearly every computer vision pipeline.

Why does this matter? Without robust fitting techniques, a single bad measurement can completely ruin your results. Imagine fitting a line to detected lane markers—one misdetection shouldn't send your self-driving car off the road.

How the topics connect: We start with Least Squares—the classic approach that works great when data is clean. Then we learn RANSAC, which elegantly handles outliers by finding consensus among the data. Finally, Total Variation shows how regularization can guide solutions toward realistic, edge-preserving results.

Chapter Roadmap

Click any topic to jump in

Explainer video
1
Least Squares

Linear regression, normal equations, and residuals — fitting models to data by minimizing error.

Least Squares CriterionNormal EquationsResiduals
Handling real-world data

Outlier robustness and regularization

2
RANSAC

Random sampling for robust fitting — handling outliers that break least squares.

RANSAC AlgorithmInlier ThresholdNumber of Iterations
3
Regularization

Total variation, ROF model, and edge preservation — adding priors to prevent overfitting.

Total VariationROF ModelEdge Preservation

Topics

3 topics in this chapter

Every measurement a camera or sensor hands you is corrupted a little: a detected edge point sits a pixel off, a matched feature drifts, a depth reading jitters. Yet you still need a single clean model — a line, a plane, a curve — that explains all those noisy points at once. How do you choose the one model that best balances every conflicting observation? That is the model-fitting problem, and least squares is the oldest and most important answer. The image-processing tools from the previous chapter gave you edges and features; now we must turn those scattered detections into geometry. Least squares picks the parameters that make the total squared error as small as possible, and because that error is quadratic, the best model has a clean closed-form solution you can compute directly. We start here because the method is exact, fast, and provably optimal when the noise is Gaussian. Its one great weakness — a single wild outlier can drag the whole fit off course, since squaring shows no mercy to large errors — is exactly what motivates RANSAC in the next topic, so understanding least squares first makes both its power and its limits clear.

Definition

Least squares fits a model to data by choosing the parameters that minimize the sum of the squared residuals — the vertical gaps between each observation and the model's prediction. When the model is linear in its parameters, this minimization has a unique closed-form solution given by the normal equations.

In this topic

  1. 1Least Squares Criterion
  2. 2Normal Equations
  3. 3Residuals
1 of 3
Least Squares Criterion

E=∑i(yi−f(xi))2E = \sum_i (y_i - f(x_i))^2

The least squares criterion minimizes the sum of squared residuals—the vertical distances from data points to the fitted curve, squared and summed. Here:

  • yiy_i is the observed value at point ii
  • f(xi)f(x_i) is the model's prediction at that point
  • The squaring penalizes large errors more heavily than small ones

This is the optimal solution when errors are normally distributed (Gaussian noise). However, it's sensitive to outliers because squaring amplifies large deviations. A single outlier can dramatically shift the fitted line.

Mathematical Intuition

The least squares objective E=∑i(yi−f(xi))2=∥b−Ax∥22E = \sum_i (y_i - f(x_i))^2 = \|\mathbf{b} - \mathbf{A}\mathbf{x}\|_2^2 minimizes the squared L2L^2 norm of the residual vector. Setting the gradient ∇xE=−2AT(b−Ax)=0\nabla_\mathbf{x} E = -2 \mathbf{A}^T (\mathbf{b} - \mathbf{A}\mathbf{x}) = 0 yields the normal equations. The quadratic form E(x)E(\mathbf{x}) defines a paraboloid in parameter space with a unique minimum when ATA\mathbf{A}^T \mathbf{A} is positive definite. Squaring penalizes large residuals disproportionately — a single outlier at distance dd contributes d2d^2 to the cost, giving it leverage proportional to d2d^2 on the solution.

Example:

Points (1,2), (2,3), (3,5) are fit with line y=x+1. Calculate the sum of squared errors.

2 of 3
Normal Equations

(ATA)x=ATb(\mathbf{A}^T\mathbf{A})\mathbf{x} = \mathbf{A}^T\mathbf{b}

The normal equations provide a closed-form solution to the least squares problem:

  • A\mathbf{A} is the design matrix, where each row contains features for one data point (e.g., [xi,1][x_i, 1] for linear regression)
  • x\mathbf{x} is the vector of parameters we're solving for (e.g., slope and intercept)
  • b\mathbf{b} is the vector of observed outputs (y values)
  • AT\mathbf{A}^T is the transpose of A\mathbf{A}

The solution is x=(ATA)−1ATb\mathbf{x} = (\mathbf{A}^T\mathbf{A})^{-1}\mathbf{A}^T\mathbf{b}, which can be computed directly using matrix operations. This is efficient for small to medium datasets but can be numerically unstable for ill-conditioned problems.

Mathematical Intuition

The normal equations (ATA)x=ATb(\mathbf{A}^T \mathbf{A})\mathbf{x} = \mathbf{A}^T \mathbf{b} project the observation vector b\mathbf{b} onto the column space of A\mathbf{A}. Geometrically, b^=Ax\hat{\mathbf{b}} = \mathbf{A}\mathbf{x} is the point in col(A)\text{col}(\mathbf{A}) closest to b\mathbf{b}, and the residual b−b^\mathbf{b} - \hat{\mathbf{b}} is orthogonal to every column of A\mathbf{A} — hence the name "normal" equations. The condition number κ(ATA)=κ(A)2\kappa(\mathbf{A}^T\mathbf{A}) = \kappa(\mathbf{A})^2 means numerical errors are amplified quadratically; for ill-conditioned problems, the SVD-based pseudoinverse x=A+b\mathbf{x} = \mathbf{A}^+ \mathbf{b} or QR decomposition is preferred.

Example:

For points (0,1), (1,3), write the design matrix A for fitting y=ax+b.

3 of 3
Residuals

ri=yi−y^ir_i = y_i - \hat{y}_i

Residuals are the differences between observed values (yiy_i) and predictions (y^i\hat{y}_i). Analyzing residuals helps validate your model:

  • Random scatter around zero: Good fit, model captures the pattern
  • Curved pattern: Model is missing nonlinear structure
  • Increasing spread: Heteroscedasticity—variance changes with xx
  • Clustering: Possible outliers or model inadequacy

The sum of residuals in linear regression always equals zero, but the sum of squared residuals (RSS) measures overall fit quality.

Mathematical Intuition

The residual vector r=b−Ax^\mathbf{r} = \mathbf{b} - \mathbf{A}\hat{\mathbf{x}} lies in the left null space of A\mathbf{A} (orthogonal complement of the column space). For a correctly specified linear model with i.i.d. Gaussian noise ϵi∼N(0,σ2)\epsilon_i \sim \mathcal{N}(0, \sigma^2), the residuals follow r∼N(0,σ2(I−H))\mathbf{r} \sim \mathcal{N}(\mathbf{0}, \sigma^2 (\mathbf{I} - \mathbf{H})) where H=A(ATA)−1AT\mathbf{H} = \mathbf{A}(\mathbf{A}^T\mathbf{A})^{-1}\mathbf{A}^T is the hat matrix. The unbiased estimator σ^2=∥r∥2/(n−p)\hat{\sigma}^2 = \|\mathbf{r}\|^2 / (n - p) uses n−pn - p degrees of freedom because the projection H\mathbf{H} consumes pp of the nn original dimensions.

Example:

Fitted line predicts [10, 20, 30] but actual values are [12, 19, 32]. Compute residuals and RSS.

Theory Exercise

Problem:

Given 3 data points: (1, 2), (2, 4), (3, 5), fit a line y = ax + b using least squares. Calculate the optimal values of a and b.

Hints:
  • Set up the sums: Σx, Σy, Σxy, Σx²
  • Use the formulas: a = (nΣxy - ΣxΣy)/(nΣx² - (Σx)²)
  • Then: b = (Σy - aΣx)/n