二维线性回归系数

two dimensional linear regression coefficients

我正在用二维变量做线性回归:

 filtered[['p_tag_x', 'p_tag_y', 's_tag_x', 's_tag_y']].head()

     p_tag_x      p_tag_y            s_tag_x     s_tag_y
35    589.665646  1405.580171        517.5       1636.5
36    589.665646  1405.580171        679.5       1665.5
100   610.546851  2425.303250        569.5       2722.0
101   610.546851  2425.303250        728.0       2710.0
102   717.237730  1411.842428        820.0       1616.5



clt = linear_model.LinearRegression()
clt.fit(filtered[['p_tag_x', 'p_tag_y']], filtered[['s_tag_x', 's_tag_y']])

我得到以下回归系数:

clt.coef_

array([[ 0.4529769 , -0.22406594],
       [-0.00859452, -0.00816968]])

和残差(X_0,和Y_0)

clt.residues_
array([ 1452.97816371,    69.12754694])

我应该如何根据回归线理解上述系数矩阵?

正如我已经在评论中解释的那样,你的 coef_intercept_ 都有一个额外的维度,因为你有 2 个目标 y.shape(n_samples, n_targets))。在这种情况下,sklearn 将适合 2 个独立回归器,每个目标一个。

然后您可以将 n 个回归变量 分开并单独处理每一个。

你的回归线formula仍然是:

y(w, x) = intercept_ + coef_[0] * x[0] + coef_[1] * x[1] ... 

遗憾的是,由于维度的原因,您的示例有点难以形象化。

将此视为一个演示,针对此特定案例(以及糟糕的示例数据!)进行了大量丑陋的硬编码:

代码:

# Warning: ugly demo-like code using a lot of hard-coding!!!!!

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import linear_model

X = np.array([[589.665646,  1405.580171],
              [589.665646,  1405.580171],
              [610.546851,  2425.303250],
              [610.546851,  2425.303250],
              [717.237730,  1411.842428]])

y = np.array([[517.5,       1636.5],
              [679.5,       1665.5],
              [569.5,       2722.0],
              [728.0,       2710.0],
              [820.0,       1616.5]])

clt = linear_model.LinearRegression()
clt.fit(X, y)

print(clt.coef_)
print(clt.residues_)

def curve_0(x, y):  # target 0; single-point evaluation hardcoded for 2 features!
    return clt.intercept_[0] + x * clt.coef_[0, 0] + y * clt.coef_[0, 1]

def curve_1(x, y):  # target 1; single-point evaluation hardcoded for 2 features!
    return clt.intercept_[1] + x * clt.coef_[1, 0] + y * clt.coef_[1, 1]

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

xs = [np.amin(X[:, 0]), np.amax(X[:, 0])]
ys = [np.amin(X[:, 1]), np.amax(X[:, 1])]

# regressor 0
ax.scatter(X[:, 0], X[:, 1], y[:, 0], c='blue')
ax.plot([xs[0], xs[1]], [ys[0], ys[1]], [curve_0(xs[0], ys[0]), curve_0(xs[1], ys[1])], c='cyan')

# regressor 1
ax.scatter(X[:, 0], X[:, 1], y[:, 1], c='red')
ax.plot([xs[0], xs[1]], [ys[0], ys[1]], [curve_1(xs[0], ys[0]), curve_1(xs[1], ys[1])], c='magenta')

ax.set_xlabel('X[:, 0] feature 0')
ax.set_ylabel('X[:, 1] feature 1')
ax.set_zlabel('Y')

plt.show()

输出:

备注:

  • 您不必自己计算公式:clt.predict() 会做到这一点!
  • 涉及 ax.plot(...) 的代码行使用假设,即我们的线仅由 2 个点(线性)定义!