You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

绘图问题:拟合图过于嘈杂,需生成清晰的单条拟合直线

解决拟合图嘈杂、无清晰拟合直线的问题

你的拟合图看起来杂乱无章,核心原因是X_test数据未按从小到大排序。plt.plot()会严格按照输入X的顺序依次连接点,无序的X会让折线来回交叉,导致视觉上显得嘈杂。

修改代码步骤:

在预测前先对X_test排序,确保预测值和排序后的X一一对应:

model2 = Pipeline([('poly', PolynomialFeatures(degree=2)),('quadratic', linear_model.LinearRegression())])
model2.fit(np.array(X_train).reshape(-1, 1), Y_train)

# 对X_test排序,保证拟合线按顺序绘制
X_test_sorted = np.sort(np.array(X_test).reshape(-1, 1), axis=0)
y_new = model2.predict(X_test_sorted)

# plot the results
plt.scatter(X_train, Y_train)
plt.plot(X_test_sorted, y_new, 'r', label="Fit "+str(2)+ " degree poly")
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
               ncol=2, mode="expand", borderaxespad=0.)
plt.show()  # 确保图形正常显示

额外检查点:

  • 如果X_train本身包含大量噪声点,拟合曲线可能仍会有一定波动,但排序是解决折线混乱的核心操作
  • 确认PolynomialFeatures的include_bias参数(默认True)符合你的需求,一般无需调整

内容的提问来源于stack exchange,提问作者Sana Ullah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 10:50:24