首页 > 解决方案 > 在 Python 中绘制多项式回归

问题描述

我正在尝试使用 Matplotlib 绘制多项式模型,但它总是绘制多条线,我不知道如何修复它。我查找了多个网站,但找不到任何有用的东西。

我的数据示例

这是代码:

poly = PolynomialFeatures(degree = 3, include_bias = False)
poly.fit(X_train)

X_train_transformed = poly.transform(X_train)
X_test_transformed = poly.transform(X_test)

model_poly = LinearRegression()
model_poly.fit(X_train_transformed, Y_train)
print("Test accuracy: " + str(model_poly.score(X_test_transformed, Y_test)))
print("Train accuracy: " + str(model_poly.score(X_train_transformed, Y_train)))

Y_predicted_poly = model_poly.predict(X_test_transformed)

plt.figure(figsize = (12,8))
plt.scatter(X_train, Y_train, label = "Train")
plt.scatter(X_test, Y_test, label = "Test")
plt.plot(X_test, Y_predicted_poly, color = "green", label = "Regression")
plt.xlabel("Year")
plt.ylabel("Temperature")
plt.title("Polynomial Regression", fontsize = 16)
plt.legend()
plt.show()

谢谢你的帮助!

标签: pythonmatplotlibscikit-learn

解决方案


您正在“连接点”,但数据未排序 - 更改

plt.plot(X_test, Y_predicted_poly, color = "green", label = "Regression")

plt.scatter(X_test, Y_predicted_poly, color = "green", label = "Regression")

我 blv 事情会看起来好一点。或者,在计算 Y_predicted_poly 之前,将 X_test 从小到大(反之亦然)排序。或者,不要在 plt.plot 中使用一行:

plt.plot(X_test, Y_predicted_poly, 'go', label = "Regression")

推荐阅读