Coding Your Own Linear Regression Model#
One task that you will almost certainly be required to do other data science courses (especially if you are a MIDS student) is to write up some of your statistical / machine learning models from scratch. This can be a very valuable exercise, as it ensures that you understand what is actually going on behind the scenes of the models you use ever day, and that you don’t just think of them as “black boxes”.
To get a little practice doing this, today you will be coding up your own linear regression model!
(If you are using this site but aren’t actually in this class, you are welcome to skip this exercise if you’d like – this is more about practicing Python in anticipation of the requirements of other courses than developing your applied data science skills.)
There are, broadly speaking, two approaches you can take to coding up your own model:
you can write the model by defining a new function, or
you can write the model by defining a new class with associated methods (making a model that works the way a model works in
scikit-learn).
Whether you do 1 or 2 is very much a matter of choice and style. Approach one, for example, is more consistent with what is called a functional style of programming, while approach two is more consistent with an object-oriented style of programming. Python can readily support both approaches, so either would work fine.
In these exercises, however, I will ask you to use approach number 2 as this tends to be the more difficult approach, and so practicing approach 2 will be extra useful in preparing you for other classes (HA! Pun…). In particular, our goal is to implement a linear regression model that has the same “initialize-fit-predict-score” API (application programming interface – a fancy name for the methods a class supports) as scikit-learn models. That means your model should be able to do all of the following:
Initialize a new model.
Fit a linear model when given a numpy vector (
y) and a numpy matrix (X) with the syntaxmy_model.fit(X, y).Predict values when given a new
numpymatrix (X_test) with the syntaxmy_model.predict(X_test).Return the model coefficients through the property
my_model.coefficients(not quite what is used insklearn, but let’s use that interface).
Also, bear in mind that throughout these exercises, we’ll be working in numpy instead of pandas, just as we do in scikit-learn. So assume that before using your model, your user has already converted their data from pandas into numpy arrays.
Setup#
Unlike most of the exercises in this part of the course, you won’t be doing this one in a Jupyter notebook. A model like this is something you’d want to be able to import into lots of different projects, so you’ll write it the way the models you import are written: in a .py file.
Open a new file in VS Code and save it as codeyourown.py (all lower case). Then paste the following scaffolding into it:
import numpy as np
# Define your MyLinearModel class here!
# Code in this block only runs when you run this file directly.
# It does not run when someone (like the autograder!) imports
# MyLinearModel from this file, so this is where the code you
# write to test your model should go.
if __name__ == "__main__":
pass
You will see that we have started you off with two things:
A spot for your
MyLinearModelclass.An
if __name__ == "__main__":block. Several of the questions below ask you to create some toy data and test your model. Put that code in this block (replacingpass), so that it runs when you run the file by clicking the “Run arrow” in the upper right, but not when your class is imported somewhere else.
Exercise 1#
Define a new Class called MyLinearModel with methods for __init__, fit, predict, and an attribute for coefficients. For now, we don’t need any initialization arguments, just an __init__ function.
As you get your code outline going, start by just having each method pass:
def my_method(self):
pass
This will allow your methods to run without errors (they just don’t do anything). Then we can double back to each method to get them working one by one.
Exercise 2#
Now define your fit method. This is the method that should actually run your linear regression. In case you’ve forgotten your linear algebra, remember that for linear regressions, \(\beta = (X'X)^{-1}X'Y\), a fact you can see explained in detail on page four here.
Note that once you have written the code to do a linear regression, you’ll need to put your outputs (your coefficents) somewhere. Store them in an attribute of your class called coefficients, as a one-dimensional numpy array.
(As a reminder: the normal multiply operator (*) in numpy implies scalar multiplication. Use @ for matrix multiplication).
HINT: Remember that linear regressions usually include a constant term. As in most packages, you should assume that users want this included, even if there isn’t a vector of 1s in their X. So before you fit the model, add a vector of 1s to X as its first column. That way the first entry in coefficients will be the constant term, and the rest will be in the same order as the columns of the X the user gave you.
Exercise 3#
When we are writing code to fit a statistical model, it usually makes sense to start by constructing data that has properties you understand. This give you way to validate your model as you go along.
In a sense, this is an inversion of how we usually approach data science — usually, we have data, and we use a model we understand to try and understand the underlying structure of the data. But here, we want to construct data whose structure we understand so that we know what our model should generate.
To illustrate, here’s an example of a toy dataset — an X matrix and a y vector. The values in X are random, but I’ve carefully specified how y should be created. In particular, I’ve said that y should be the result of multiplying the values of X by a specified set of coefficients plus a little mean-zero noise.
Because this is precisely how a linear regression tries to decompose relationships in data, a working model should recover the coefficients you started with (or something very close to those coefficients, since you added a little random noise).
import numpy as np
import numpy.random as npr
npr.seed(42)
n = 1_000
# Three columns — one constant and two random variables.
sample_X = np.column_stack([np.ones(n), npr.normal(size=(n, 2))])
# The coefficients I'm using
sample_betas = np.array([2.0, -1.5, 7])
# generate my y
sample_y = sample_X @ sample_betas + npr.normal(scale=1.0, size=n)
Exercise 4#
Now test whether your fit method generates the correct coefficients.
Exercise 5#
Now let’s make the statisticians proud, and in addition to storing the coefficients, let’s store the standard errors for our estimated coefficients as another attribute called standard_errors (in the same order as your coefficients). Recall that the simplest method of calculating the variance covariance matrix for \(\beta\) is using the formula \(\sigma^2 (X'X)^{-1}\), where \(\sigma^2\) is the variance of the error terms of your regression.
The standard errors for your coefficient estimates will be the square root of the diagonal values of that matrix. See page six here for a full derivation.
To estimate \(\sigma^2\), divide the sum of your squared residuals by \(n - k\), where \(n\) is the number of observations and \(k\) is the number of coefficients you estimated (including the constant term).
Exercise 6#
Now let’s also add an R-squared attribute to the model called r_squared.
Exercise 7#
Now we’ll go ahead and cheat a little. Use statsmodels to fit your model with your toy data to ensure your standard errors and r-squared are correct!
Exercise 8#
Now implement predict! It should return a one-dimensional numpy array with one predicted value for each row of X_test. Then test it against your original X data – do you get back something very close to your true y?
Exercise 9#
Finally, create the option of fitting the model with or without a constant term. In other words, create an option so that, if the user passes a numpy array without a constant term, your code will add a vector of 1s before fitting the model. As in scikit-learn, make this an option you set during initialization.
Call the argument add_constant, and have it default to True. So MyLinearModel() and MyLinearModel(add_constant=True) should both add a vector of 1s (as you’ve been doing all along), while MyLinearModel(add_constant=False) should use X exactly as the user provided it — both when fitting and when predicting!
Submitting on Gradescope#
Once you feel your code is operating correctly, be sure your file is named codeyourown.py and upload it to Gradescope.
The autograder will import your MyLinearModel class, fit it to several datasets you haven’t seen, and compare what it gets to our own implementation. For that to work, your class needs to follow the interface laid out above:
The class is named
MyLinearModel, and can be created withMyLinearModel()or withMyLinearModel(add_constant=False).my_model.fit(X, y)takes a two-dimensional numpy arrayX(one row per observation, one column per variable) and a one-dimensional numpy arrayy.After fitting,
my_model.coefficientsandmy_model.standard_errorsare one-dimensional numpy arrays (with the constant term first, if there is one), andmy_model.r_squaredis a number.my_model.predict(X_test)returns a one-dimensional numpy array of predicted values.
And as always, be sure your code is formatted with black before you submit.