gpt4 book ai didi

python - 具有多项式特征和线性回归的管道 - 意外的结果

转载 作者:太空宇宙 更新时间:2023-11-03 15:01:08 25 4
gpt4 key购买 nike

使用以下代码,我只想将回归曲线拟合到未按预期工作的样本数据。

X = 10*np.random.rand(100)
y= 2*X**2+3*X-5+3*np.random.rand(100)
xfit=np.linspace(0,10,100)


poly_model=make_pipeline(PolynomialFeatures(2),LinearRegression())
poly_model.fit(X[:,np.newaxis],y)


y_pred=poly_model.predict(X[:,np.newaxis])


plt.scatter(X,y)
plt.plot(X[:,np.newaxis],y_pred,color="red")

plt.show()

enter image description here

难道不应该有一条与数据点完美拟合的曲线吗?因为训练数据 (X[:,np.newaxis]) 和用于预测 y_pred 的数据是相同的(也是 (X[:,np.newaxis])。

如果我使用 xfit 数据来预测模型,结果将如预期......

...

y_pred=poly_model.predict(xfit[:,np.newaxis])

plt.scatter(X,y)
plt.plot(xfit[:,np.newaxis],y_pred,color="red")

plt.show()

enter image description here

那么问题是什么以及这种行为的解释是什么?

最佳答案

两个图之间的区别在于行

plt.plot(X[:,np.newaxis],y_pred,color="red")

X[:,np.newaxis] 中的值未排序,而

plt.plot(xfit[:,np.newaxis],y_pred,color="red")

xfit[:,np.newaxis] 的值已排序。

现在,plt.plot 按行连接数组中的任意两个连续值,并且由于它们未排序,因此您会在第一个图中得到这一串行。

替换

plt.plot(X[:,np.newaxis],y_pred,color="red")

plt.scatter(X[:,np.newaxis],y_pred,color="red")

你会得到这个漂亮的人物:

enter image description here

关于python - 具有多项式特征和线性回归的管道 - 意外的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45098253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com