With an understanding of the method of least squares and QR decomposition, weâ€™re now ready to look at one of its most practical applications: least squares fitting. In this tutorial, weâ€™ll explore straight-line fitting and polynomial least squares fitting, both by hand and with Python. But before we get to the problems, we need a little background and some more theory.

##
What Is Least Squares Fitting?

In **least squares fitting**, we have some function that takes -vectors as its inputs and maps them to real numbers. We donâ€™t really know anything about the function itself and what it does under the hood. Itâ€™s your classic black box: You feed some vector to the function, and it spits out a in response:

Our goal in least squares fitting is to try to model as closely as possible, based on the input-output data pairs that weâ€™re given. Typically, we use the following notation for our data, with denoting the -th data pair:

Here, is the number of data points (i.e., the size of our data set), while is the size of each input vector, . Keep that in mind because these two are not necessarily the same.

Note: We use superscripts in parentheses to denote data pairs. Note that subscripts are usually reserved for the elements of a vector. So in this case, the first element of the second input vector would be represented as .

The typical example used in an introductory machine learning class is the house price index data set. You have data pairs of the form . You feed your feature vector to your function, and it produces some corresponding scalar value, , in response. In this case, may be a set of measurements for the home: the number of bedrooms, the number of bathrooms, its age, and so on. The corresponding output is , which denotes the price of the homeâ€”the *real* price, not a prediction.

Now, as I mentioned earlier, we rarely ever know what is. So what weâ€™ll do is model the relationship between each and as closely as we can. We approximate their relationship with a **model function** that we call :

Note that and are simply placeholders. Since weâ€™re really given data pointsâ€” and â€”we should write out the expanded form of the above by plugging in each data pair. Thatâ€™ll give us a clearer picture of whatâ€™s going on:

This is starting to look more like a system of equations. But weâ€™re not quite there yet. How exactly do we pick ?

Summary: Our goal in data fitting is to model the relationship between the inputs, , and the outputs, , as closely as possible using a model function, . Because remember, we donâ€™t know thetruerelationship, .

##
Picking a Model Function for Data Fitting

Below is the general form of the model function used in least squares fitting:

If this looks confusing, donâ€™t worryâ€”itâ€™s actually very simple.

First, notice that the model is a function like any other. In this case, though, itâ€™s composed of parameters, , as well as functions, . In data fitting, these functions are called **basis functions**.

Okay, so how can we make this least squares model function more concrete?

Well, the good news is that we get to pick the basis functions based on how we think the real function, , behaves. As weâ€™ll see shortly, if appears to be linear in behavior, then we may decide to pick our basis functions such that ends up resembling a straight line. On the other hand, if appears to be quadratic, then we may pick our basis functions such that ends up being some sort of a polynomial.

Takeaway: We pick the basis functions based on how we think behaves. This is a key step in engineering a model function. In picking the basis functions, we also decide how many of them weâ€™ll need. This is .

*We* pick the basis functions. The valuesâ€”the **model parameters**â€”are what we need to solve for.

###
Data Fitting: The System of Equations

Letâ€™s plug this general form of into the earlier set of equations that we saw:

Now thatâ€™s more like itâ€”this is a linear system of equations! Letâ€™s represent it in matrix form:

Notice that our matrix has dimensions . In practice, is often much, much larger than . Sound familiar? All this really means is that we have an overdetermined systemâ€”thereâ€™s no exact solution to . This means that **many data fitting problems are actually least squares problems**â€”we need to find the that gets us as close as possible to .

**To summarize**:

- There exists some unknown relationship, , between and , such that .
- We approximate using .
- We pick the basis functions based on how we think the real function behaves.
- We solve for the parameters of our modelâ€”â€”using the least squares method.

##
General Strategy for Solving Least Squares Problems

Hereâ€™s a simple five-step strategy you can use to solve least squares problems:

- Visualize the problem. For example, you may be given a set of data points that you can plot.
- Pick an appropriate model. Based on what we learned, this involves choosing the basis functions and .
- Identify the equations involved. Write them out explicitly based on your input and output pairs.
- Solve the overdetermined system using the least squares method.
- (Optional) Visualize the solution. This is a useful way to sanity check your answer, though itâ€™s not fool-proof.

Note: For all the examples that follow, weâ€™ll let . That is, our input s will just be scalar values. In reality, this changes nothing about the least squares method.

##
Example 1: Least Squares Straight-Line Fit

Suppose weâ€™re given these data points for a least squares line fitting problem:

Weâ€™re asked to model the relationship between and . Letâ€™s take it step by step.

###
Step 1: Visualize the Problem

First, weâ€™ll plot the points:

We note that the points, while scattered, appear to have a linear pattern. Clearly, itâ€™s not possible to fit an actual straight line to the points, so weâ€™ll do our best to get as close as possibleâ€”using least squares, of course.

###
Step 2: Pick an Appropriate Model

