Mth3007 Lecture 1

How Can We Derive the Formula for Least Squares Regression?

How Do We Program Least Squares Regression?

First, we’ve gotta handle the dependencies using a package manager - here we use micropip.

Python
Output

Then, to solve some of the earlier warm-up questions we devise a function to sum the squares of a given list of floats - a useful helper function later, too.

Python
Output

The main linear regression stuff is then done here, implementing the logic derived during the lecture - formulae repeated in the notes of the function.

Python
Output

To test our linear regression stuff, we can plot all the pairs of coordinates and the line of best fit we calculated (using the slope and intercept returned from the function). This was outside of the scope of the lecture, but I had some extra time.

Python
Output

Now that all of our functions are set up, time to input the data we were given in the lecture!

Python
Output

Let’s just double check the actual values first, so we can cross-reference against manual working, or just a calculator.

Python
Output

Finally, the plot…

Python
Output

Looks good!