'Get the coefficients of my sklearn polynomial regression model in Python

I want to get the coefficients of my sklearn polynomial regression model in Python so I can write the equation elsewhere.. i.e. ax1^2 + ax + bx2^2 + bx2 + c

I've looked at the answers elsewhere but can't seem to get the solution, unless I just don't know what I am looking at.

from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree = 2)
X_poly = poly_reg.fit_transform(X_train)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(X_poly,y_train)

lin_reg_2.coef_


Solution 1:[1]

Support Vector Regression:

from sklearn.svm import SVR
import numpy as np
n_samples, n_features = 10, 5
np.random.seed(0)
y = np.random.randn(n_samples)
X = np.random.randn(n_samples, n_features)
clf = SVR(kernel="poly",degree=3,gamma="scale",C=0.8)
clf.fit(X, y) 
clf.predict(X)

Definition of class sklearn.svm.SVR?

class sklearn.svm.SVR(kernel=’rbf’, degree=3, gamma=’auto_deprecated’, coef0=0.0, tol=0.001, C=1.0, epsilon=0.1, shrinking=True, cache_size=200, verbose=False, max_iter=-1)

Solution 2:[2]

This snippet should work, it was taken from my own script :

from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree=2)
poly_x_inliers = poly_reg.fit_transform(x_inliers)

regressor = LinearRegression()
regressor.fit(poly_x_inliers, y_inliers)

reg_label = "Inliers coef:%s - b:%0.2f" % \
            (np.array2string(regressor.coef_,
                             formatter={'float_kind': lambda fk: "%.3f" % fk}),
            regressor.intercept_)
print(reg_label)

You should check on : https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html

Solution 3:[3]

You were so close. The problem is how you wrote the model. For it to work you'll have to write it as:

from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree = 2)
X_poly = poly_reg.fit_transform(X_Train)
lin_reg_2=LinearRegression().fit(X_poly, y_Train)
pred = lin_reg_2.predict(X_poly_test) #this line is not necessary. It's just a predict for test data

lin_reg_2.coef_

Also make sure X_train and y_train are arrays with the right shapes.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 myhaspldeep
Solution 2 Yassine
Solution 3