We know appears linear, like a equation. We want our model function to look something like this:

Note: Alternatively, you could just as well pick . It wonâ€™t change the solution.

So, we revisit our general model:

And we pick our basis functions, as promised, to give a linear shape. We pick to be , such that we have:

Next, we define our basis functions:

What does this do for us? Letâ€™s plug them into the general formula:

That gives us precisely the function we wanted.

Note: You donâ€™t have to be this explicit about how you select your basis functions. However, I recommend doing so because it allows you to verify that your reasoning is sound.

###
Step 3: Identify the Equations Involved

Here are all three equations for our problem:

Letâ€™s plug in our points:

And, in matrix form, this looks like the following:

###
Step 4: Solve the Overdetermined System Using Least Squares

Three equations and two unknownsâ€”this is an overdetermined system. How do we solve this system? Well, as we know, thereâ€™s no exact solution. But we can get the least squares solution by solving for in this equation:

Of course, we shouldnâ€™t solve this directly without first using QR decomposition. If you perform the necessary steps for QR decomposition, youâ€™ll get that:

You can verify this by performing matrix multiplication to see that you do in fact get back. It looks pretty nasty with all those square root terms, but they actually cancel out quite nicely as weâ€™ll see here in a second.

Letâ€™s plug into the least squares equation. Doing so yields the following simplified form:

Letâ€™s plug in the actual matrices:

And letâ€™s simplify the right-hand side of the equation:

This is a square system! Even better, itâ€™s an upper-triangular systemâ€”this means we can solve for really easily and then plug it back into the first equation to solve for (recall that this strategy is known as **back-substitution**). First, letâ€™s explicitly write out the two equations:

Solving the second equation, we get that .

Plug that into the first equation:

Solving yields . Excellent!

###
Step 5: Visualize the Solution

We have the following solution:

Remember our model?

Plugging those in yields the following straight-line equation:

Letâ€™s plot the best-fit line along with the points:

Awesome! This is the best-line fit for the data points we were given.

As you add more points, data fitting (particularly the QR factorization portion) becomes more difficult to do by hand. Fortunately, you can use languages like MATLAB or Python to solve these problems. But now, when you do rely on computers, youâ€™ll at least know what theyâ€™re doing behind the scenes.

##
Example 2: Least Squares Polynomial Fitting (with Python!)

Letâ€™s not stop there! Suppose instead that we are given these five data points:

Letâ€™s repeat the process.

###
Step 1: Visualize the Problem

Hereâ€™s a graph of our points:

To me, these points seems to take on the shape of a parabola. Based on that observation, Iâ€™m going to perform a least squares polynomial fit using a polynomial of degree two (a quadratic, basically).

###
Step 2: Pick an Appropriate Model

Since weâ€™re modeling a quadratic equation (degree-two polynomial), this is the general form of the model function weâ€™ll aim for:

To get that, weâ€™ll start with the original form again:

And weâ€™ll pick with:

There we go! Itâ€™s that simple.

Note: Again, you could reverse the order of the polynomial to be . This would change nothing except the order of the elements in your resulting matrix.

###
Step 3: Identify the Equations Involved

Here are all five equations for our polynomial fitting problem:

Letâ€™s plug in the data we were given:

Iâ€™ll simplify things a bit and represent this as a matrix equation:

###
Step 4: Solve the Overdetermined System Using Least Squares

Straight-line fitting is pretty simple by hand, but polynomial least squares fitting is where it gets kind of difficult. So Iâ€™m going to â€ścheatâ€ť and use Python! You can use MATLAB instead if youâ€™d prefer; the language doesnâ€™t really matter once you know the theory.

Hereâ€™s a script that uses QR factorization explicitly:

```
import numpy as np
from numpy import linalg as LA
# Our data
A = np.array([[1, -4, 16], [1, 0, 0], [1, 1, 1], [1, 2, 4], [1, -6, 36]])
y = np.array([[5], [1], [3], [9], [10]])
# QR factorize A
Q, R = LA.qr(A)
# R (theta) = Q^T (y)
QT = np.transpose(Q)
theta = LA.solve(R, QT.dot(y))
print(theta)
```

However, this is really equivalent to the following code, which simply uses the `LA.lstsq`

function:

```
import numpy as np
from numpy import linalg as LA
# Our data
A = np.array([[1, -4, 16], [1, 0, 0], [1, 1, 1], [1, 2, 4], [1, -6, 36]])
y = np.array([[5], [1], [3], [9], [10]])
theta = LA.lstsq(A, y)
print(theta)
```

Regardless of which version we run, weâ€™ll get the same answer for the vector:

Plugging this into our model, we arrive at the following polynomial function:

###
Step 5: Visualize the Solution

And hereâ€™s the resulting graph with our polynomial fit to the data:

Looks like a pretty good fit to me!

## Conclusion

That about does it for this series on the least squares method! I hope you found this helpful.

## đź’¬ Comments

Post comment