我目前有一个数据点的散点图,我想画一条线来捕获数据的一般模式。我相信这也被称为普通最小二乘回归方法,但我可能是错的,因为我不完全熟悉文献。
例如,如果我有如下图:
我只想要一条穿过数据点的线,捕捉最普遍的趋势。
我尝试过使用 Scikit-Learn 的 LinearRegression
模块等方法,但我必须将数据拆分为训练集和测试集并执行回归。有没有一种方法可以让我无需执行此操作即可捕获总体趋势?
谢谢。
最佳答案
这里是一个执行此操作的多项式拟合器示例,如果您将日期格式转换为数字类型(例如“经过的天数”),您可以直接将数据替换到示例中。在这里,我使用弯曲的二阶多项式(二次)方程,设置在代码顶部,因为在我看来,数据的趋势似乎具有一定的曲率而不是直线。
import numpy, matplotlib
import matplotlib.pyplot as plt
xData = numpy.array([1.1, 2.2, 3.3, 4.4, 5.0, 6.6, 7.7, 0.0])
yData = numpy.array([1.1, 20.2, 30.3, 40.4, 50.0, 60.6, 70.7, 0.1])
polynomialOrder = 2 # example quadratic
# curve fit the test data
fittedParameters = numpy.polyfit(xData, yData, polynomialOrder)
print('Fitted Parameters:', fittedParameters)
modelPredictions = numpy.polyval(fittedParameters, xData)
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 = numpy.polyval(fittedParameters, xModel)
# 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)
关于python - 有没有办法在另一个图上绘制普通最小二乘类型的线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57744117/