代码之家  ›  专栏  ›  技术社区  ›  Sean

有没有办法在另一个图上绘制普通的最小二乘型直线?

  •  0
  • Sean  · 技术社区  · 5 年前

    我现在有一个数据点的散点图,我想画一条线来捕捉数据的一般模式。我相信这也被称为一个普通的最小二乘回归方法,但我可能是错的,因为我不完全熟悉的文献。

    例如,如果我有如下情节:

    enter image description here

    我只想要一条线,通过数据点,捕捉最普遍的趋势。

    我试过像使用Scikit Learn这样的方法 LinearRegression 模块,但我必须将数据拆分为训练集和测试集并执行回归。有没有一种方法可以让我不必这样做就可以捕捉总体趋势?

    谢谢您。

    0 回复  |  直到 5 年前
        1
  •  1
  •   James Phillips    5 年前

    下面是一个多项式拟合的例子,如果你把你的日期格式转换成一个数字类型,如“已用天数”,你可以直接把你的数据替换成例子。在这里,我使用一个二阶多项式(二次)曲线方程,设置在代码的顶部,因为在我看来,数据的趋势似乎有一些曲率,而不是直线。

    plot

    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)