0

I have some code that generates a polynomial regression model based on some experimental data in Python3.

I need to find the equation of this model so I can use it a different program for predictions based on the model. Do any of you know how to get the polynomial equation of a model generated by the sklearn.preprocessing.PolynomialFeatures module?

Here is the code:

import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures


def viz_linear():
    plt.scatter(X, y, color='red')
    plt.plot(X, lin_reg.predict(X), color='blue')
    plt.show()
    return viz_linear()


def viz_polynomial():
    plt.scatter(X, y, color='red')
    plt.plot(X, pol_reg.predict(poly_reg.fit_transform(X)), color='blue')
    plt.show()
    return viz_polynomial()


if __name__ == '__main__':
    # Experimental data
    y = [0.0, 0.1, 0.2, 0.29, 0.39, 0.5, 0.62, 0.72, 0.82, 0.88, 1.05, 1.31, 1.61, 2.1, 2.48, 2.58, 2.88, 3.32, 3.66, 4.28, 4.54, 4.95, 5.09, 5.67, 7.09, 8.48, 9.03, 9.22, 10.0]
    X = [[0.0], [138.0], [259.0], [360.0], [439.0], [515.0], [558.0], [583.0], [606.0], [617.0], [648.0], [684.0], [715.0], [754.0], [776.0], [781.0], [795.0], [812.0], [824.0], [841.0], [847.0], [855.0], [858.0], [868.0], [888.0], [902.0], [906.0], [908.0], [914.0]]

    lin_reg = LinearRegression()
    lin_reg.fit(X, y)
    
    poly_reg = PolynomialFeatures(degree=10)
    X_poly = poly_reg.fit_transform(X)
    pol_reg = LinearRegression()
    pol_reg.fit(X_poly, y)
    
    viz_polynomial()

    print(pol_reg.predict(poly_reg.fit_transform([[914]])))
Zach M.
  • 31
  • 4

1 Answers1

1

You need to create a polynomial with the degree you want then pass it to the regressor getting coefficients back would be straightforward.

from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
regressor = LinearRegression()
y = [1, 3, 7, 13, 21, 31]
X = [[0], [1], [2], [3], [4], [5]]

poly = PolynomialFeatures(2)
new_X = poly.fit_transform(X)
regressor = LinearRegression()
regressor.fit(new_X, y)
print('Coefs for X0, X1, X2', regressor.coef_)
print('Intercept', regressor.intercept_)

output:

Coefs for X0, X1, X2 [0. 1. 1.]
Intercept 1.0000000000000018
meti
  • 1,921
  • 1
  • 8
  • 15