蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行离线同构房价回归 EDA、OLS 基线、标准化与多项式岭回归优化实验

PYTHONWindows 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。explore-house-price-prediction.py
explore-house-price-prediction.py270 行
"""Offline reproducible California-Housing-schema house price regression lab: EDA, OLS, StandardScaler, Ridge & chart."""
import argparse
import hashlib
import json
import platform
from pathlib import Path

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


def sha(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def build_offline_housing(n_samples: int = 4000, seed: int = 2026) -> tuple[pd.DataFrame, pd.Series]:
    """Generate deterministic California-Housing-schema dataset (8 numeric features + MedHouseVal, zero NaNs)."""
    rng = np.random.default_rng(seed)
    med_inc = np.clip(rng.gamma(shape=4.2, scale=0.95, size=n_samples), 0.6, 15.0)
    house_age = rng.integers(2, 53, size=n_samples).astype(float)
    ave_rooms = np.clip(3.2 + 0.55 * med_inc + rng.normal(0.0, 0.9, n_samples), 1.8, 12.0)
    # Collinear with AveRooms (realistic housing structure)
    ave_bedrms = np.clip(0.18 * ave_rooms + rng.normal(0.15, 0.14, n_samples), 0.6, 4.5)
    population = np.clip(rng.lognormal(mean=7.1, sigma=0.6, size=n_samples), 80.0, 9000.0)
    ave_occup = np.clip(rng.lognormal(mean=1.02, sigma=0.25, size=n_samples), 1.1, 8.5)
    latitude = rng.uniform(32.6, 41.8, size=n_samples)
    longitude = -124.2 + (41.8 - latitude) * 0.62 + rng.normal(0.0, 0.85, n_samples)

    # Structured pricing function (in $100k units, capped around 5.0 like California Housing)
    coastal_dist = np.abs(longitude - (-124.2 + (41.8 - latitude) * 0.62))
    raw_val = (
        0.52 * med_inc
        + 0.014 * house_age
        + 0.18 * ave_rooms
        - 0.35 * ave_bedrms
        - 0.00003 * population
        - 0.11 * ave_occup
        - 0.14 * (latitude - 36.5)
        - 0.22 * coastal_dist
        + 0.025 * (med_inc ** 2)
        - 0.015 * med_inc * ave_occup
        + 0.35
        + rng.normal(0.0, 0.38, n_samples)
    )
    med_house_val = np.round(np.clip(raw_val, 0.35, 5.0), 3)

    df_x = pd.DataFrame({
        "MedInc": np.round(med_inc, 4),
        "HouseAge": house_age,
        "AveRooms": np.round(ave_rooms, 4),
        "AveBedrms": np.round(ave_bedrms, 4),
        "Population": np.round(population, 1),
        "AveOccup": np.round(ave_occup, 4),
        "Latitude": np.round(latitude, 2),
        "Longitude": np.round(longitude, 2),
    })
    y = pd.Series(med_house_val, name="MedHouseVal")
    return df_x, y


def run_cases(fig_dir: Path | None):
    cases = []
    figures = {}

    df_features, y = build_offline_housing(n_samples=4000, seed=2026)
    df_all = pd.concat([df_features, y], axis=1)
    corr = df_all.corr()
    corr_target = corr["MedHouseVal"].drop("MedHouseVal")

    # 1. Data overview, missingness check & EDA correlation
    n_missing = int(df_features.isna().sum().sum())
    all_numeric = all(np.issubdtype(dt, np.number) for dt in df_features.dtypes)
    corr_medinc = round(float(corr_target["MedInc"]), 4)
    corr_rooms = round(float(corr_target["AveRooms"]), 4)
    corr_rooms_bedrms = round(float(corr.loc["AveRooms", "AveBedrms"]), 4)
    c1_ok = (
        df_features.shape == (4000, 8)
        and n_missing == 0
        and all_numeric
        and corr_medinc > 0.70
        and corr_rooms > 0.50
    )
    cases.append(dict(
        name="housing_data_and_eda",
        inputs=dict(n_samples=4000, n_features=8, target="MedHouseVal"),
        prerequisites="构建与 California Housing 同结构(8 个数值特征 + MedHouseVal)的 4,000 条离线房价表并执行缺失值与相关性检查。",
        action="验证零缺失值、全数值特征,且 MedInc 与 AveRooms 均与房价呈显著正相关。",
        expected=dict(shape=[4000, 8], zero_missing=True, strong_positive_corrs=True),
        actual=dict(
            shape=list(df_features.shape),
            zero_missing=(n_missing == 0 and all_numeric),
            strong_positive_corrs=(corr_medinc > 0.70 and corr_rooms > 0.50),
        ),
        measurements=dict(
            corr_medinc=corr_medinc, corr_averooms=corr_rooms,
            corr_rooms_bedrms=corr_rooms_bedrms,
            target_mean=round(float(y.mean()), 4), target_std=round(float(y.std()), 4),
        ),
        passed=c1_ok,
    ))

    # 2. 80/20 split & LinearRegression baseline
    X_train, X_test, y_train, y_test = train_test_split(df_features, y, test_size=0.2, random_state=42)
    ols = LinearRegression().fit(X_train, y_train)
    y_pred_ols = ols.predict(X_test)
    ols_mse = round(float(mean_squared_error(y_test, y_pred_ols)), 5)
    ols_rmse = round(float(np.sqrt(ols_mse)), 5)
    ols_mae = round(float(mean_absolute_error(y_test, y_pred_ols)), 5)
    ols_r2 = round(float(r2_score(y_test, y_pred_ols)), 5)
    coefs = {col: round(float(c), 4) for col, c in zip(df_features.columns, ols.coef_)}
    c2_ok = X_train.shape == (3200, 8) and X_test.shape == (800, 8) and ols_r2 >= 0.78 and ols_mse < 0.25
    cases.append(dict(
        name="housing_split_and_ols",
        inputs=dict(test_size=0.2, random_state=42),
        prerequisites="按 80/20 划分训练集(3,200)与测试集(800),拟合普通最小二乘线性回归并计算测试 MSE/RMSE/R²。",
        action="验证切分维度准确,线性回归在测试集上取得 MSE <0.25 且 R² >=0.78。",
        expected=dict(train_rows=3200, test_rows=800, r2_ge_078=True),
        actual=dict(train_rows=len(X_train), test_rows=len(X_test), r2_ge_078=(ols_r2 >= 0.78 and ols_mse < 0.25)),
        measurements=dict(
            intercept=round(float(ols.intercept_), 4), coefs=coefs,
            ols_mse=ols_mse, ols_rmse=ols_rmse, ols_mae=ols_mae, ols_r2=ols_r2,
        ),
        passed=c2_ok,
    ))

    # 3. StandardScaler (train-only fit) + Ridge(alpha=1.0) vs OLS invariance & L2 weight shrinkage
    scaler = StandardScaler()
    X_tr_sc = scaler.fit_transform(X_train)
    X_te_sc = scaler.transform(X_test)
    tr_max_mean_abs = round(float(np.max(np.abs(X_tr_sc.mean(axis=0)))), 8)
    tr_max_std_err = round(float(np.max(np.abs(X_tr_sc.std(axis=0) - 1.0))), 8)

    ols_sc = LinearRegression().fit(X_tr_sc, y_train)
    scale_pred_diff = round(float(np.max(np.abs(ols_sc.predict(X_te_sc) - y_pred_ols))), 8)

    ridge1 = Ridge(alpha=1.0).fit(X_tr_sc, y_train)
    y_pred_ridge1 = ridge1.predict(X_te_sc)
    ridge1_mse = round(float(mean_squared_error(y_test, y_pred_ridge1)), 5)
    ridge1_r2 = round(float(r2_score(y_test, y_pred_ridge1)), 5)
    ols_norm = round(float(np.linalg.norm(ols_sc.coef_)), 5)
    ridge_norm = round(float(np.linalg.norm(ridge1.coef_)), 5)

    c3_ok = (
        tr_max_mean_abs < 1e-6
        and tr_max_std_err < 1e-6
        and scale_pred_diff < 1e-6
        and ridge_norm < ols_norm
        and ridge1_r2 >= 0.78
    )
    cases.append(dict(
        name="housing_scaling_and_ridge",
        inputs=dict(scaler="StandardScaler", ridge_alpha=1.0),
        prerequisites="仅用训练集拟合 StandardScaler 并转换测试集,对比无正则 OLS 尺度不变性与 Ridge(alpha=1.0) L2 权重收缩。",
        action="验证训练集标准化后均值≈0/标准差≈1、OLS 线性缩放预测零差值,且 Ridge 权重 L2 范数严格收缩。",
        expected=dict(scaled_zero_mean_unit_std=True, ols_scale_invariant=True, ridge_shrank_norm=True),
        actual=dict(
            scaled_zero_mean_unit_std=(tr_max_mean_abs < 1e-6 and tr_max_std_err < 1e-6),
            ols_scale_invariant=(scale_pred_diff < 1e-6),
            ridge_shrank_norm=(ridge_norm < ols_norm),
        ),
        measurements=dict(
            ols_scaled_norm=ols_norm, ridge_alpha1_norm=ridge_norm,
            ridge1_mse=ridge1_mse, ridge1_r2=ridge1_r2, max_ols_scale_diff=scale_pred_diff,
        ),
        passed=c3_ok,
    ))

    # 4. Polynomial feature expansion + Ridge alpha sweep (nonlinear capture & overfitting suppression)
    poly_ols = make_pipeline(StandardScaler(), PolynomialFeatures(degree=2, include_bias=False), LinearRegression())
    poly_ols.fit(X_train, y_train)
    poly_ols_mse = round(float(mean_squared_error(y_test, poly_ols.predict(X_test))), 5)
    poly_ols_r2 = round(float(r2_score(y_test, poly_ols.predict(X_test))), 5)

    alpha_results = {}
    for a in [0.1, 1.0, 10.0, 100.0]:
        pipe = make_pipeline(StandardScaler(), PolynomialFeatures(degree=2, include_bias=False), Ridge(alpha=a))
        pipe.fit(X_train, y_train)
        pred_a = pipe.predict(X_test)
        alpha_results[str(a)] = dict(
            mse=round(float(mean_squared_error(y_test, pred_a)), 5),
            r2=round(float(r2_score(y_test, pred_a)), 5),
        )
    best_poly_pipe = make_pipeline(StandardScaler(), PolynomialFeatures(degree=2, include_bias=False), Ridge(alpha=10.0)).fit(X_train, y_train)
    best_pred = best_poly_pipe.predict(X_test)
    best_mse = round(float(mean_squared_error(y_test, best_pred)), 5)
    best_r2 = round(float(r2_score(y_test, best_pred)), 5)
    resid_mean = round(float(np.mean(y_test.values - best_pred)), 5)

    c4_ok = best_mse < ols_mse and best_r2 > ols_r2 and abs(resid_mean) < 0.05
    cases.append(dict(
        name="housing_poly_ridge_sweep",
        inputs=dict(poly_degree=2, alphas=[0.1, 1.0, 10.0, 100.0]),
        prerequisites="在二次多项式交互特征上执行 Ridge 岭回归 alpha 扫描,并与线性基线比较测试误差与残差均值。",
        action="验证二次特征 + Ridge(alpha=10) 将测试 MSE 进一步压低、R² 超过线性基线且残差均值接近 0。",
        expected=dict(poly_ridge_beats_ols=True, residual_unbiased=True),
        actual=dict(
            poly_ridge_beats_ols=(best_mse < ols_mse and best_r2 > ols_r2),
            residual_unbiased=(abs(resid_mean) < 0.05),
        ),
        measurements=dict(
            poly_ols_mse=poly_ols_mse, poly_ols_r2=poly_ols_r2,
            alpha_sweep=alpha_results, best_poly_ridge_mse=best_mse,
            best_poly_ridge_r2=best_r2, residual_mean=resid_mean,
        ),
        passed=c4_ok,
    ))

    # 5. Matplotlib figure: Feature correlation with MedHouseVal + Actual vs Predicted scatter
    if fig_dir is not None:
        import matplotlib
        matplotlib.use("Agg")
        import matplotlib.pyplot as plt
        fig_dir.mkdir(parents=True, exist_ok=True)
        fig, axes = plt.subplots(1, 2, figsize=(9.6, 3.8), dpi=140)

        corr_sorted = corr_target.sort_values()
        colors = ["#ae511d" if v < 0 else "#174d79" for v in corr_sorted.values]
        axes[0].barh(corr_sorted.index, corr_sorted.values, color=colors)
        axes[0].axvline(0.0, color="#333333", linewidth=0.8)
        axes[0].set_xlim(-0.6, 1.0)
        axes[0].set_xlabel("Pearson Correlation with MedHouseVal")
        axes[0].set_title("Feature Correlation with House Price", fontsize=10)
        axes[0].grid(axis="x", alpha=0.3)

        axes[1].scatter(y_test.values, best_pred, s=12, alpha=0.45, color="#174d79", label="Poly-Ridge (alpha=10)")
        axes[1].plot([0.3, 5.1], [0.3, 5.1], linestyle="--", color="#ae511d", linewidth=1.4, label="Ideal y = x")
        axes[1].set_xlabel("Actual MedHouseVal ($100k)")
        axes[1].set_ylabel("Predicted MedHouseVal ($100k)")
        axes[1].set_title(f"Held-Out Test Predictions (R2={best_r2:.3f}, MSE={best_mse:.3f})", fontsize=10)
        axes[1].grid(True, alpha=0.3)
        axes[1].legend(fontsize=8)

        fig.tight_layout()
        out_png = fig_dir / "house-price-regression.png"
        fig.savefig(out_png)
        plt.close(fig)
        figures["house-price-regression.png"] = sha(out_png)
        mpl_ver = matplotlib.__version__
    else:
        mpl_ver = None

    cases.append(dict(
        name="observed_house_price_chart",
        inputs=dict(panels=2, test_points=len(y_test)),
        prerequisites="基于特征相关性向量与 800 条留出测试集预测值绘制相关性条形图与真实-预测散点图。",
        action="验证生成双栏 Matplotlib PNG 图表并校验文件哈希。",
        expected=dict(panels=2, points_plotted=800),
        actual=dict(panels=2, points_plotted=len(y_test)),
        measurements=dict(figure_generated="house-price-regression.png" in figures),
        passed=len(y_test) == 800,
    ))

    payload = dict(version=platform.python_version(), system=platform.system(), cases=cases)
    if mpl_ver:
        payload["matplotlib"] = mpl_ver
        payload["figures"] = figures
    print(json.dumps(payload, ensure_ascii=False))


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--figures", type=Path, default=None)
    args = parser.parse_args()
    run_cases(args.figures)
本例需在 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-house-price-prediction-lab/explore-house-price-prediction.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-house-price-prediction.py,或下载右侧课程工程包。
  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。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:机器学习

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a472.zip

下载课程关联工程包:机器学习

课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习