比较不同曲线的均方误差

时间:2019-05-20 08:38:02

标签: python numpy linear-regression least-squares mean-square-error

我找到了适合线性,二次方和三次方函数的最小二乘法,并尝试打印其误差。一切正常,但是我不明白为什么每次我都变得更合适时他们的错误会增加,我是否以错误的方式计算了错误?这是情节,我的代码如下:

enter image description here

][1]

enter image description here

例如,这是使我获得立方图的代码。

Docker container

2 个答案:

答案 0 :(得分:2)

我认为这只是最后一段代码中的一个小错误:您正在计算沿线的错误,而不仅仅是针对点。相反,您要做的是计算每个点的距离。换句话说,y_prediction和b应该具有相同的尺寸

b = np.array((1,2,0,3))
y_prediction = xfeature**3*xstar[3] + xfeature**2*xstar[2] + xfeature*xstar[1] + xstar[0]
SSE = np.sum(np.square(y_prediction - b))
MSE = np.mean(np.square(y_prediction - b))
print("Sum of squared errors:", SSE)
print("Mean squared error:", MSE)

那是你的追求吗?

答案 1 :(得分:1)

作为拟合的另一种方法,这是一个使用numpy的polyfit()的示例Python图形多项式拟合器。您可以在代码顶部更改多项式顺序。

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)