Machine Learning Series: Polynomial Regression

 

Hello Reader, 

In a previous post I described the linear regression, the algorithm works well when the features are linearly correlated but what if the data cannot be described with a straight line? Surprisingly it is possible to use Linear Regression also in these cases, simply adding new features as power of existing features and run the linear regression on this new set. This technique is called Polynomial Regression.

 

Let's get create some synthetic data using SIN and some added noise


Now I proceed to split the dataset in train and test sets



And let's train linear regression



Let's evaluate the model using MSE



Here we can see how linear regression is trying to do its best to predict the test instances


We can definitely do better, let's calculate new polynomial features using Sklearn library



As you can see I have configured the PolynomialFeatures library to generate the 8-degree polynomial features it means that the algorithm is generating all combination of the original features with a degree less than equal to eight (for example if we have two feature a, b and we specify a degree = 3 the function is going to create a2, b2, ab, a2b, ab2, a3, b3, ab).

Note that this technique generates a large number of new features to be precise if we have n feature and a degree d



Let's train Linear Regression on this new train set and evaluate the MSE



The prediction on the test set improved by a remarkable 47%, as we can clearly see below


The technique worked extremely well in this case, but we need to be careful because increasing the polynomial degree increase the risk of overfitting the training set. As showed below



In this graph, you can see that for this specific dataset, the MSE of train and test is similar until a degree eleven after that the model performance on the test set starts degrading. The difference is since the algorithm is overfitting to the training set and it is not able to generalize to new unseen instances of the data.

 

The issue is also called model variance,  in the next post, I am going to present the various issue we can face when we train a model and how we can try to solve it.



Recommended resources 

Notebook:

Course:  

Books:



Comments