1

Here is my code:

import numpy as np
from sklearn.preprocessing import PolynomialFeatures

X=np.array([[1, 2, 4]]).T
print(X)
y=np.array([1, 4, 16])
print(y)
model = PolynomialFeatures(degree=2)
model.fit(X,y)
print('Coefficients: \n', model.coef_)
print('Others: \n', model.intercept_)

#X_predict=np.array([[3]])
#model.predict(X_predict)

I have these errors:

https://i.stack.imgur.com/bqavG.jpg

iacob
  • 20,084
  • 6
  • 92
  • 119
user1543915
  • 1,025
  • 1
  • 10
  • 16
  • Does this answer your question? [polynomial regression using python](https://stackoverflow.com/questions/31406975/polynomial-regression-using-python) – iacob Mar 28 '21 at 16:20

1 Answers1

2

PolynomialFeatures doesn't have a variable named coef_. PolynomialFeatures doesn't do a polynomial fit, it just transforms your initial variables to higher order. The full code for actually doing the regression would be:

import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline

X=np.array([[1, 2, 4]]).T
print(X)
y=np.array([1, 4, 16])
print(y)
model = make_pipeline(PolynomialFeatures(degree=2), LinearRegression(fit_intercept = False))
model.fit(X,y)
X_predict = np.array([[3]])
print(model.named_steps.linearregression.coef_)
print(model.predict(X_predict))
user2653663
  • 2,818
  • 1
  • 18
  • 22
  • 1
    I have https://imgur.com/a/9FosRVG Coefficients: [ 3.55300751e-15 -5.10702591e-15 1.00000000e+00] > but the model is y=a * x * x+b * x+c (a=1, b=0,c=0) .. – user1543915 Aug 06 '18 at 14:55
  • 1
    The coeffictients is [c,b,a], so it's working well enough since 1e-15 ~ 0. Look at how `X_poly` looks when printed – user2653663 Aug 06 '18 at 15:13
  • 1
    ok please can i do a prediction using X_predict=np.array([[3]]) model.predict(X_predict) ? which give me y=a*3*3+b*3+c=9 – user1543915 Aug 06 '18 at 15:19
  • 1
    I updated the answer to use scikit-learn pipelines. When you construct the pipeline, you say that the model should first transform the data using PolynomialFeatures, then it should do regression with LinearRegression. – user2653663 Aug 06 '18 at 15:32
  • 1
    i can do the prediction and display the coefficient at the same time ? With this code i can't display coefficient – user1543915 Aug 06 '18 at 15:50
  • That was a bit more convoluted than I though, but look at the updated code, it should do it now. – user2653663 Aug 06 '18 at 16:30