scikit learn 与 np.polyfit 的多项式回归

XR *_* SC 5 python regression linear-regression scikit-learn

我很惊讶没有人谈论这一点:使用 scikit learn 进行的多项式回归与使用 numpy 进行的 polyfit 的区别。

一、数据:

xdic={'X': {11: 300, 12: 170, 13: 288, 14: 360, 15: 319, 16: 330, 17: 520, 18: 345, 19: 399, 20: 479}}
ydic={'y': {11: 305000, 12: 270000, 13: 360000, 14: 370000, 15: 379000, 16: 405000, 17: 407500, 18: 450000, 19: 450000, 20: 485000}}

X=pd.DataFrame.from_dict(xdic)
y=pd.DataFrame.from_dict(ydic)
import numpy as np
X_seq = np.linspace(X.min(),X.max(),300).reshape(-1,1)
Run Code Online (Sandbox Code Playgroud)

然后我们用 scikit learn 创建模型

from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LinearRegression

degree=9

polyreg=make_pipeline(PolynomialFeatures(degree),
                      LinearRegression())
polyreg.fit(X,y)
Run Code Online (Sandbox Code Playgroud)

然后你可以创建一个情节

plt.figure()
plt.scatter(X,y)
plt.plot(X_seq,polyreg.predict(X_seq),color="black")
plt.xlabel('X')
plt.ylabel('y')
plt.show()
Run Code Online (Sandbox Code Playgroud)

这是情节

在此输入图像描述

对于 numpy,情况就完全不同了。

coefs = np.polyfit(X.values.flatten(), y.values.flatten(), 9)

X_seq = np.linspace(X.min(),X.max(),300)

plt.figure()
plt.plot(X_seq, np.polyval(coefs, X_seq), color="black")
plt.scatter(X,y)
plt.show()
Run Code Online (Sandbox Code Playgroud)

从图中我们可以看出,结果有很大不同。

在此输入图像描述

看起来这可能是由于浮点不精确造成的......

s66*_*666 2

我同时使用了它们,并得到了相同的 R2 分数和相同的曲线

regr = LinearRegression()
cubic = PolynomialFeatures(degree=3)
X_cubic = cubic.fit_transform(dfa3.home_realshow_cnt.values.reshape(-1, 1))
regr = regr.fit(X_cubic,dfa3.prop)

sklearn_r2=r2_score(dfa3.prop,regr.predict(X_cubic))
fit_r2=r2_score(dfa3.prop,yvalsa)
print("sklearn_r2: ",sklearn_r2,'; fit_r2: ',fit_r2)
Run Code Online (Sandbox Code Playgroud)
def fit(x,y,n):
    z1 = np.polyfit(x,y, n)
    p1 = np.poly1d(z1)
    return p1(x)
Run Code Online (Sandbox Code Playgroud)