DEV Community

Cover image for Polynomial Regression with Python
codesharedot
codesharedot

Posted on

Polynomial Regression with Python

Regression is a way to see trends, and optionally make predictions. If you have X data points, you want to find line Y that closely follows the pattern.

Lets collect data from the korean central bank (interest rates). You can fetch those here.

We will use the Python programming language.

Then we use sklearn to load the polynomial. Numpy to process the data. Matplotlib is used to plot the data points and the line.

You can copy the (quick and dirty) code below:

#!/usr/bin/python3
from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_model
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split 
import numpy as np
import matplotlib.pyplot as plt

y = [
    4.75,
    5.00,
    5.25,
    5.00,
    4.75,
    4.50,
    4.00,
    4.25,
    4.00,
    3.75,
    3.50,
    3.25,
    3.50,
    3.75,
    4.00,
    4.25,
    4.50,
    4.75,
    5.00,
    5.00,
    5.25,
    5.00,
    4.25,
    4.00,
    3.00,
    2.50,
    2.00,
    2.25,
    2.50,
    2.75,
    3.00,
    3.25,
    3.00,
    2.75,
    2.50,
    2.25,
    2.00,
    1.75,
    1.50,
    1.25,
    1.50,
    1.75,
    1.50
    ]    

X = np.array(range(0,len(y))).reshape(-1,1)
Y = np.array(y).reshape(-1,1)

print(X)
print(y)
print(len(X[0]))
print(len(y))


from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree=9)
X_poly = poly_reg.fit_transform(X)
pol_reg = LinearRegression()
pol_reg.fit(X_poly, y)

# Visualizing the Polymonial Regression results
def viz_polymonial():
    plt.scatter(X, y, color='red')
    plt.plot(X, pol_reg.predict(poly_reg.fit_transform(X)), color='blue')
    plt.title('Korean Interest Rate')
    plt.xlabel('Quarter')
    plt.ylabel('Interest Rate')
    plt.show()
    return
viz_polymonial()

This will fit the line to the data points. You can choose the number of degrees for the polynomial. You want to prevent over fitting and under fitting.

Alt Text

Related links:

Top comments (0)