DUE IN 6 HOURS!!!! Linear algebra, matlab knowledge required, handshake required
ENGR 231
Linear Engineering Systems
Lab 8 - Curve Fitting via Least Squares in MATLAB
Goals:
1. Introduce the concept of a least squares regression in MATLAB.
2. Apply least squares for linear regression against a data set.
3. Apply least squares for polynomial curve fitting against a data set.
Introduction
A common task in science and engineering is to model and analyze relationships existing in the natural world. As an example, consider the relationship between running speed and an individual’s heart rate. If we could quantize this phenomenon within the context of a mathematical model, then we could stand to make more detailed conclusions of the true relationship that exists.
In the simplest terms, we can cast this problem as modeling via some mathematical equation having a standard form (i.e. linear, exponential, polynomial, logarithmic etc.). Once we have decided upon the standard form of the model, we can then collect data and come up with an estimation of the parameters for the model we chose. Finally, we can see how closely the data points predicted by our model lines up with the actual data points found.
To do this parameter estimation, we will use least squares estimation . This topic will be covered in more detail in later lectures. Here we introduce the minimum needed for implementation.
Derivation of Least Squares Estimation: Linear Model
The simplest model between an independent variable x and a dependent variable y, is a straight line. Every linear function is uniquely specified by just two parameters, its slope and the intercept or offset along the dependent axis.
y
rise
run
x
Parameters for a Linear Model
Any two distinct points, uniquely determine a linear function, as long as they have different
x-values. Below, we derive the equation for the line through two distinct points, in a way that will hopefully elucidate the least square calculations to appear a bit later.
The figure shows graphically the unique linear function through two given points and.
x
y
Two Points Determine a Line
Given two points, how can we find the line that goes through both of them? Well, the line must have the form:
Since both points lie on this line, we have two equations for the two unknown parameters and .
Point 1:
Point 2:
Now define the parameter vector and the observation vector y.
and introduce the design matrix:
Notice the design matrix only depends on the x-coordinates of the points, which form its second column. The y-coordinates only appear in the observation vector, and do not appear in D at all.
Using these definitions, we can write both equations for the two points in vector/matrix form:
The determinant of the design matrix D is non-zero, provided the two points have different
x-values.
Recall a vertical line does not define a linear function! (It fails the vertical line test!)
Provided the two points are distinct and not directly above one another, there is always a unique solution. The design matrix has the inverse:
and the unique solution is:
You should recognize this result as slope equals
rise over run.
Thus, the line through these two points has the intercept and slope:
An Alternative Derivation
Here is another derivation of the same problem with two points determining a line. It looks way more complicated, but the advantage is, it can be generalized to any number of points – not just two! Let's define the matrix product:
This matrix is invertible, (unless ), since its determinant is:
Its inverse is:
Now we are ready to resolve the equation:
First multiply both sides by obtaining:
Now multiply by and exchange sides to find:
If you expand out the product on the RHS, you will find (after some cancellations), that this gives the exact same result for the slope and intercept that we found earlier. Further, this new equation is valid no matter how many points we need to fit to our linear model.
An Arbitrary Number of Points
Let us now consider some experimental data for an athlete's heart rate as a function of their running speed. We can write in general for any given running speed, xi , and heart rate, yi :
where 0 and 1 are the parameters corresponding the y-offset and slope of the linear equation respectively. If we write out these equations for N such measurements we have:
Combining these using the same model yields N equations in two unknowns. Writing this in matrix form yields the following:
where D is known as the design matrix, y is known as the observation vector, and is known as the parameter vector. Our goal is to determine the parameter vector, , with as much certainty as possible.
If the design matrix D was invertible, then we would be able to solve for the parameter vector in a relatively straightforward manner. However, since D is a matrix we see immediately by definition that it is not invertible. We will rectify this through the least squares method. The actual derivation is in-depth and will be covered in class later (a good reference is Lay, sections 6.5 and 6.6). The end result is that we can solve the equation y = D β in the following way. First multiply the equation by DT, the transpose of D,
We can show that the matrix DTD is square and invertible.
Therefore, we can now solve for using:
The value of β obtained from this formula produces the least error.
This method is used in the following way:
1. We obtain a large number of (x, y) data points. We either choose or are given an equation we wish to fit the data ,
2. From the data set, create the observation vector y and the design matrix D
3. Use the boxed equation given above to calculate from D and y.
4. Use the β values from step 3, in equation (2c) to compute the predicted values of at the specified x values.
5. Compare the predicted and observed y values, to see how good is formula obtained.
The example code below illustrates an implementation in MATLAB:
Ex 1:
%% Linear Least Square Estimation
% Given the following set of points:
% First row: x values
% Second row: y values (observed)
pts = [-0.04 0.35 0.57 1.23 2.17 2.15 3.21 3.44 3.90 4.52 5.48
4.06 5.78 7.14 8.39 10.3 11.9 13.0 14.4 16.0 17.8 19.1];
% Make the design matrix, D, and observation vector, Y
D = [ones(length(pts),1), pts(1,:)']
Y = pts(2,:)' % The symbol ' transposes the matrix
% Find Beta based on the equations
beta = (D'*D)^-1*(D'*Y)
% Use the matrix equation to get all of the estimated y values
Y_est = D*beta;
%% Plot the points as circles and the fitted line
plot(pts(1,:),pts(2,:),'o'), hold on
plot(pts(1,:),Y_est,'r')
legend('Observations','Estimated Linear Fit')
Figure 1. Example 1 Output graph showing the estimated fit compared to the actual data.
Calculating a Goodness of Fit metric (RMS error)
It important to find simple numerical measure that shows how close is our model to the actual data points given. If we use the estimated parameter vector, EST, we can calculate the estimated observations, y EST, with the following matrix equation:
The vector of error values can now be found from the equation
the differences between the observed and the estimated values. From this we compute
In example 2, we repeat the calculations of example 1 and append the computation of the RMS error. We also illustrate the use of the 'load' command. Rather than defining the x and y values in a statement, we load a variable 'pts' from a file[footnoteRef:1]†. [1: † The data used resides in file 'pts_ex.mat'. The command 'load pts_ex' reads this file and creates variables that were saved in this file. In the current example there is only one variable whose name is pts. The values in this are identical to the ones in Ex. 1. ]
Ex 2:
% Read the data file pts_ex.mat
% First row: x values
% Second row: y values (observed)
load pts_ex
N = length(pts);
% Make the design matrix, D, and observation vector, Y
D = [ones(N,1), pts(1,:)']
Y = pts(2,:)' % The symbol ' transposes the matrix
% This makes it a column vector
% Find Beta_est based on the equations
% Use the matrix equation to get all of the estimated y values
beta_est = (D'*D)^-1*(D'*Y)
Y_est = D*beta_est;
%% Plot the points as circles and the fitted line
plot(pts(1,:),pts(2,:),'o'), hold on
plot(pts(1,:),Y_est,'r')
legend('Observations','Estimated Linear Fit')
%% Calculate the RMS Error
% Notice that both Y and Y_est are column vectors.
err = Y-Y_est;
RMSE = (err'*err/N)^0.5
title(['RMS error = ', num2str(RMSE)])
Least Squares with a Second Degree Polynomial
Following the exact same methodology presented in the previous discussion, one can also perform curve fitting using a second order polynomial. The general equation for a second order polynomial is:
Following the same method, we end up with the matrix form as:
Though matrix D and vector are different from the equations for linear regression, it turns out that the matrix equations for finding the least squares curve fit are identical to those shown in the linear case. As before, the equation is
with X , Y , and as defined above. Again, once is known, YEST can be found via
Clearly the same process can be used for higher order curve fits.
Appendix – Squaring a set of values
Consider the following set of data in MATLAB: a = [3 4 5 7]. Say we wanted to find the values given in b squared. If we intuitively tried the command a^2, MATLAB would produce the following error:
??? Error using ==> mpower
Inputs must be a scalar and a square matrix.
This is because MATLAB thinks we are trying to do the matrix multiplication a*a. This obviously can’t work, let alone is it what we are actually trying to do. To rectify this, we must use the dot operator . The command becomes a.^2, and the correct result of [9 16 25 49] is produced.
8
Copyright 2016, Drexel University
�
yi = β0 + β1xi
y
i
=b
0
+b
1
x
i
�
y1 = β0 + β1x1 y2 = β0 + β1x2
yN = β0 + β1xN
y
1
=b
0
+b
1
x
1
y
2
=b
0
+b
1
x
2
y
N
=b
0
+b
1
x
N
y1 y2 yN
⎡
⎣
⎢ ⎢ ⎢ ⎢ ⎢
⎤
⎦
⎥ ⎥ ⎥ ⎥ ⎥
=
1 x1 1 x2 1 xN
⎡
⎣
⎢ ⎢ ⎢ ⎢ ⎢
⎤
⎦
⎥ ⎥ ⎥ ⎥ ⎥
β0 β1
⎡
⎣ ⎢ ⎢
⎤
⎦ ⎥ ⎥
y
1
y
2
y
N
é
ë
ê
ê
ê
ê
ê
ù
û
ú
ú
ú
ú
ú
=
1x
1
1x
2
1x
N
é
ë
ê
ê
ê
ê
ê
ù
û
ú
ú
ú
ú
ú
b
0
b
1
é
ë
ê
ê
ù
û
ú
ú
y = Dβ
y=Db
D T y = DT Dβ
D
T
y=D
T
Db
β = DT D( )−1 DT y
b=D
T
D
()
-1
D
T
y
y EST = DβEST
y
EST
=Db
EST
ε = y − y EST
e=y-y
EST
ε RMS =
1 N ε Tε
⎛ ⎝⎜
⎞ ⎠⎟
1/2
e
RMS
=
1
N
e
T
e
æ
è
ç
ö
ø
÷
1/2
yi = β0 + β1xi + β2 xi 2
y
i
=b
0
+b
1
x
i
+b
2
x
i
2
y1 y2 yN
⎡
⎣
⎢ ⎢ ⎢ ⎢ ⎢
⎤
⎦
⎥ ⎥ ⎥ ⎥ ⎥
=
1 x1 x1 2
1 x2 x2 2
1 xN xN
2
⎡
⎣
⎢ ⎢ ⎢ ⎢ ⎢ ⎢
⎤
⎦
⎥ ⎥ ⎥ ⎥ ⎥ ⎥
β0 β1 β2
⎡
⎣
⎢ ⎢ ⎢ ⎢
⎤
⎦
⎥ ⎥ ⎥ ⎥
y
1
y
2
y
N
é
ë
ê
ê
ê
ê
ê
ù
û
ú
ú
ú
ú
ú
=
1x
1
x
1
2
1x
2
x
2
2
1x
N
x
N
2
é
ë
ê
ê
ê
ê
ê
ê
ù
û
ú
ú
ú
ú
ú
ú
b
0
b
1
b
2
é
ë
ê
ê
ê
ê
ù
û
ú
ú
ú
ú
y = Dβ
y=Db
β = DT D( )−1 DT y
b=D
T
D
()
-1
D
T
y
y EST = DβEST
y
EST
=Db
EST