Sklearn 线性回归输出

Sklearn Linear Regression output

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

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_

这看起来有点笨拙,所以我想学习如何正确生成曲线。我认为问题一定是我的数据的离散性,但我无法自行解决。

这是你修复的错误:

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

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