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

Why is the linear regression wrong when I switch X and Y of a random variable Z(X, Y)?

我有一个我似乎无法理解的奇怪错误:

  1. 我在二维 Z(X,Y) 中绘制随机变量的 N 个值 (X, Y)。
  2. 我构建直方图并用 imshow 绘制它。
  3. 我用 (X,Y) 值计算线性回归并绘制它: 到目前为止一切看起来都很正常。
  4. 现在我重复 1.、2. 和 3,但切换 X 和 Y。我希望找到相同的图片,但轴切换。但是,这次 线性回归(橙色虚线)不正确 并且斜率不同于预期的 1/0.25(红色虚线)。

知道错误所在吗?

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, 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, xedges, yedges = np.histogram2d(X2, Y2, bins=[x, y])
H = H.T

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

lr = linregress(X2, Y2)
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.plot(xLine, [4*z for z in xLine], 'red', ls = '--')


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

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

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

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

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

当然还有很多其他可能指定的不同验配标准。

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

中的pp.7-8复制过来的

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

关键是 线性回归优化参数,使垂直轴上的误差最小化 。我们可以通过 随机变量沿垂直轴的分布 (绿色虚线)及其 平均值(绿色点)。我在两张图片中都手绘了这些:

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

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