python - matplotlib 中多元回归的散点图
问题描述
我有四个特征和一个从属(X)。我想用预测的回归线和特征值绘制一个图表。我浏览了文档,但我不知道如何在散点图中表示所有内容。
解决方案
这里有一些示例代码可以帮助您入门,它适合一个简单的二次方并散点图原始数据和拟合曲线以及 RMSE 和 R 平方的计算。如果您想尝试拟合非线性方程,该示例使用非线性拟合。
import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import scipy.stats
xData = numpy.array([1.1, 2.2, 3.3, 4.4, 5.0, 6.6, 7.7])
yData = numpy.array([1.1, 20.2, 30.3, 40.4, 50.0, 60.6, 70.7])
def func(x, a, b, c): # simple quadratic example
return (a * numpy.square(x)) + b * x + c
initialParameters = numpy.array([1.0, 1.0, 1.0])
# curve fit the test data
fittedParameters, pcov = curve_fit(func, xData, yData, initialParameters)
modelPredictions = func(xData, *fittedParameters)
absError = modelPredictions - yData
SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))
print('RMSE:', RMSE)
print('R-squared:', Rsquared)
print()
##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
axes = f.add_subplot(111)
# first the raw data as a scatter plot
axes.plot(xData, yData, 'D')
# create data for the fitted equation plot
xModel = numpy.linspace(min(xData), max(xData))
yModel = func(xModel, *fittedParameters)
# now the model as a line plot
axes.plot(xModel, yModel)
axes.set_xlabel('X Data') # X axis data label
axes.set_ylabel('Y Data') # Y axis data label
plt.show()
plt.close('all') # clean up after using pyplot
graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)
推荐阅读
- c# - 为什么我们在 asp.net core 的 kestrel 配置中使用 UseConnectionLogging 以及它是如何工作的?
- swift - 快速防止手机键盘文本字段上的“0”第一个字符
- html - 如何使页面文本从右到左?
- python - 为什么我的 IdentitySet 只显示最后一项?
- java - 如何使用 Quarkus 反应式客户端插入时间?
- node.js - 有没有办法告诉 nodejs 服务器从浏览器请求中丢弃查询字符串?
- php - 错误:在文件 Container.php 中的 clas JsonResource 中无法解析的依赖解析 $resource
- javascript - 无论如何从变量执行JavaScript?
- continuous-integration - 手动作业中的 Gitlab CI/CD 预填充变量
- android - 在kotlin中使用MapView检索片段中的当前位置?