"""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()
本例需在 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。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境: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。
入口文件:projects/ml-multiple-linear-regression-lab/explore-multiple-linear-regression.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-multiple-linear-regression.py,或下载右侧课程工程包。 - 确认本地已准备 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。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a489.zip