python - 在 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()
谢谢你的帮助!
解决方案
您正在“连接点”,但数据未排序 - 更改
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")
推荐阅读
- css - 如何删除嵌入在网站上的订阅按钮中的文本
- python - Python 错误:TypeError:'Timestamp' 类型的对象不是 JSON 可序列化的'
- java - 在 PostgreSQL JDBC 中设置模式似乎不起作用
- php - 如何使用 Laravel 在网站中实现 OCR
- macos - 如何从可执行文件更改mac应用程序名称?
- java - 尝试根据字符串数组列表的索引来累加双数组列表的总成本
- javascript - 如何将html文件的控制台输出带入phantomjs
- hazelcast - Hazelcast 分区队列
- gis - 从 GIS 转换到 netlogo 坐标时的小偏移
- dataset - “响应”对象在 kaggle cli 中没有属性“汤”