蓝色天空网mbsky.com · 知识 · 实践 · 创造机器学习 · 本地阅读预览
教程 / AI / 智能开发 / 机器学习

多元线性回归

核对多元线性回归模型公式、矩阵闭合解、糖尿病离线数据集建模、多重共线性诊断与岭回归稳定化,以及过拟合与非线性局限实测。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

多元线性回归概念、公式与系数解读

现实预测任务(如房价受面积、卧室数量、地理位置与房龄共同影响)往往依赖多个自变量,多元线性回归正是简单线性回归向多特征的自然扩展,用来刻画多个特征与单个连续目标之间的联合线性关系,如同调配多种调料共同决定汤的味道并分别量化每种调料的边际贡献。

多元模型写作 y = β₀ + β₁x₁ + β₂x₂ + ... + βₙxₙ + ε,各符号含义见下表。以房价模型 50000 + 3000*面积 + 10000*卧室数 - 2000*房龄 为例:β₀ = 50000 为各特征取 0 时的理论截距基准;β₁ = 3000 表示固定卧室数和房龄时面积每增 1 ㎡ 房价均涨 3000 元;β₂ = 10000 表示多一间卧室均涨 10000 元;β₃ = -2000 表示房龄每增一年均降 2000 元(前提是其他自变量保持不变)。

残差平方和与矩阵闭合解

训练多元线性回归的核心是在训练集上最小化残差平方和 RSS = Σ(yᵢ - ŷᵢ)²。用设计矩阵 X(首列全 1 对应 β₀,其余各列对应特征)、目标列向量 Y、系数向量 β 与误差向量 ε 可写作 Y = Xβ + ε;当 XᵀX 满秩可逆时,最小二乘闭合解为 β = (XᵀX)⁻¹XᵀY。工程上 scikit-learn 采用数值更稳定的奇异值分解/最小二乘求解器,避免直接显式求逆带来的病态误差。本站对 300 条三特征模拟房价数据按 70/30 划分实测,矩阵方程解与 LinearRegression 最大系数差仅 1.15e-09,拟合得截距 52705.83、系数 [2976.03, 10056.48, -2031.04],留出测试 R² = 0.9952、RMSE = 8863.25。

scikit-learn 多特征建模与离线数据集实测

来源示例演示使用 fetch_california_housing() 加载加州房价并经 pandas 探索及 train_test_split 70/30 切分;由于 fetch_california_housing 需联网下载外部压缩包,本站在离线隔离环境中改用 scikit-learn 内置的 load_diabetes(as_frame=True)(442 条样本、10 个连续特征,同步覆盖练习 3),在 70/30 划分下完成探索、拟合与留出检验。

在糖尿病数据集上,LinearRegression 实测训练 MSE = 2924.05(R² = 0.5244)、留出测试 MSE = 2821.75(R² = 0.4773),训练集残差均值精确归零(<1e-10)。系数解读需注意特征量纲:糖尿病数据集特征已做标准化缩放,因此可直接比较系数绝对值(正向最大 s5 系数 659.27,负向最大 s1 系数 -901.96);若特征单位不同(如面积与房龄),不能直接拿未标准化回归系数绝对值代表特征重要性。

统计假设、共线性/过拟合挑战与练习验证

经典多元线性回归推断依赖五项统计假设:线性关系、观测独立性、误差同方差性、误差正态性及无多重共线性。下表汇总多重共线性、过拟合与非线性关系三大常见挑战的成因与应对策略。

