📐 10 · 相关与回归分析¶
「广告投入和收入相关吗?」「投入 10 万能带来多少收入?」——相关度量关系强度,回归给出关系方程。本节手写皮尔逊/斯皮尔曼相关与 OLS 回归,并对照 numpy/sklearn。
📋 本节要解决的问题¶
| # | 问题 | 方法 |
|---|---|---|
| 1 | 两个变量线性相关有多强? | 皮尔逊 r |
| 2 | 非线性或离群值下用什么? | 斯皮尔曼秩相关 |
| 3 | y 怎么随 x 变化? | 一元 OLS |
| 4 | 多个因素怎么一起预测? | 多元 OLS + R² |
| 5 | 自变量互相相关怎么办? | 多重共线性 |
Copied!
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'PingFang SC', 'Noto Sans CJK SC', 'Arial Unicode MS']
matplotlib.rcParams['axes.unicode_minus'] = False
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'PingFang SC', 'Noto Sans CJK SC', 'Arial Unicode MS']
matplotlib.rcParams['axes.unicode_minus'] = False
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
1️⃣ 皮尔逊相关系数:手写 vs numpy¶
✍️ §1.1 手算皮尔逊相关系数:5 个点的 r = 0.8¶
$r=\frac{\sum(x_i-\bar x)(y_i-\bar y)}{\sqrt{\sum(x_i-\bar x)^2\sum(y_i-\bar y)^2}}$——5 个点手算,理解"线性相关强度"。
设定:$(x,y)=(1,2),(2,4),(3,3),(4,6),(5,5)$,均值 $\bar x=3,\ \bar y=4$。
第 1 步:离差乘积与平方和
| x | y | $x-\bar x$ | $y-\bar y$ | 乘积 | $(x-\bar x)^2$ | $(y-\bar y)^2$ |
|---|---|---|---|---|---|---|
| 1 | 2 | −2 | −2 | 4 | 4 | 4 |
| 2 | 4 | −1 | 0 | 0 | 1 | 0 |
| 3 | 3 | 0 | −1 | 0 | 0 | 1 |
| 4 | 6 | 1 | 2 | 2 | 1 | 4 |
| 5 | 5 | 2 | 1 | 2 | 4 | 1 |
第 2 步:代入
$$r=\frac{4+0+0+2+2}{\sqrt{(4+1+0+1+4)(4+0+1+4+1)}}=\frac{8}{\sqrt{10\times10}}=\mathbf{0.8}$$
手算收获:
- $r$ 只衡量线性相关:$|r|$ 接近 1 = 点在直线附近,$r=0$ 不代表无关(可能是非线性,§2 斯皮尔曼对比离群值/单调非线性)
- 分子是"协方差",分母是"各自标准差之积"——$r$ 无量纲(不随单位变化),所以可比
- 共线性注意:广告与门店数高度相关时多元回归系数会不稳定(§5)——相关系数矩阵是初筛工具
- 回归延伸:一元 OLS 斜率 $\hat\beta=r\frac{s_y}{s_x}$,$r$ 可以直接换算成回归系数(§3 最小二乘)
下面 numpy 复算。
Copied!
# ---- §1.1 验证:numpy 复算皮尔逊相关系数 ----
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 3, 6, 5])
r = np.corrcoef(x, y)[0, 1]
print(f'皮尔逊 r = {r:.4f}(手算 0.8)')
assert abs(r - 0.8) < 1e-9
print('\n✓ 与手算一致')
# ---- §1.1 验证:numpy 复算皮尔逊相关系数 ----
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 3, 6, 5])
r = np.corrcoef(x, y)[0, 1]
print(f'皮尔逊 r = {r:.4f}(手算 0.8)')
assert abs(r - 0.8) < 1e-9
print('\n✓ 与手算一致')
皮尔逊 r = 0.8000(手算 0.8) ✓ 与手算一致
Copied!
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y = np.array([2.1, 3.9, 6.2, 8.0, 10.1, 12.3, 14.0, 16.2, 18.1, 20.0])
def pearson(a, b):
xm, ym = a.mean(), b.mean()
return np.sum((a-xm)*(b-ym)) / np.sqrt(np.sum((a-xm)**2) * np.sum((b-ym)**2))
r_manual = pearson(x, y)
r_np = np.corrcoef(x, y)[0, 1]
print(f'手写 r = {r_manual:.4f} numpy r = {r_np:.4f}')
assert abs(r_manual - r_np) < 1e-9
print('✅ 高度正相关(r 接近 1)')
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y = np.array([2.1, 3.9, 6.2, 8.0, 10.1, 12.3, 14.0, 16.2, 18.1, 20.0])
def pearson(a, b):
xm, ym = a.mean(), b.mean()
return np.sum((a-xm)*(b-ym)) / np.sqrt(np.sum((a-xm)**2) * np.sum((b-ym)**2))
r_manual = pearson(x, y)
r_np = np.corrcoef(x, y)[0, 1]
print(f'手写 r = {r_manual:.4f} numpy r = {r_np:.4f}')
assert abs(r_manual - r_np) < 1e-9
print('✅ 高度正相关(r 接近 1)')
手写 r = 0.9998 numpy r = 0.9998 ✅ 高度正相关(r 接近 1)
2️⃣ 皮尔逊 vs 斯皮尔曼:离群值与非线性¶
Copied!
from scipy import stats
# 单调非线性(指数关系):皮尔逊低估相关,斯皮尔曼按秩得满分
x2 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y2 = np.array([2, 4, 8, 16, 32, 64, 128, 256, 512, 1024])
r_p = pearson(x2, y2)
r_s, _ = stats.spearmanr(x2, y2)
print(f'皮尔逊 r = {r_p:.3f}(只捕捉线性,低估指数关系)')
print(f'斯皮尔曼 ρ = {r_s:.3f}(按秩计算,捕捉单调关系)')
assert r_s > 0.99 and r_s > r_p
print('\n✅ 非线性单调关系:斯皮尔曼更合适')
from scipy import stats
# 单调非线性(指数关系):皮尔逊低估相关,斯皮尔曼按秩得满分
x2 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y2 = np.array([2, 4, 8, 16, 32, 64, 128, 256, 512, 1024])
r_p = pearson(x2, y2)
r_s, _ = stats.spearmanr(x2, y2)
print(f'皮尔逊 r = {r_p:.3f}(只捕捉线性,低估指数关系)')
print(f'斯皮尔曼 ρ = {r_s:.3f}(按秩计算,捕捉单调关系)')
assert r_s > 0.99 and r_s > r_p
print('\n✅ 非线性单调关系:斯皮尔曼更合适')
皮尔逊 r = 0.799(只捕捉线性,低估指数关系) 斯皮尔曼 ρ = 1.000(按秩计算,捕捉单调关系) ✅ 非线性单调关系:斯皮尔曼更合适
3️⃣ 一元线性回归:最小二乘手写 vs sklearn¶
Copied!
from sklearn.linear_model import LinearRegression
n2 = 200
x2a = rng.uniform(0, 100, n2)
y2a = 3.0 + 0.8*x2a + rng.normal(0, 5, n2)
# 手写最小二乘:β = cov(x,y)/var(x),α = ȳ - βx̄
beta = np.sum((x2a-x2a.mean())*(y2a-y2a.mean())) / np.sum((x2a-x2a.mean())**2)
alpha = y2a.mean() - beta*x2a.mean()
# sklearn 对照
lr = LinearRegression().fit(x2a.reshape(-1, 1), y2a)
print(f'手写: y = {alpha:.3f} + {beta:.3f}x')
print(f'sklearn: y = {lr.intercept_:.3f} + {lr.coef_[0]:.3f}x')
assert abs(alpha - lr.intercept_) < 0.2 and abs(beta - lr.coef_[0]) < 0.2
plt.figure(figsize=(7, 4))
plt.scatter(x2a, y2a, alpha=0.4, s=20)
xs = np.linspace(0, 100, 10)
plt.plot(xs, alpha + beta*xs, color='red', lw=2)
plt.xlabel('广告投入')
plt.ylabel('销售额')
plt.title('一元回归拟合')
plt.show()
from sklearn.linear_model import LinearRegression
n2 = 200
x2a = rng.uniform(0, 100, n2)
y2a = 3.0 + 0.8*x2a + rng.normal(0, 5, n2)
# 手写最小二乘:β = cov(x,y)/var(x),α = ȳ - βx̄
beta = np.sum((x2a-x2a.mean())*(y2a-y2a.mean())) / np.sum((x2a-x2a.mean())**2)
alpha = y2a.mean() - beta*x2a.mean()
# sklearn 对照
lr = LinearRegression().fit(x2a.reshape(-1, 1), y2a)
print(f'手写: y = {alpha:.3f} + {beta:.3f}x')
print(f'sklearn: y = {lr.intercept_:.3f} + {lr.coef_[0]:.3f}x')
assert abs(alpha - lr.intercept_) < 0.2 and abs(beta - lr.coef_[0]) < 0.2
plt.figure(figsize=(7, 4))
plt.scatter(x2a, y2a, alpha=0.4, s=20)
xs = np.linspace(0, 100, 10)
plt.plot(xs, alpha + beta*xs, color='red', lw=2)
plt.xlabel('广告投入')
plt.ylabel('销售额')
plt.title('一元回归拟合')
plt.show()
手写: y = 1.454 + 0.833x sklearn: y = 1.454 + 0.833x
4️⃣ 多元回归与 R²(决定系数)¶
Copied!
# y = 收入;X = [广告, 促销天数, 门店数]
X = np.column_stack([rng.uniform(10, 50, 100), rng.uniform(0, 10, 100), rng.integers(3, 20, 100)])
beta_true = np.array([2.0, 5.0, 1.5])
y3 = X @ beta_true + rng.normal(0, 4, 100)
# 正规方程:β = (XᵀX)⁻¹Xᵀy
Xb = np.column_stack([np.ones(100), X])
beta_hat = np.linalg.inv(Xb.T @ Xb) @ Xb.T @ y3
y_pred = Xb @ beta_hat
# R² = 1 - SSE/SST
sse = np.sum((y3 - y_pred)**2)
sst = np.sum((y3 - y3.mean())**2)
r_sq = 1 - sse/sst
print(f'回归系数(含截距): {beta_hat.round(3)}')
print(f'R² = {r_sq:.4f}')
assert r_sq > 0.9
print('✅ 多元线性回归 + R² 计算完成')
# y = 收入;X = [广告, 促销天数, 门店数]
X = np.column_stack([rng.uniform(10, 50, 100), rng.uniform(0, 10, 100), rng.integers(3, 20, 100)])
beta_true = np.array([2.0, 5.0, 1.5])
y3 = X @ beta_true + rng.normal(0, 4, 100)
# 正规方程:β = (XᵀX)⁻¹Xᵀy
Xb = np.column_stack([np.ones(100), X])
beta_hat = np.linalg.inv(Xb.T @ Xb) @ Xb.T @ y3
y_pred = Xb @ beta_hat
# R² = 1 - SSE/SST
sse = np.sum((y3 - y_pred)**2)
sst = np.sum((y3 - y3.mean())**2)
r_sq = 1 - sse/sst
print(f'回归系数(含截距): {beta_hat.round(3)}')
print(f'R² = {r_sq:.4f}')
assert r_sq > 0.9
print('✅ 多元线性回归 + R² 计算完成')
回归系数(含截距): [-2.854 2.122 4.892 1.438] R² = 0.9862 ✅ 多元线性回归 + R² 计算完成
5️⃣ 多重共线性:自变量之间相关的问题¶
Copied!
# 广告投入与门店数高度相关 → 系数不稳定
feat = pd.DataFrame({
'广告': rng.uniform(10, 50, 100),
'促销天数': rng.uniform(0, 10, 100),
})
feat['门店数'] = feat['广告'] * 0.8 + rng.normal(0, 1, 100) # 与广告强相关
print('自变量相关系数矩阵:')
print(feat.corr().round(3))
plt.figure(figsize=(5, 4))
plt.imshow(feat.corr().values, cmap='RdBu_r', vmin=-1, vmax=1)
plt.xticks(range(3), feat.columns); plt.yticks(range(3), feat.columns)
plt.colorbar(label='r')
plt.title('特征相关性热力图(广告↔门店数 强相关)')
plt.show()
print('\n➡️ 共线性后果:系数估计方差变大、解释不可靠;可用 VIF 检测或做特征选择')
# 广告投入与门店数高度相关 → 系数不稳定
feat = pd.DataFrame({
'广告': rng.uniform(10, 50, 100),
'促销天数': rng.uniform(0, 10, 100),
})
feat['门店数'] = feat['广告'] * 0.8 + rng.normal(0, 1, 100) # 与广告强相关
print('自变量相关系数矩阵:')
print(feat.corr().round(3))
plt.figure(figsize=(5, 4))
plt.imshow(feat.corr().values, cmap='RdBu_r', vmin=-1, vmax=1)
plt.xticks(range(3), feat.columns); plt.yticks(range(3), feat.columns)
plt.colorbar(label='r')
plt.title('特征相关性热力图(广告↔门店数 强相关)')
plt.show()
print('\n➡️ 共线性后果:系数估计方差变大、解释不可靠;可用 VIF 检测或做特征选择')
自变量相关系数矩阵:
广告 促销天数 门店数
广告 1.000 -0.110 0.995
促销天数 -0.110 1.000 -0.131
门店数 0.995 -0.131 1.000
C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 8596 missing from current font. font.set_text(s, 0.0, flags=flags) C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 8596 missing from current font. font.set_text(s, 0, flags=flags)
➡️ 共线性后果:系数估计方差变大、解释不可靠;可用 VIF 检测或做特征选择
6️⃣ 业务解读与注意事项¶
- 回归 ≠ 因果:系数只描述条件相关,业务决策需实验或因果推断;
- R² 高不一定好:过拟合、共线性、数据泄漏都可能导致虚假高 R²;
- 系数量纲:广告每多 1 万元,销售额平均多 β 万元(控制其他变量);
- 适用范围:关系只在观测范围内可信,外推需谨慎;
- 离群值:OLS 对离群值敏感,必要时用稳健回归;
- 面试常问:为什么用最小二乘(残差平方和最小、估计无偏)、怎么判共线性(VIF>10)、R² vs 调整 R²。
📝 自测清单¶
- 能手写皮尔逊 r 并与 numpy/scipy 对照
- 能说出皮尔逊 vs 斯皮尔曼的适用场景
- 能手写一元 OLS(α、β 闭式解)
- 能写出正规方程并计算 R²
- 能解释多重共线性的危害与检测方法
- 能说清回归 ≠ 因果及系数解读要点