Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Scikit-learn LinearRegression vs Numpy Polyfit
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
poly1d = PolynomialFeatures(degree=1)
X1 = poly1d.fit_transform(np.array(x).reshape(-1, 1))
linear_reg_1d = LinearRegression()
linear_reg_1d.fit(X1, y)
print(linear_reg_1d.coef_[1:])
print(linear_reg_1d.intercept_)
print(np.linalg.norm(y - linear_reg_1d.predict(X1)) ** 2)
[-0.1605313]
125.77023172322043
92743.77449407903
poly2d = PolynomialFeatures(degree=2)
X2 = poly2d.fit_transform(np.array(x).reshape(-1, 1))
linear_reg_2d = LinearRegression()
linear_reg_2d.fit(X2, y)
print(linear_reg_2d.coef_[1:])
print(linear_reg_2d.intercept_)
print(np.linalg.norm(y - linear_reg_2d.predict(X2)) ** 2)
[-0.40780952 0.00079718]
139.78768437342626
92025.81182290474
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment