簡體   English   中英

有沒有辦法在另一個圖上繪制普通最小二乘類型的線?

[英]Is there a way to plot the ordinary least squares type of line on another plot?

我目前有一個數據點的散點圖,我想畫一條線來捕捉數據的一般模式。 我相信這也被稱為普通的最小二乘回歸方法,但我可能錯了,因為我不完全熟悉文獻。

例如,如果我有一個像下面這樣的情節:

在此處輸入圖片說明

我只想要一條穿過數據點的線,捕捉最普遍的趨勢。

我嘗試過使用 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM