【问题标题】:Sklearn Linear Regression outputSklearn 线性回归输出
【发布时间】:2021-02-20 13:57:48
【问题描述】:

我正在尝试使用线性回归将抛物线拟合到一个简单的生成数据集中,但是无论我做什么,我直接从模型中得到的曲线都变得一团糟。

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

#xtrain, ytrain datasets have been generated earlier

model = LinearRegression(fit_intercept = True)
model.fit(np.hstack([xtrain, xtrain**2]), ytrain)  
xfit = np.linspace(-3,3,20)  
yfit = model.predict(np.hstack([xtrain, xtrain**2]))
plt.plot(xfit, yfit)
plt.scatter(xtrain, ytrain, color="black")

此代码输出以下图表:

但是,当我通过简单地更改以下代码行从模型产生的系数手动生成图时,我得到了我想要的结果。

yfit = model.coef_[0]*xfit + model.coef_[1]*xfit**2 + model.intercept_

这似乎有点笨拙,所以我想学习如何正确生成曲线。我认为问题一定是我的数据的离散性,但我自己无法弄清楚。

【问题讨论】:

  • 有一个类型..应该是model.predict(np.hstack([xfit, xfit**2]))

标签: python scikit-learn linear-regression


【解决方案1】:

这是您修复的错误:

yfit = model.predict(np.hstack([xfit, xfit**2]))

在您的代码中,您在 X 轴上绘制 xfit 值,而在 Y 轴上绘制 f(xtrain)

【讨论】:

    猜你喜欢
    • 2016-10-25
    • 2018-05-16
    • 2016-10-05
    • 2015-06-10
    • 2014-05-05
    • 2015-01-29
    • 2020-12-24
    • 1970-01-01
    • 2019-08-01
    相关资源
    最近更新 更多