gpt4 book ai didi

python - 使用 ScikitLearn 的多元线性回归,不同的方法给出不同的答案

转载 作者:太空宇宙 更新时间:2023-11-03 20:33:29 24 4
gpt4 key购买 nike

这在统计数据交换上可能与这里同样有效(可能是我不确定的统计数据或Python。

假设我有两个自变量 X,Y 来解释 Z 的一些方差。

    from sklearn.linear_model import LinearRegression
import numpy as np
from scipy.stats import pearsonr,linregress

Z = np.array([1,3,5,6,7,8,9,7,10,9])

X = np.array([2,5,3,1,6,4,7,8,6,7])
Y = np.array([3,2,6,4,6,1,2,5,6,10])

我想从 Z 中回归 X 和 Y 的变异性。我知道有两种方法:

首先从 Z 回归出 X(形成 X,Z 的线性回归,找到残差,然后对 Y 重复)。这样:

    regr = linregress(X,Z) 
resi_1 = NAO - (X*regr[0])+regr[1] #residual = y-mx+c

regr = linregress(Y,resi_1)
resi_2 = resi_1 - (Y*regr[0])+regr[1] #residual = y-mx+c

其中 regr_2 是 Z 的余数,其中 X 和 Y 已按顺序回归。

另一种方法是为 X 和 Y 创建多元线性回归模型来预测 Z:

regr = LinearRegression()
Model = regr.fit(np.array((X,Y)).swapaxes(0,1),Z)

pred = Model.predict(np.array((X,Y)).swapaxes(0,1))
resi_3 = Z - pred

第一个序贯方法 resi_2 和多元线性回归 resi_3 的残差非常相似 (correlation=0.97),但并不等效。两个残差绘制如下: enter image description here

任何想法都很棒(不是统计学家,所以可能是我的理解与Python问题!)。请注意,如果对于第一部分,我首先回归 Y,然后回归 X,我会得到不同的残差。

最佳答案

这是一个示例 3D 图形表面拟合器,使用您的数据和 scipy 的 curve_fit() 例程以及散点图、曲面图和等高线图。您应该能够单击并拖动 3D 图以在 3 空间中旋转它们,并看到数据似乎并不位于任何类型的光滑表面上,因此此处使用的平面模型“z = (a *x) + (b * y) + c"与此数据的任何其他模型相比几乎没有更好或更差。

fitted prameters [ 0.65963199  0.18537117  2.43363301]
RMSE: 2.11487214206
R-squared: 0.383078044516

scatter

surface

contour

import numpy, scipy, scipy.optimize
import matplotlib
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm # to colormap 3D surfaces from blue to red
import matplotlib.pyplot as plt

graphWidth = 800 # units are pixels
graphHeight = 600 # units are pixels

# 3D contour plot lines
numberOfContourLines = 16


def SurfacePlot(func, data, fittedParameters):
f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)

matplotlib.pyplot.grid(True)
axes = Axes3D(f)

x_data = data[0]
y_data = data[1]
z_data = data[2]

xModel = numpy.linspace(min(x_data), max(x_data), 20)
yModel = numpy.linspace(min(y_data), max(y_data), 20)
X, Y = numpy.meshgrid(xModel, yModel)

Z = func(numpy.array([X, Y]), *fittedParameters)

axes.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=1, antialiased=True)

axes.scatter(x_data, y_data, z_data) # show data along with plotted surface

axes.set_title('Surface Plot (click-drag with mouse)') # add a title for surface plot
axes.set_xlabel('X Data') # X axis data label
axes.set_ylabel('Y Data') # Y axis data label
axes.set_zlabel('Z Data') # Z axis data label

plt.show()
plt.close('all') # clean up after using pyplot or else there can be memory and process problems


def ContourPlot(func, data, fittedParameters):
f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
axes = f.add_subplot(111)

x_data = data[0]
y_data = data[1]
z_data = data[2]

xModel = numpy.linspace(min(x_data), max(x_data), 20)
yModel = numpy.linspace(min(y_data), max(y_data), 20)
X, Y = numpy.meshgrid(xModel, yModel)

Z = func(numpy.array([X, Y]), *fittedParameters)

axes.plot(x_data, y_data, 'o')

axes.set_title('Contour Plot') # add a title for contour plot
axes.set_xlabel('X Data') # X axis data label
axes.set_ylabel('Y Data') # Y axis data label

CS = matplotlib.pyplot.contour(X, Y, Z, numberOfContourLines, colors='k')
matplotlib.pyplot.clabel(CS, inline=1, fontsize=10) # labels for contours

plt.show()
plt.close('all') # clean up after using pyplot or else there can be memory and process problems


def ScatterPlot(data):
f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)

matplotlib.pyplot.grid(True)
axes = Axes3D(f)
x_data = data[0]
y_data = data[1]
z_data = data[2]

axes.scatter(x_data, y_data, z_data)

axes.set_title('Scatter Plot (click-drag with mouse)')
axes.set_xlabel('X Data')
axes.set_ylabel('Y Data')
axes.set_zlabel('Z Data')

plt.show()
plt.close('all') # clean up after using pyplot or else there can be memory and process problems


def func(data, a, b, c): # example flat surface
x = data[0]
y = data[1]
return (a * x) + (b * y) + c


if __name__ == "__main__":

xData = numpy.array([2.0, 5.0, 3.0, 1.0, 6.0, 4.0, 7.0, 8.0, 6.0, 7.0])
yData = numpy.array([3.0, 2.0, 6.0, 4.0, 6.0, 1.0, 2.0, 5.0, 6.0, 10.0])
zData = numpy.array([1.0, 3.0, 5.0, 6.0, 7.0, 8.0, 9.0, 7.0, 10.0, 9.0])

data = [xData, yData, zData]

initialParameters = [1.0, 1.0, 1.0] # these are the same as scipy default values in this example

# here a non-linear surface fit is made with scipy's curve_fit()
fittedParameters, pcov = scipy.optimize.curve_fit(func, [xData, yData], zData, p0 = initialParameters)

ScatterPlot(data)
SurfacePlot(func, data, fittedParameters)
ContourPlot(func, data, fittedParameters)

print('fitted prameters', fittedParameters)

modelPredictions = func(data, *fittedParameters)

absError = modelPredictions - zData

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(zData))
print('RMSE:', RMSE)
print('R-squared:', Rsquared)

关于python - 使用 ScikitLearn 的多元线性回归,不同的方法给出不同的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57326775/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com