针对文末三项练习,本站全部在离线环境实测落地:(1)系数解读与符号核验已于模拟房价与糖尿病数据集完成;(2)多重共线性诊断中,构造相关性 |r| = 0.999997(>0.7)的特征对 (z1, z2_collinear),OLS 系数发生剧烈震荡且符号反转至 [-12.228, 7.631, -1.454](系数 L2 范数 14.487),移除冗余列后范数降至 3.363(测试 R² = 0.9786),改用训练集内拟合的 StandardScaler + Ridge(alpha=1.0) 范数降至 2.626(测试 R² = 0.9785);(3)额外注入 60 列纯噪声特征使训练 R² 从 0.8642 虚涨至 0.9576,但测试 MSE 由 0.4582 恶化至 1.6720;对二次曲线数据直接线性拟合测试 R² 仅 0.3732,引入二次特征后跃升至 0.9851。

多元线性回归模型符号说明

符号名称含义
y因变量待预测的连续型目标值(如房价或疾病进展指标)。
x₁, x₂, ..., xₙ自变量用于预测目标的多个输入特征(如面积、卧室数、房龄)。
β₀截距项所有自变量同时为 0 时的理论预测基准值。
β₁, β₂, ..., βₙ回归系数控制其余特征不变时,xᵢ 每增加 1 个单位引起 y 的平均变化量。
ε误差项模型未能解释的随机测量误差与未观测扰动。

多元线性回归三大常见挑战与应对策略

挑战描述可能后果应对方法
多重共线性自变量之间存在高度线性相关(如 |r|>0.7)OLS 系数估计剧烈不稳定甚至符号反转(本站实测范数膨胀至 14.487)计算训练集相关矩阵删冗余特征、PCA 降维或采用 Ridge 正则化
过拟合无关特征过多导致拟合训练集噪声训练 R² 虚高但测试 MSE 暴涨(实测 60 噪声列使测试 MSE 增至 3.6 倍)增加样本量、执行特征选择或引入 L1/L2 正则化
非线性关系特征与目标的真实关系呈弯曲非线性线性模型欠拟合、测试 R² 偏低(实测二次数据仅 0.3732)构造多项式/对数等非线性特征变换,或改用树模型/神经网络

运行多元线性回归矩阵闭合解、糖尿病数据集与多重共线性/过拟合对比实验

python · 阅读源码
"""Independent scikit-learn 1.9.1 lab for Multiple Linear Regression, Multicollinearity & Ridge."""
import json
import platform

import numpy as np
import pandas as pd
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.metrics import mean_squared_error, r2_score, root_mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler


