Python线性回归,残差的最佳拟合线

标签 python linear-regression

我已经完成了线性回归和最佳拟合线,但还希望有一条线将真实点(蓝色的点)连接到代表预测误差的预测点(红色 x 的点),或者所谓的残差。情节应该看起来类似:

Desired output

到目前为止我所拥有的是:

Until now

# draw the plot
xx=X[:,np.newaxis]
yy=y[:,np.newaxis]
slr=LinearRegression()
slr.fit(xx,yy)
y_pred=slr.predict(xx)
plt.scatter(xx,yy)
plt.plot(xx,y_pred,'r')
plt.plot(X,y_pred,'rx') #add the prediction points 
plt.show()

提前非常感谢您!

最佳答案

这是带有垂直线的示例代码

import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

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, 60.4, 50.0, 60.6, 70.7])


def func(x, a, b): # simple linear example
    return a * x + b


initialParameters = numpy.array([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)

    # now add individual line for each point
    for i in range(len(xData)):
        lineXdata = (xData[i], xData[i]) # same X
        lineYdata = (yData[i], modelPredictions[i]) # different Y
        plt.plot(lineXdata, lineYdata)

    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)

enter image description here

关于Python线性回归,残差的最佳拟合线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53779773/

相关文章:

python - Django - 通过 ajax 请求提供文件

python - 如何在 python (windows 7) 上安装模块

python - 在 Python 中引导多个回归参数

python - 使用 python 将具有字符串形式值的属性转换为 vetor

python - 从seaborn散点图中的点中删除白色边框

python - 无法使用 Python 请求自动执行脚本来检查 phishcheck.me 上的 url

python - 执行 FFT 和峰值检测后如何获取 BPM

OLS中自动测试交互效果的Python方法

r - 综上.lm(P.for.trend) : essentially perfect fit: summary may be unreliable; How to deal with this?

r - 从多个线性回归模型的输出创建数据框