v9.1.1
Menu

Line Fitting

mediumFREELeast SquaresOptimizationCV: Model Fitting and Optimization

Implement a line fitting model using the least squares method to find the best-fit line y=mx+by = mx + b for a given set of points. This task involves minimizing the sum of squared residuals between observed points and predicted values.

The least squares approach is a fundamental concept in model fitting and optimization, aiming to find the optimal parameters that result in the smallest possible sum of squared errors. In this case, the goal is to determine the slope mm and intercept bb of the line that minimizes the sum of squared residuals E=∑i(yi−(mxi+b))2E = \sum_i (y_i - (mx_i + b))^2.

To achieve this, the process involves the following steps:

  1. Calculate the necessary summations of xx, yy, x2x^2, and xyxy for the given points.
  2. Use these summations to derive the parameters mm and bb. The key to this process lies in the mathematical formulation of the normal equations, which provide a way to solve for mm and bb.
E=∑i(yi−(mxi+b))2E = \sum_i (y_i - (mx_i + b))^2

This technique is widely used in computer vision for tasks such as image processing and object detection.

Example

Input
fit_line([(0,0), (1,1), (2,2)])
Output
[1.0, 0.0]
Reasoning
  • points is a list of n=3n = 3 coordinate pairs (xi,yi)(x_i, y_i): (0,0)(0,0), (1,1)(1,1), (2,2)(2,2). The output is the pair [m,b][m, b], slope first, then intercept.
  • The four sums the description mentions: ∑xi=0+1+2=3\sum x_i = 0+1+2 = 3, ∑yi=3\sum y_i = 3, ∑xi2=0+1+4=5\sum x_i^2 = 0+1+4 = 5, ∑xiyi=0+1+4=5\sum x_i y_i = 0+1+4 = 5.
  • Setting the derivatives of EE with respect to mm and bb to zero gives the normal equations ∑xiyi=m∑xi2+b∑xi\sum x_i y_i = m\sum x_i^2 + b\sum x_i and ∑yi=m∑xi+nb\sum y_i = m\sum x_i + nb. With these numbers: 5=5m+3b5 = 5m + 3b and 3=3m+3b3 = 3m + 3b.
  • Subtracting the second from the first leaves 2=2m2 = 2m, so m=1m = 1; then 3=3+3b3 = 3 + 3b gives b=0b = 0. Rounded to 4 decimal places that is [1.0, 0.0].
  • Notice every residual yi−(mxi+b)y_i - (mx_i + b) is 00 here, so E=0E = 0: the points lie exactly on y=xy = x. Noisy points give the line of smallest EE, with E>0E > 0.

Constraints

  • Return [m, b] rounded to 4 decimal places

Learn this in

More from CV: Model Fitting and Optimization

solution.py

Test results

Sign in to run your code against the test cases.