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.sstatic.net/bqavG.jpg

1

1 Answer 1

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))
Sign up to request clarification or add additional context in comments.

6 Comments

I have 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) ..
The coeffictients is [c,b,a], so it's working well enough since 1e-15 ~ 0. Look at how X_poly looks when printed
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
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.
i can do the prediction and display the coefficient at the same time ? With this code i can't display coefficient
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.