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

运行脏数据检查、特征派生、多项式复杂度对比、手动梯度下降与五模型对照实验

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-basics.py
explore-basics.py213 行
"""Independent offline ML basics terminology lab: data quality, feature eng, complexity, GD, inference & classic models."""
import json
import platform

import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier


def run_cases():
    cases = []

    # 1. Structured vs unstructured data & data quality ("Garbage In, Garbage Out")
    students_df = pd.DataFrame({
        "姓名": ["张三", "李四", "王五"],
        "年龄": [18, 19, 20],
        "成绩": [85, 92, 78],
        "班级": ["一班", "二班", "一班"],
    })
    problematic_df = pd.DataFrame({
        "价格": [100, 200, None, 300, -50],
        "评分": [4.5, "好", 3.8, 4.2, 5.0],
        "销量": [1000, 1200, 800, 1500, "很多"],
    })
    raw_nulls = int(problematic_df.isna().sum().sum())
    neg_prices = int((pd.to_numeric(problematic_df["价格"], errors="coerce") < 0).sum())
    # Coerce mixed columns to numeric to surface hidden invalid strings as NaN
    cleaned_rating = pd.to_numeric(problematic_df["评分"], errors="coerce")
    cleaned_sales = pd.to_numeric(problematic_df["销量"], errors="coerce")
    coerced_invalids = int(cleaned_rating.isna().sum() + cleaned_sales.isna().sum())
    c1_ok = students_df.shape == (3, 4) and raw_nulls == 1 and neg_prices == 1 and coerced_invalids == 2
    cases.append(dict(
        name="structured_unstructured_and_data_quality",
        inputs=dict(students_rows=3, problematic_rows=5),
        prerequisites="学生结构化表与含缺失、负价格、类型混杂的脏数据表",
        action="统计原始缺失值、负价格异常数,并通过 pd.to_numeric(errors='coerce') 暴露混杂字符串为无效值。",
        expected=dict(student_shape=[3, 4], raw_nulls=1, negative_prices=1, mixed_string_invalids=2),
        actual=dict(student_shape=list(students_df.shape), raw_nulls=raw_nulls, negative_prices=neg_prices, mixed_string_invalids=coerced_invalids),
        measurements=dict(raw_dtypes={k: str(v) for k, v in problematic_df.dtypes.items()}),
        passed=c1_ok,
    ))

    # 2. Feature types, house feature engineering & label standardization
    house_df = pd.DataFrame({
        "面积": [80, 120, 60, 150, 90],
        "卧室数": [2, 3, 1, 4, 2],
        "建造年份": [2000, 2010, 1995, 2015, 2005],
        "价格": [200, 350, 150, 500, 280],
    })
    house_df["房龄"] = 2023 - house_df["建造年份"]
    house_df["每平米价格"] = house_df["价格"] / house_df["面积"]
    house_df["卧室面积比"] = house_df["卧室数"] / house_df["面积"] * 100.0
    corrs = {k: round(float(v), 4) for k, v in house_df.corr()["价格"].items()}

    raw_labels = ["猫", "犬", "猫咪", "狗"]
    mapping = {"猫": "cat", "猫咪": "cat", "犬": "dog", "狗": "dog"}
    std_labels = [mapping[x] for x in raw_labels]
    c2_ok = bool(
        house_df.shape == (5, 7)
        and corrs["面积"] > 0.98
        and corrs["房龄"] < -0.95
        and std_labels == ["cat", "dog", "cat", "dog"]
    )
    cases.append(dict(
        name="features_engineering_and_label_standardization",
        inputs=dict(houses=5, raw_labels=raw_labels),
        prerequisites="房屋原始 4 列特征派生房龄/单价/卧室占比与非一致标签归一化映射",
        action="验证派生特征与价格的相关性(面积强正相关、房龄强负相关)及同义标签统一为 cat/dog。",
        expected=dict(derived_cols=7, standardized_labels=["cat", "dog", "cat", "dog"]),
        actual=dict(derived_cols=house_df.shape[1], standardized_labels=std_labels),
        measurements=dict(price_correlations=corrs),
        passed=c2_ok,
    ))

    # 3. Linear model representation & complexity tradeoff (degree 1 vs 5 vs 10 vs 15 on [0, 10] sin(x))
    x_lin = np.array([1, 2, 3, 4, 5], dtype=float)
    y_lin_pred = (2.0 * x_lin + 0.0).tolist()

    np.random.seed(42)
    X_nl = np.random.rand(20, 1) * 10.0
    y_nl = np.sin(X_nl) + np.random.randn(20, 1) * 0.1
    X_grid = np.linspace(0.0, 10.0, 100).reshape(-1, 1)
    y_grid_true = np.sin(X_grid)

    mses = {}
    x_tr_scaled = (X_nl - 5.0) / 5.0
    x_gr_scaled = (X_grid - 5.0) / 5.0
    for deg in (1, 5, 10, 15):
        pf = PolynomialFeatures(degree=deg, include_bias=False)
        Xp_tr = pf.fit_transform(x_tr_scaled)
        Xp_te = pf.transform(x_gr_scaled)
        m = LinearRegression().fit(Xp_tr, y_nl)
        tr_mse = round(float(mean_squared_error(y_nl, m.predict(Xp_tr))), 5)
        te_mse = round(float(mean_squared_error(y_grid_true, m.predict(Xp_te))), 5)
        mses[f"deg{deg}"] = dict(train_mse=tr_mse, test_mse=te_mse)
    c3_ok = bool(
        y_lin_pred == [2.0, 4.0, 6.0, 8.0, 10.0]
        and mses["deg15"]["train_mse"] < mses["deg5"]["train_mse"] < mses["deg1"]["train_mse"]
        and mses["deg15"]["test_mse"] > mses["deg5"]["test_mse"] * 5.0
    )
    cases.append(dict(
        name="linear_model_and_complexity_tradeoff",
        inputs=dict(train_points=20, degrees=[1, 5, 10, 15]),
        prerequisites="线性函数 y=2x 与含噪正弦曲线 [0,10] 上 1/5/10/15 次多项式复杂度对比",
        action="验证 1 次线性欠拟合、5 次与 10 次多项式在标准化后拟合正弦波,而 15 次过高阶多项式训练 MSE 最低却在测试网格上剧烈过拟合。",
        expected=dict(linear_preds=[2.0, 4.0, 6.0, 8.0, 10.0], deg15_severe_overfit=True),
        actual=dict(linear_preds=y_lin_pred, deg15_severe_overfit=bool(mses["deg15"]["test_mse"] > mses["deg5"]["test_mse"] * 5.0)),
        measurements=mses,
        passed=c3_ok,
    ))

    # 4. Manual GD training (100 epochs) & HousePriceModel single/batch inference
    np.random.seed(42)
    X_gd = np.random.rand(50, 1) * 10.0
    y_gd = 3.0 * X_gd + 2.0 + np.random.randn(50, 1) * 2.0
    w, b = 0.0, 0.0
    loss_hist = []
    for _ in range(100):
        yp = w * X_gd + b
        loss_hist.append(float(np.mean((yp - y_gd) ** 2)))
        dw = float(np.mean(2.0 * X_gd * (yp - y_gd)))
        db = float(np.mean(2.0 * (yp - y_gd)))
        w -= 0.01 * dw
        b -= 0.01 * db

    weights = {"面积": 2.5, "卧室数": 10.0, "房龄": -1.0, "地段评分": 50.0}
    bias = 50.0
    new_houses = [
        {"面积": 80, "卧室数": 2, "房龄": 5, "地段评分": 8},
        {"面积": 120, "卧室数": 3, "房龄": 2, "地段评分": 9},
        {"面积": 60, "卧室数": 1, "房龄": 10, "地段评分": 6},
    ]
    batch_prices = [bias + sum(weights[k] * v for k, v in h.items()) for h in new_houses]
    c4_ok = loss_hist[-1] < 5.0 and batch_prices == [665.0, 828.0, 500.0]
    cases.append(dict(
        name="manual_gd_training_and_inference",
        inputs=dict(gd_samples=50, epochs=100, lr=0.01, infer_houses=3),
        prerequisites="手动梯度下降训练 100 轮与已知权重房价推理器批量预测",
        action="验证训练损失由初始高位降至 <5.0,并核对 3 套新房批量推理结果为 [665.0, 828.0, 500.0] 万元。",
        expected=dict(final_loss_lt_5=True, batch_prices=[665.0, 828.0, 500.0]),
        actual=dict(final_loss_lt_5=loss_hist[-1] < 5.0, batch_prices=batch_prices),
        measurements=dict(
            epoch0_loss=round(loss_hist[0], 4),
            epoch99_loss=round(loss_hist[-1], 4),
            learned_w=round(w, 4),
            learned_b=round(b, 4),
        ),
        passed=c4_ok,
    ))

    # 5. End-to-end 200-sample housing LinearRegression + 5 classic ML classifiers from Table 0
    np.random.seed(42)
    n_s = 200
    area = np.random.normal(100, 30, n_s)
    bedrooms = np.random.randint(1, 5, n_s)
    age = np.random.randint(0, 20, n_s)
    loc = np.random.randint(1, 10, n_s)
    price = area * 2.5 + bedrooms * 20 + age * -2 + loc * 15 + np.random.normal(0, 50, n_s)
    df_e2e = pd.DataFrame({"面积": area, "卧室数": bedrooms, "房龄": age, "地段评分": loc, "价格": price})
    feats = ["面积", "卧室数", "房龄", "地段评分"]
    Xe_tr, Xe_te, ye_tr, ye_te = train_test_split(df_e2e[feats], df_e2e["价格"], test_size=0.2, random_state=42)
    e2e_lr = LinearRegression().fit(Xe_tr, ye_tr)
    tr_r2 = round(float(r2_score(ye_tr, e2e_lr.predict(Xe_tr))), 4)
    te_r2 = round(float(r2_score(ye_te, e2e_lr.predict(Xe_te))), 4)
    te_mse = round(float(mean_squared_error(ye_te, e2e_lr.predict(Xe_te))), 2)
    infer_df = pd.DataFrame({"面积": [85, 120, 65], "卧室数": [2, 3, 1], "房龄": [3, 1, 8], "地段评分": [7, 9, 5]})
    infer_preds = [round(float(v), 2) for v in e2e_lr.predict(infer_df)]

    # Classic models benchmark (DT, RF, LR, SVM, NB) on binary price>median classification
    y_bin = (df_e2e["价格"] > df_e2e["价格"].median()).astype(int)
    Xc_tr, Xc_te, yc_tr, yc_te = train_test_split(df_e2e[feats], y_bin, test_size=0.25, random_state=42, stratify=y_bin)
    sc_c = StandardScaler().fit(Xc_tr)
    Xc_tr_s, Xc_te_s = sc_c.transform(Xc_tr), sc_c.transform(Xc_te)
    classic_accs = {
        "DT": round(float(DecisionTreeClassifier(max_depth=4, random_state=42).fit(Xc_tr, yc_tr).score(Xc_te, yc_te)), 4),
        "RF": round(float(RandomForestClassifier(n_estimators=80, random_state=42).fit(Xc_tr, yc_tr).score(Xc_te, yc_te)), 4),
        "LR": round(float(LogisticRegression(random_state=42).fit(Xc_tr_s, yc_tr).score(Xc_te_s, yc_te)), 4),
        "SVM": round(float(SVC(random_state=42).fit(Xc_tr_s, yc_tr).score(Xc_te_s, yc_te)), 4),
        "NB": round(float(GaussianNB().fit(Xc_tr_s, yc_tr).score(Xc_te_s, yc_te)), 4),
    }
    c5_ok = bool(tr_r2 > 0.70 and te_r2 > 0.50 and all(v >= 0.70 for v in classic_accs.values()) and len(infer_preds) == 3)
    cases.append(dict(
        name="end_to_end_housing_and_classic_models",
        inputs=dict(samples=200, train_size=160, test_size=40),
        prerequisites="200 条四特征房价端到端回归与 5 种传统分类模型(DT/RF/LR/SVM/NB)对照",
        action="拟合多元线性回归评估训练/测试集 MSE 与 R² 并预测 3 套新房,同时核对 5 种传统分类模型均可稳定运行。",
        expected=dict(train_r2_gt_070=True, test_r2_gt_050=True, all_five_classic_ge_070=True),
        actual=dict(train_r2_gt_070=bool(tr_r2 > 0.70), test_r2_gt_050=bool(te_r2 > 0.50), all_five_classic_ge_070=all(v >= 0.70 for v in classic_accs.values())),
        measurements=dict(
            train_r2=tr_r2,
            test_r2=te_r2,
            test_mse=te_mse,
            coefs=[round(float(c), 2) for c in e2e_lr.coef_],
            intercept=round(float(e2e_lr.intercept_), 2),
            new_house_preds=infer_preds,
            classic_model_accs=classic_accs,
        ),
        passed=c5_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-basics-lab/explore-basics.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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