机器学习教程
核对机器学习与传统规则编程的范式差异、数据/算法/模型三大核心要素,以及线性回归房价预测的完整流程与实测拟合图。
学完这一章,你能够
- 核对机器学习与传统规则编程的范式差异、数据/算法/模型三大核心要素,以及线性回归房价预测的完整流程与实测拟合图。
机器学习概念与传统编程差异
机器学习(Machine Learning)属于人工智能核心分支,它不依赖开发人员逐条手写业务判断,而是借助算法从历史经验数据中自动归纳规律并持续改进性能,已广泛用于推荐系统、图像与语音识别、金融风控及自动驾驶(例如识别交通标志、行人与障碍物)。
传统编程要求程序员显式编写确定性规则(如计算器或固定计价公式),而机器学习输入的是历史数据与答案,由算法反推出隐含映射规则。本站离线实测对比两类范式:硬编码规则 `3.0 * area` 直接算出 85 平方米对应 `255.0` 万元,而垃圾邮件逻辑回归分类器无需人工枚举敏感词阈值,仅凭带标签文本向量训练即可在 30 条测试邮件上取得 `1.0` 准确率。
机器学习的三大核心要素
机器学习围绕数据、算法与模型三大要素运转。首先是数据——它是模型学习的燃料,质量与覆盖度直接决定效果上限;工程上通常明确区分为用于拟合规律的训练数据、用于独立检验泛化能力的测试数据,以及上线后模型实际面对的真实数据。
其次是算法,即从数据中提取规律的方法,主流分为有标准答案的监督学习、从无标签样本中发现结构的无监督学习,以及借由环境交互试错与奖励反馈优化策略的强化学习。本站实测三类范式:KMeans 将 60 个二维无标签样本纯分离为两簇;5 状态一维走廊 Q-learning 经 120 轮交互收敛至 4 步最短路径(累计回报 `7.0`,状态 0 向右 Q 值为 `4.58`,状态 3 向右 Q 值为 `10.0`)。
第三要素是模型,它是算法在数据上学习后产出的参数集合与决策规则,对应两个关键阶段:训练过程负责利用样本不断校准参数以逼近规律,推理过程则冻结学得参数对新输入输出预测结果。
线性回归房价预测实测流程
以 Python `scikit-learn` `LinearRegression` 预测房价为例:用 50 至 120 平方米对应 150 至 360 万元的 8 组训练数据拟合线性模型,本站实测精确恢复斜率 `3.0` 与截距 `0.0`(确定系数 `R² = 1.0`),对 85 平方米新房预测输出 `255.0` 万元;进一步在 60 套带随机噪声的合成房价集上拆分训练与测试集,线性回归在测试集上测得 `R² = 0.9872`、`MSE = 34.041`。
上述案例完整呈现了机器学习的入门四步管线:准备面积与价格数据、选用线性回归算法、训练模型学习线性关系、调用模型预测新面积价格。下方展示本站基于实测数据独立生成的拟合散点图(原始参考图含第三方标识,仅留存私有证据)。

传统编程与机器学习模式对比
| 对比维度 | 传统编程 | 机器学习 |
|---|---|---|
| 规则来源 | 由开发人员显式编码业务条件与运算逻辑 | 由算法从历史样本与答案中自动学习参数规则 |
| 适用问题 | 边界明确、逻辑固定、可直接用确定公式描述的任务 | 高维特征复杂、噪声较多、难以人工穷举规则的任务 |
| 典型实例 | 四则运算计算器或固定单价计费公式 | 垃圾邮件过滤、房价回归预测、图像与语音识别 |
运行传统规则对比、三类学习范式与线性回归房价预测实验
"""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)
- 核对 85 平方米预测 255.0 万元(斜率 3.0、截距 0.0、含噪测试 R²=0.9872)、垃圾邮件分类准确率 1.0、KMeans 纯分离、Q-learning 4 步回报 7.0 及独立拟合 PNG 图。
所需环境: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:4c85de9c2b29a3646fdf0b0d2334463b46343d97ef26a90888940e1233ac2559
本地运行
解压后按 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:fdb97da6b16c2df0153b8e30cf53957e43cbd512788f753eff07be399acb0795
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
机器学习与传统编程的核心输入输出差异是什么?在房价预测中训练数据与测试数据各自承担什么职责?
展开参考解答
传统编程输入“数据+人工规则”得到结果,机器学习输入“数据+样本答案”由算法学习规则并产出模型;训练数据用于拟合斜率和截距等参数,测试数据用于独立检验模型对未见样本的泛化误差。