计算线性回归斜率矩阵(类似于相关矩阵)- Python/Pandas

calculate linear regression slope matrix (analogous to correlation matrix) - Python/Pandas

Pandas 有一个非常好的函数,可以为您的数据 DataFrame 提供相关矩阵 DataFrame,pd.DataFrame.corr().

然而,相关性的 r 并不总是那么有用。根据您的应用,线性回归的斜率可能同样重要。是否有任何函数可以 return 输入矩阵或数据帧?

除了使用 scipy.stats.linregress() 进行迭代之外,这会很痛苦,我看不出有什么方法可以做到这一点吗?

回归线的斜率 y=b0 + b1 * x 也可以使用相关系数计算:b1 = corr(x, y) * σx / σy

使用 numpy 的 newaxis 创建 σx / σy 矩阵:

df.corr() * (df.std().values / df.std().values[:, np.newaxis])
Out[59]: 
          A         B         C
A  1.000000 -0.686981  0.252078
B -0.473282  1.000000 -0.263359
C  0.137670 -0.208775  1.000000

其中 df 是:

df
Out[60]: 
   A  B  C
0  5  6  9
1  4  4  2
2  7  3  5
3  4  3  9
4  6  5  3
5  3  8  6
6  2  8  1
7  7  2  7
8  4  1  5
9  1  6  6

这是为了验证:

res = []
for col1, col2 in itertools.product(df.columns, repeat=2):
    res.append(linregress(df[col1], df[col2]).slope)
np.array(res).reshape(3, 3)
Out[72]: 
array([[ 1.        , -0.68698061,  0.25207756],
       [-0.47328244,  1.        , -0.26335878],
       [ 0.1376702 , -0.20877458,  1.        ]])