当我切换随机变量 Z(X, Y) 的 X 和 Y 时,为什么线性回归是错误的?

问题描述

我遇到了一个我似乎无法理解的奇怪错误

  1. 我在二维 Z(X,Y) 中绘制随机变量的 N 个值 (X,Y)。
  2. 我构建直方图并使用 imshow 绘制它。
  3. 我用 (X,Y) 值计算线性回归并绘制它:

    enter image description here

    到目前为止,一切看起来都很正常。
  4. 现在我重复 1.、2. 和 3,但切换 X 和 Y。我希望找到相同的图片,但轴已切换。但是,这一次线性回归(橙色虚线)不正确并且斜率与预期的 1/0.25(红色虚线)不同。

    enter image description here

您知道错误可能在哪里吗?

python中的代码

from scipy.stats import linregress
import numpy as np
import matplotlib.pyplot as plt

#Parameters
delta = 0.2
N = 10**5

#Bins
x = y = np.arange(-3.0,3.0,delta)

#Draw N values of the random variable Z(X,Y)
rnd = np.random.default_rng(seed = 0)
Z = rnd.uniform(0,1,N)
X = rnd.uniform(-3,3,N)
Y = 0.25*X + np.sqrt(np.log( 1 / Z ) ) - 0.89

#Construct histogram
H,xedges,yedges = np.histogram2d(X,Y,bins=[x,y])
#Tranpose to have x in columns and y in rows
H = H.T

#Plot
plt.imshow(H,cmap='Purples',origin='lower',extent=[-3,-3,3])

#Do linear regresion
lr = linregress(X,Y)
poly1d_fn = np.poly1d([lr.slope,lr.intercept])
xLine=[xedges[0],xedges[-1]]
plt.plot(xLine,poly1d_fn(xLine),'orange',ls = ':',label = '$y = ax+b$\n $a = %.2f \pm %.2f$\n $b = %.2f$,$R^2 = %.2f$ '%(lr.slope,lr.stderr,lr.intercept,lr.rvalue**2))
    
plt.colorbar()
plt.legend()
plt.savefig("first.png",dpi = 300)

#Repeat but switching X with Y
plt.figure()
X2 = Y
Y2 = X
H,yedges = np.histogram2d(X2,Y2,y])
H = H.T

plt.imshow(H,3])

lr = linregress(X2,Y2)
poly1d_fn = np.poly1d([lr.slope,lr.rvalue**2))

plt.plot(xLine,[4*z for z in xLine],'red',ls = '--')


plt.ylim([-3,3])
plt.colorbar()
plt.legend()
plt.savefig("second.png",dpi = 300)

解决方法

我很确定这种差异不是来自软件和代码。问题在于拟合标准。

如果数据不分散,则拟合标准无关紧要。结果是独一无二的。

如果数据是分散的,那么它们的“最佳拟合”与拟合的不同标准一样多。散点越大,结果可能因拟合标准而异。

一个众所周知的例子是线性回归:

enter image description here

当然,它们是许多其他可能指定的不同拟合标准。

注:上图和公式复制自论文https://fr.scribd.com/doc/14819165/Regressions-coniques-quadriques-circulaire-spherique

的pp.7-8 ,

在对@Jjacquelin 的评论和回答进行了一些反思后,提醒线性回归在交换 X 和 Y 轴时通常会发生变化,我理解了我的示例中线性回归的特定形状。我会分享它,以防它可以帮助其他人。

关键在于线性回归优化参数,使纵轴的误差最小​​strong>。我们可以通过随机变量沿垂直轴的分布(绿色虚线)及其平均值(绿色圆点)来直观地了解此过程背后的想法。我在两张图片中都手工绘制了这些:

enter image description here enter image description here

我们可以看到随机变量沿垂直轴的平均值(绿点)——代表最小化垂直轴线性拟合误差的点——大约下降在线性回归

此外,我们可以理解为什么在第二个图中线性回归看起来“错误”。那是因为在极端情况下,分布被“切割”,取代了图片内随机变量的平均值并旋转了预期的线性回归(红色虚线)。