【问题标题】:Polynomial regression with scikit learn vs np.polyfitscikit learn 与 np.polyfit 的多项式回归
【发布时间】:2020-10-10 06:03:17
【问题描述】:

我很惊讶没有人谈论这个:用 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)

然后让我们用 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)

然后你可以创建一个情节

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

这是剧情

使用 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()

通过情节我们可以看到结果大相径庭。

这似乎是由于浮点不精确...

【问题讨论】:

    标签: python scikit-learn regression linear-regression


    【解决方案1】:

    我两个都用了,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)
    
    def fit(x,y,n):
        z1 = np.polyfit(x,y, n)
        p1 = np.poly1d(z1)
        return p1(x)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-16
      • 2014-10-09
      • 2019-09-20
      • 2013-12-26
      • 2020-10-30
      • 2020-09-12
      • 2016-07-31
      相关资源
      最近更新 更多