v9.1.1
Menu

Weighted Least Squares

hardFREELeast SquaresOptimizationCV: Model Fitting and Optimization

Implement a weighted least squares method to fit a line to a set of points, where each point has a weight indicating its importance. This technique is crucial in model fitting and optimization as it allows for more accurate predictions by giving more influence to certain points.

The concept of weighted least squares is an extension of the ordinary least squares method, which minimizes the sum of the squared errors between observed responses and predicted responses. In weighted least squares, each point is assigned a weight wiw_i, and the goal is to minimize the weighted sum of the squared errors E=∑iwi(yi−(mxi+b))2E = \sum_i w_i(y_i - (mx_i + b))^2.

Here are the steps to achieve this:

  1. Calculate the weighted sum of xx values, yy values, x2x^2 values, and xyxy values.
  2. Use these weighted sums to calculate the slope mm and intercept bb of the line.
E=∑iwi(yi−(mxi+b))2E = \sum_i w_i(y_i - (mx_i + b))^2

This technique is widely used in computer vision applications.

Example

Input
weighted_fit_line([(0,0,1), (1,2,1), (2,2,2)])
Output
[0.9091, 0.3636]
Reasoning
  • Each tuple is a point (xi,yi)(x_i, y_i) plus a weight wiw_i: how much its squared error counts in EE. Here (2,2)(2,2) counts double.
  • The weighted sums from step 1: ∑wi=4\sum w_i = 4, ∑wixi=0+1+4=5\sum w_i x_i = 0 + 1 + 4 = 5, ∑wiyi=0+2+4=6\sum w_i y_i = 0 + 2 + 4 = 6, ∑wixi2=0+1+8=9\sum w_i x_i^2 = 0 + 1 + 8 = 9, ∑wixiyi=0+2+8=10\sum w_i x_i y_i = 0 + 2 + 8 = 10.
  • EE is smallest where its partial derivatives with respect to mm and bb are both zero. With these sums that gives two linear equations: 9m+5b=109m + 5b = 10 and 5m+4b=65m + 4b = 6.
  • Solving the pair: m=1011≈0.9091m = \frac{10}{11} \approx 0.9091, b=411≈0.3636b = \frac{4}{11} \approx 0.3636, so the output is [0.9091, 0.3636] (each rounded to 4 decimal places).
  • Notice that the line passes through the weighted mean point (1.25,1.5)(1.25, 1.5). With equal weights the slope would be 1.01.0; doubling (2,2)(2,2) pulls the right end down toward it.

Constraints

  • points is a list of (x, y, weight) tuples
  • 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.