def run_cases():
    cases = []

    # 1. Controlled multi-feature housing simulation: closed-form (X^T X)^{-1} X^T Y vs sklearn
    rng = np.random.default_rng(42)
    n = 300
    area = rng.uniform(40.0, 180.0, size=n)
    bedrooms = rng.integers(1, 6, size=n).astype(float)
    age = rng.uniform(0.0, 35.0, size=n)
    noise = rng.normal(0.0, 8000.0, size=n)
    price = 50000.0 + 3000.0 * area + 10000.0 * bedrooms - 2000.0 * age + noise

    df_house = pd.DataFrame(dict(area=area, bedrooms=bedrooms, age=age))
    x_tr, x_te, y_tr, y_te = train_test_split(df_house, price, test_size=0.3, random_state=42)

    x_design = np.column_stack([np.ones(len(x_tr)), x_tr.to_numpy()])
    beta_cf = np.linalg.solve(x_design.T @ x_design, x_design.T @ y_tr)

    lr_house = LinearRegression().fit(x_tr, y_tr)
    beta_sk = np.concatenate([[lr_house.intercept_], lr_house.coef_])
    max_diff = float(np.max(np.abs(beta_cf - beta_sk)))

    pred_te = lr_house.predict(x_te)
    house_r2 = float(r2_score(y_te, pred_te))
    house_rmse = float(root_mean_squared_error(y_te, pred_te))
    signs_ok = bool(lr_house.coef_[0] > 0 and lr_house.coef_[1] > 0 and lr_house.coef_[2] < 0)
    c1_ok = bool(max_diff < 1e-6 and signs_ok and house_r2 > 0.98)
    cases.append(dict(
        name="closed_form_housing_simulation",
        inputs=dict(n_samples=n, test_size=0.3, true_beta=[50000.0, 3000.0, 10000.0, -2000.0]),
        prerequisites="构建含面积、卧室数、房龄三特征的模拟房价数据集,先 70/30 划分再拟合。",
        action="验证矩阵闭合解 (X^T X)^-1 X^T Y 与 LinearRegression 一致、系数符号符合真实关系且测试 R² >0.98。",
        expected=dict(closed_form_matches=True, coef_signs_correct=True, test_r2_gt_098=True),
        actual=dict(closed_form_matches=max_diff < 1e-6, coef_signs_correct=signs_ok, test_r2_gt_098=house_r2 > 0.98),
        measurements=dict(
            intercept=round(float(lr_house.intercept_), 2),
            coefs=[round(float(c), 2) for c in lr_house.coef_],
            max_beta_diff=float(f"{max_diff:.2e}"),
            test_r2=round(house_r2, 4),
            test_rmse=round(house_rmse, 2),
        ),
        passed=c1_ok,
    ))

    # 2. Offline built-in load_diabetes() multivariate regression workflow (fulfills Exercise 3 offline)
    diab = load_diabetes(as_frame=True)
    xd, yd = diab.data, diab.target
    xd_tr, xd_te, yd_tr, yd_te = train_test_split(xd, yd, test_size=0.3, random_state=42)
    lr_diab = LinearRegression().fit(xd_tr, yd_tr)
    diab_tr_mse = float(mean_squared_error(yd_tr, lr_diab.predict(xd_tr)))
    diab_te_mse = float(mean_squared_error(yd_te, lr_diab.predict(xd_te)))
    diab_tr_r2 = float(r2_score(yd_tr, lr_diab.predict(xd_tr)))
    diab_te_r2 = float(r2_score(yd_te, lr_diab.predict(xd_te)))
    diab_res_mean = abs(float(np.mean(yd_tr - lr_diab.predict(xd_tr))))

    top_pos_idx = int(np.argmax(lr_diab.coef_))
    top_neg_idx = int(np.argmin(lr_diab.coef_))
    c2_ok = xd.shape == (442, 10) and diab_te_r2 > 0.45 and diab_res_mean < 1e-10
    cases.append(dict(
        name="diabetes_multivariate_regression",
        inputs=dict(dataset="load_diabetes", n_samples=442, n_features=10, test_size=0.3),
        prerequisites="离线加载 sklearn 内置糖尿病回归数据集(442×10),70/30 划分后训练多元线性回归。",
        action="输出训练/测试 MSE 与 R²、最大正负回归系数及训练集零均值残差检查。",
        expected=dict(shape_442_10=True, test_r2_gt_045=True, train_residual_zero_mean=True),
        actual=dict(shape_442_10=(xd.shape == (442, 10)), test_r2_gt_045=diab_te_r2 > 0.45, train_residual_zero_mean=diab_res_mean < 1e-10),
        measurements=dict(
            train_mse=round(diab_tr_mse, 2),
            test_mse=round(diab_te_mse, 2),
            train_r2=round(diab_tr_r2, 4),
            test_r2=round(diab_te_r2, 4),
            top_pos_feature=diab.feature_names[top_pos_idx],
            top_pos_coef=round(float(lr_diab.coef_[top_pos_idx]), 2),
            top_neg_feature=diab.feature_names[top_neg_idx],
            top_neg_coef=round(float(lr_diab.coef_[top_neg_idx]), 2),
        ),
        passed=c2_ok,
    ))

    # 3. Multicollinearity diagnosis via correlation matrix & stabilization via feature drop / Ridge
    z1 = rng.normal(0.0, 1.0, size=240)
    z2 = 2.0 * z1 + rng.normal(0.0, 0.005, size=240)  # collinear with z1
    z3 = rng.normal(0.0, 1.0, size=240)
    ym = 3.0 * z1 - 1.5 * z3 + rng.normal(0.0, 0.5, size=240)
    df_mc = pd.DataFrame(dict(z1=z1, z2_collinear=z2, z3=z3))
    xm_tr, xm_te, ym_tr, ym_te = train_test_split(df_mc, ym, test_size=0.3, random_state=42)

    corr_tr = xm_tr.corr()
    pair_corr = float(abs(corr_tr.loc["z1", "z2_collinear"]))

    ols_mc = LinearRegression().fit(xm_tr, ym_tr)
    ols_l2 = float(np.linalg.norm(ols_mc.coef_))
    ols_r2 = float(r2_score(ym_te, ols_mc.predict(xm_te)))

    # Dropping redundant collinear feature
    ols_drop = LinearRegression().fit(xm_tr[["z1", "z3"]], ym_tr)
    drop_l2 = float(np.linalg.norm(ols_drop.coef_))
    drop_r2 = float(r2_score(ym_te, ols_drop.predict(xm_te[["z1", "z3"]])))

    # Ridge regularization inside Pipeline (StandardScaler fit strictly on train)
    ridge_pipe = make_pipeline(StandardScaler(), Ridge(alpha=1.0)).fit(xm_tr, ym_tr)
    ridge_l2 = float(np.linalg.norm(ridge_pipe.named_steps["ridge"].coef_))
    ridge_r2 = float(r2_score(ym_te, ridge_pipe.predict(xm_te)))

    c3_ok = pair_corr > 0.99 and ridge_l2 < ols_l2 and drop_l2 < ols_l2 and ridge_r2 > 0.95 and drop_r2 > 0.95
    cases.append(dict(
        name="multicollinearity_diagnosis_and_ridge",
        inputs=dict(n_samples=240, collinear_noise=0.005, ridge_alpha=1.0),
        prerequisites="构造高度共线特征对 (|r|>0.99),仅在训练集计算相关性矩阵并对比 OLS、删特征与 Ridge。",
        action="验证相关矩阵检出共线性(|r|>0.7),且删去冗余特征或施加 Ridge 均显著压低系数范数并保持测试 R² >0.95。",
        expected=dict(collinear_detected=True, ridge_shrinks_norm=True, drop_shrinks_norm=True, stabilized_r2_gt_095=True),
        actual=dict(
            collinear_detected=pair_corr > 0.7,
            ridge_shrinks_norm=ridge_l2 < ols_l2,
            drop_shrinks_norm=drop_l2 < ols_l2,
            stabilized_r2_gt_095=(ridge_r2 > 0.95 and drop_r2 > 0.95),
        ),
        measurements=dict(
            train_corr_z1_z2=round(pair_corr, 6),
            ols_coefs=[round(float(c), 3) for c in ols_mc.coef_],
            ols_coef_l2=round(ols_l2, 3),
            drop_coef_l2=round(drop_l2, 3),
            ridge_coef_l2=round(ridge_l2, 3),
            ols_test_r2=round(ols_r2, 4),
            drop_test_r2=round(drop_r2, 4),
            ridge_test_r2=round(ridge_r2, 4),
        ),
        passed=c3_ok,
    ))

    # 4. Overfitting with noisy extra features & Nonlinear limitation fixed by quadratic feature
    xo = rng.normal(0.0, 1.0, size=(120, 62))
    yo = 2.0 * xo[:, 0] - 1.5 * xo[:, 1] + rng.normal(0.0, 0.8, size=120)
    xo_tr, xo_te, yo_tr, yo_te = train_test_split(xo, yo, test_size=0.3, random_state=42)
    lr_clean = LinearRegression().fit(xo_tr[:, :2], yo_tr)
    lr_noisy = LinearRegression().fit(xo_tr, yo_tr)
    clean_tr_r2 = float(r2_score(yo_tr, lr_clean.predict(xo_tr[:, :2])))
    noisy_tr_r2 = float(r2_score(yo_tr, lr_noisy.predict(xo_tr)))
    clean_te_mse = float(mean_squared_error(yo_te, lr_clean.predict(xo_te[:, :2])))
    noisy_te_mse = float(mean_squared_error(yo_te, lr_noisy.predict(xo_te)))

    xnl = rng.uniform(-3.0, 3.0, size=(150, 1))
    ynl = 1.5 * (xnl[:, 0] ** 2) - 0.5 * xnl[:, 0] + rng.normal(0.0, 0.4, size=150)
    xnl_tr, xnl_te, ynl_tr, ynl_te = train_test_split(xnl, ynl, test_size=0.3, random_state=42)
    r2_lin_only = float(r2_score(ynl_te, LinearRegression().fit(xnl_tr, ynl_tr).predict(xnl_te)))
    xnl_tr_q = np.column_stack([xnl_tr, xnl_tr ** 2])
    xnl_te_q = np.column_stack([xnl_te, xnl_te ** 2])
    r2_with_quad = float(r2_score(ynl_te, LinearRegression().fit(xnl_tr_q, ynl_tr).predict(xnl_te_q)))

    c4_ok = noisy_tr_r2 > clean_tr_r2 and noisy_te_mse > clean_te_mse * 2.0 and r2_lin_only < 0.45 and r2_with_quad > 0.95
    cases.append(dict(
        name="nonlinear_limitation_and_overfitting_check",
        inputs=dict(overfit_noise_features=60, nonlinear_samples=150),
        prerequisites="分别构造 60 个无关噪声特征(过拟合)与二次曲线数据(非线性关系)。",
        action="验证噪声特征推高训练 R² 却使测试 MSE 翻倍以上;线性模型拟合二次数据测试 R² <0.45,补入二次项后跃升至 >0.95。",
        expected=dict(overfit_pattern_observed=True, nonlinear_fixed_by_quad=True),
        actual=dict(
            overfit_pattern_observed=(noisy_tr_r2 > clean_tr_r2 and noisy_te_mse > clean_te_mse * 2.0),
            nonlinear_fixed_by_quad=(r2_lin_only < 0.45 and r2_with_quad > 0.95),
        ),
        measurements=dict(
            clean_train_r2=round(clean_tr_r2, 4),
            noisy_train_r2=round(noisy_tr_r2, 4),
            clean_test_mse=round(clean_te_mse, 4),
            noisy_test_mse=round(noisy_te_mse, 4),
            linear_only_test_r2=round(r2_lin_only, 4),
            quadratic_test_r2=round(r2_with_quad, 4),
        ),
        passed=c4_ok,
    ))

    print(json.dumps(dict(version=platform.python_version(), system=platform.system(), cases=cases), ensure_ascii=False))


if __name__ == "__main__":
    run_cases()
预期结果 · 待实际运行核验
  • 核对三特征房价矩阵闭合解与 sklearn 差 <1e-6、load_diabetes 留出 MSE/R²、高共线特征对经删列与 Ridge 压低系数范数,以及噪声过拟合与二次项修正效果。
运行多元线性回归矩阵闭合解、糖尿病数据集与多重共线性/过拟合对比实验

所需环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。

当前源码 SHA256:83d58a0c152f85508718350752c96959c3d63d7d737e259bfbc4a70f79a6a2a4

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载多元线性回归实验

所需环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。

ZIP SHA256:2ea5f4e2323522f1e19831280c092a06be61323c988d2abdd818e192e05ca6a1

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么在特征量纲不同(如面积单位平方米、房龄单位年)时,不能直接用多元线性回归原始系数的绝对值排序作为特征重要性?

展开参考解答

系数 βᵢ 的数值随特征单位缩放而反比变化(把面积从平方米换算为平方厘米会使系数缩小 10000 倍);只有先在训练集上执行标准化(StandardScaler)或在同等无量纲尺度下,系数绝对值才具可比性。

规范与官方依据