使用sklearn的多项式回归

时间:2018-08-06 11:21:16

标签: python scikit-learn

这是我的代码:

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)

我有这些错误:

https://imgur.com/a/GkYFQlc

请帮忙吗? 亲切的问候。

1 个答案:

答案 0 :(得分:1)

PolynomialFeatures没有名为coef_的变量。 PolynomialFeatures不执行多项式拟合,它只是将您的初始变量转换为更高阶。实际进行回归分析的完整代码为:

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))