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

3

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

  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, 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)


2
我相信问题不在你的代码中,而是在你的期望值上,因为那条虚线看起来是正确的。(参见以下问题及其被接受的答案:https://stats.stackexchange.com/questions/22718/what-is-the-difference-between-linear-regression-on-y-with-x-and-x-with-y) - Jasmijn
@Jasmijn,通过你提供的问题,我理解第二种情况下的线性回归应该与第一种情况不同,因为你在不同的轴上最小化误差。然而,我发现它实际上看起来与随机变量的“斜率”为4的定义非常不同(甚至是错误的)... - Puco4
2个回答

2

在仔细思考了@Jjacquelin的评论和回答后,我理解了我的示例线性回归的特殊形状。如果有帮助,我将分享它给其他人。

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

enter image description here enter image description here

我们可以看到,沿着垂直轴的随机变量的平均值(绿点)——代表在垂直轴上最小化线性拟合误差的点——大约落在线性回归处。此外,我们可以理解为什么在第二个图中线性回归看起来“错误”。这是因为在极端情况下,分布被“截断”,将随机变量的平均值移动到图片内部并旋转预期的线性回归(红色虚线)。

1
我相信问题不在于软件和代码,而是拟合标准的问题。
如果数据不分散,则拟合标准并不重要,结果是唯一的。
如果数据分散,那么最佳拟合也会因不同的拟合标准而异。随着散点图的离散程度越大,拟合标准的不同可能导致结果差异越大。
线性回归是一个众所周知的例子:

enter image description here

当然,可能会规定其他不同的拟合标准。
注意:上面的图和公式是从该论文的第7-8页复制而来https://fr.scribd.com/doc/14819165/Regressions-coniques-quadriques-circulaire-spherique

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接