"""Independent offline ML tutorial lab: house price linear regression, paradigm comparison & chart."""
import argparse
import hashlib
import json
import platform
from pathlib import Path
import numpy as np
from sklearn.cluster import KMeans
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
def sha(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def run_cases(fig_dir: Path | None):
cases = []
figures = {}
# 1. Exact house price linear regression + noisy train/test generalization
house_sizes = np.array([50, 60, 70, 80, 90, 100, 110, 120], dtype=float).reshape(-1, 1)
house_prices = np.array([150, 180, 210, 240, 270, 300, 330, 360], dtype=float)
model = LinearRegression()
model.fit(house_sizes, house_prices)
pred_85 = round(float(model.predict([[85.0]])[0]), 4)
slope = round(float(model.coef_[0]), 4)
intercept = round(float(model.intercept_), 4)
if abs(intercept) < 1e-9:
intercept = 0.0
r2_exact = round(float(r2_score(house_prices, model.predict(house_sizes))), 6)
rng = np.random.default_rng(2026)
n_sizes = rng.uniform(45.0, 145.0, size=(60, 1))
n_prices = 3.0 * n_sizes.ravel() + 12.0 + rng.normal(0.0, 6.0, size=60)
X_tr, X_te, y_tr, y_te = train_test_split(n_sizes, n_prices, test_size=0.25, random_state=42)
noisy_model = LinearRegression().fit(X_tr, y_tr)
test_r2 = round(float(r2_score(y_te, noisy_model.predict(X_te))), 4)
test_mse = round(float(mean_squared_error(y_te, noisy_model.predict(X_te))), 4)
c1_ok = (
abs(pred_85 - 255.0) < 1e-4
and abs(slope - 3.0) < 1e-4
and abs(intercept) < 1e-4
and r2_exact == 1.0
and test_r2 > 0.95
)
cases.append(dict(
name="house_price_linear_regression",
inputs=dict(sizes_count=8, query_area=85, noisy_samples=60),
prerequisites="固定房屋面积与价格线性数据及带噪声留出验证集",
action="拟合 LinearRegression 验证 85 平方米预测 255.00 万元,并在 60 条含噪数据上检查留出集 R²。",
expected=dict(pred_85=255.0, slope=3.0, intercept=0.0, noisy_r2_gt_095=True),
actual=dict(pred_85=pred_85, slope=slope, intercept=intercept, noisy_r2_gt_095=test_r2 > 0.95),
measurements=dict(exact_r2=r2_exact, noisy_test_r2=test_r2, noisy_test_mse=test_mse),
passed=c1_ok,
))
# 2. Traditional explicit rule vs data-driven ML spam filter
def traditional_calc(a: float, b: float) -> float:
return a * 3.0 + b
calc_val = traditional_calc(85.0, 0.0)
rng_s = np.random.default_rng(7)
# Features: [suspicious_links, promo_keyword_count, sender_reputation_0_to_1]
ham = np.column_stack([
rng_s.poisson(0.3, 60),
rng_s.poisson(0.5, 60),
rng_s.uniform(0.65, 1.0, 60),
])
spam = np.column_stack([
rng_s.poisson(4.5, 60),
rng_s.poisson(5.0, 60),
rng_s.uniform(0.0, 0.45, 60),
])
X_mail = np.vstack([ham, spam])
y_mail = np.array([0] * 60 + [1] * 60)
Xm_tr, Xm_te, ym_tr, ym_te = train_test_split(X_mail, y_mail, test_size=0.25, random_state=42, stratify=y_mail)
clf = LogisticRegression(random_state=42).fit(Xm_tr, ym_tr)
spam_acc = round(float(clf.score(Xm_te, ym_te)), 4)
c2_ok = calc_val == 255.0 and spam_acc >= 0.95
cases.append(dict(
name="traditional_rule_vs_ml_learning",
inputs=dict(rule_inputs=[85.0, 0.0], mail_samples=120),
prerequisites="显式计算规则与带标签垃圾邮件特征数据",
action="对比固定公式直接计算与逻辑回归从 90 条训练样本自动学习垃圾邮件判别边界的留出准确率。",
expected=dict(rule_output=255.0, ml_spam_acc_ge_095=True),
actual=dict(rule_output=calc_val, ml_spam_acc_ge_095=spam_acc >= 0.95),
measurements=dict(test_samples=len(ym_te), spam_test_acc=spam_acc),
passed=c2_ok,
))
# 3. Three paradigms: Supervised, Unsupervised (KMeans), Reinforcement Learning (Q-learning)
rng_u = np.random.default_rng(11)
c_a = rng_u.normal(loc=[0.0, 0.0], scale=0.35, size=(30, 2))
c_b = rng_u.normal(loc=[5.0, 5.0], scale=0.35, size=(30, 2))
X_unsup = np.vstack([c_a, c_b])
km = KMeans(n_clusters=2, n_init=10, random_state=42).fit(X_unsup)
lbl_a = set(km.labels_[:30].tolist())
lbl_b = set(km.labels_[30:].tolist())
unsup_pure = len(lbl_a) == 1 and len(lbl_b) == 1 and lbl_a != lbl_b
# 1D corridor states 0..4, goal=4 (+10), step=-1, actions: 0=left, 1=right
q = np.zeros((5, 2), dtype=float)
rng_rl = np.random.default_rng(42)
for _ in range(120):
s = 0
for _step in range(20):
if s == 4:
break
a = int(rng_rl.integers(0, 2)) if rng_rl.random() < 0.25 else int(np.argmax(q[s]))
ns = max(0, s - 1) if a == 0 else min(4, s + 1)
r = 10.0 if ns == 4 else -1.0
q[s, a] += 0.3 * (r + 0.9 * (0.0 if ns == 4 else np.max(q[ns])) - q[s, a])
s = ns
# Greedy rollout from state 0
s, steps, total_reward = 0, 0, 0.0
while s != 4 and steps < 10:
a = int(np.argmax(q[s]))
s = max(0, s - 1) if a == 0 else min(4, s + 1)
total_reward += 10.0 if s == 4 else -1.0
steps += 1
rl_optimal = (s == 4 and steps == 4 and total_reward == 7.0)
c3_ok = unsup_pure and rl_optimal
cases.append(dict(
name="three_paradigms_demo",
inputs=dict(kmeans_points=60, rl_states=5, rl_episodes=120),
prerequisites="监督预测结果、两簇无标签点集与 5 状态走廊强化学习环境",
action="核对 KMeans 无监督双簇纯分离与 Q-learning 学得 4 步最短路径(累计回报 7.0)。",
expected=dict(unsup_clusters_pure=True, rl_optimal_steps=4, rl_total_reward=7.0),
actual=dict(unsup_clusters_pure=unsup_pure, rl_optimal_steps=steps, rl_total_reward=total_reward),
measurements=dict(q_state0_right=round(float(q[0, 1]), 3), q_state3_right=round(float(q[3, 1]), 3)),
passed=c3_ok,
))
# 4. Clean owned Matplotlib chart for house price linear fit
if fig_dir is not None:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ["Microsoft YaHei", "SimHei", "DejaVu Sans"]
plt.rcParams["axes.unicode_minus"] = False
fig_dir.mkdir(parents=True, exist_ok=True)
fig, ax = plt.subplots(figsize=(7.6, 4.5), dpi=140)
ax.scatter(house_sizes.ravel(), house_prices, color="#174d79", s=55, zorder=3, label="训练数据 (50-120 m²)")
ax.plot(house_sizes.ravel(), model.predict(house_sizes), color="#c0392b", lw=2.2, zorder=2, label="线性回归拟合线 (y = 3x)")
ax.scatter([85.0], [pred_85], color="#1e8449", s=110, marker="D", zorder=4, label=f"85 m² 预测点 ({pred_85:.2f} 万元)")
ax.annotate(
f"(85 m², {pred_85:.0f} 万元)",
xy=(85.0, pred_85),
xytext=(92.0, 228.0),
arrowprops=dict(arrowstyle="->", color="#1e8449", lw=1.2),
fontsize=9.5,
color="#145a32",
)
ax.set_title("房屋面积与价格线性回归实测拟合图", fontsize=12)
ax.set_xlabel("房屋面积(平方米)", fontsize=10)
ax.set_ylabel("房屋价格(万元)", fontsize=10)
ax.grid(True, linestyle="--", alpha=0.35)
ax.legend(loc="upper left", fontsize=9)
fig.tight_layout()
out_png = fig_dir / "house-price-linear-fit.png"
fig.savefig(out_png)
plt.close(fig)
figures["house-price-linear-fit.png"] = sha(out_png)
mpl_ver = matplotlib.__version__
else:
mpl_ver = None
cases.append(dict(
name="house_price_fit_plot",
inputs=dict(train_points=8, query_area=85),
prerequisites="线性回归拟合线与 85 平方米预测结果",
action="输出无第三方品牌标识的房屋面积-价格线性拟合散点图 PNG。",
expected=dict(plotted_points=8, predicted_price=255.0),
actual=dict(plotted_points=len(house_sizes), predicted_price=pred_85),
measurements=dict(figure_generated="house-price-linear-fit.png" in figures),
passed=(len(house_sizes) == 8 and abs(pred_85 - 255.0) < 1e-4),
))
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-tutorial-lab/explore-tutorial.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial.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章) · 含当前章节或实例 · mbskycom202612a505.zip