Here we’ll see an example of fitting a straight line in a set of samples using the least-squares method. Let’s suppose we have the following data:
(1, 3), (2, 4), (3, 5), (4, 6), (5, 8)
In the graph below, we can see the data in a scatter plot:
-
We want to fit the linear function y = a x + b. If we replace our data in the equations we derived in the previous section we have the following results:
26 = 5b + 15a
90 = 15b + 55a
We solve the above system of two equations and two variables, and we find that a=1.2 and b=1.6. So, we have the function y = 1.2x + 1.6:
In the graph above, the red line corresponds to the fitted curve on the input data (blue dots). As we expected, the fitted line is the one that has the minimum distance from the input points.