Python 学习线性回归输出
我试图使用线性回归将抛物线拟合到一个简单生成的数据集中,但是无论我做什么,直接从模型中得到的曲线都是一团混乱Python 学习线性回归输出,python,scikit-learn,linear-regression,Python,Scikit Learn,Linear Regression,我试图使用线性回归将抛物线拟合到一个简单生成的数据集中,但是无论我做什么,直接从模型中得到的曲线都是一团混乱 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
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.predict(np.hstack([xfit,xfit**2]))
在代码中,您正在X轴上绘制
xfit
值,而在Y轴上绘制f(xtrain)
。有一个类型。。它应该是model.predict(np.hstack([xfit,xfit**2])
yfit = model.coef_[0]*xfit + model.coef_[1]*xfit**2 + model.intercept_