跳到主要内容

人工智能与机器学习

大学计算机科学知识点 13

本主题的视频课程 打开视频页面
6:33

人工智能与机器学习

本课程介绍人工智能的经典核心内容,并对其进行如实衡量。前三个单元是主干:搜索、逻辑推理和概率。接下来两个单元介绍从数据中学习:回归、分类和优化。最后两个单元通过评估和公平性确保结果可信。所有数字都来自一个名为 Overnight 的合成数据集,其中包含 200 条配送记录和一张数据卡。

英文讲解 · 可切换中英文字幕

探索

Storm to delay, and back

With P(S) = 0.3, P(D | S) = 0.8 and P(D | ¬S) = 0.1, a delay raises the belief in a storm from 0.3 to 0.24 / 0.31 ≈ 0.77. Lower P(S) towards rare storms and watch the posterior fall.

讲义

English

What this course is, and how to use it

This is the thirteenth course in University Computer Science: artificial intelligence and machine learning 人工智能与机器学习. It covers the classical core: search, reasoning, probability and learning from data, plus the tools that keep results honest (evaluation, leakage and fairness).

A limit, stated once: this is a study course, not a degree. One documented, made-up dataset, Overnight (200 fictional parcel deliveries, with a data card that describes it), supplies every calculation. Every metric in this handout is calculated from first principles, so you can calculate it again yourself.

  • Units 13.1–13.3 are the classical core: search, knowledge and probability.
  • Units 13.4–13.5 learn from data: models and how to fit them.
  • Units 13.6–13.7 keep them honest: evaluation, leakage and fairness.

The habit to build: a score without a resampling story is just an anecdote. Every score in this course is calculated again.

Search

Why it matters. Search solves problems by exploring a space of choices: routes, timetables, game moves. The classical algorithms are the grammar of all of them.

The idea. In a search tree 搜索树, nodes are states and edges are moves.

  • Uninformed 无信息 search explores blindly:
    • breadth-first 广度优先 search (BFS) finds the path with the fewest steps when all steps cost the same;
    • depth-first 深度优先 search (DFS) uses little memory.
  • Informed 有信息 search uses a heuristic 启发函数 $h(n)$, an estimate of the cost still to go. A* A* 搜索 always expands the node with the smallest $f(n) = g(n) + h(n)$: the cost so far plus the estimate.

Search tree The course tree: A with an admissible h expands toward the goal without the breadth-first wave*

Why an admissible heuristic gives the best answer. A heuristic is admissible if it never overestimates: $h(n) \le h^*(n)$, the true remaining cost. Then, when A* takes the goal off the queue, its cost $f(\text{goal}) = g(\text{goal})$ is no more than the $f$ of any node still waiting, and every path through those nodes costs at least their $f$. So no unexplored path can be cheaper.

The course graph: from the Depot D, the moves are D→A (4), D→B (2), A→C (3), B→C (1), C→Goal (5) and B→Goal (9). The heuristic is $h = \{A{:}8, B{:}6, C{:}5, G{:}0\}$, which is admissible (the true remaining costs are 8, 6, 5 and 0). BFS visits every node; A* expands only D, B, C and Goal, and finds the best cost, 8, by D→B→C→G ($2 + 1 + 5$).

Worked example 1: the course route, exactly.

step take off the queue add to the queue
1 D ($f = 0$) A ($g = 4$, $f = 12$), B ($g = 2$, $f = 8$)
2 B ($f = 8$) C ($g = 3$, $f = 8$), Goal ($g = 11$, $f = 11$)
3 C ($f = 8$) Goal by a cheaper path ($g = 3 + 5 = 8$, $f = 8$)
4 Goal ($f = 8$) stop

The best cost is 8, after four expansions.

Worked example 2: when the heuristic lies. Change $h(C)$ to $12$, an overestimate. After D and B, node C has $f = 3 + 12 = 15$, while the Goal reached through B has $f = 11$ (and A has $12$). So A* takes the Goal off the queue at cost 11 and stops. This is not the best path ($11 > 8$). An overestimate breaks the guarantee, because the algorithm trusts a false estimate.

Common mistakes.

  • Mixing up complete (finds a solution) with optimal (finds the best one).
  • Using a heuristic that is not admissible and still expecting the best answer.
  • Forgetting how much memory BFS uses: it stores the whole frontier, $O(b^d)$ nodes.

Summary. Uninformed searches trade information against memory. A* adds $g + h$, and with an admissible $h$ the first time it takes the goal off the queue, the path is the best one. The heuristic is the whole contract.

Knowledge and reasoning

Why it matters. Some knowledge is rules, not data: timetable constraints, diagnoses, regulations. Symbolic reasoning 符号推理 reaches conclusions that no data ever showed.

The idea. In propositional logic 命题逻辑 there are facts and rules ($P \to Q$). Inference 推理 applies the rules until the query is proved or no rule can fire.

  • Forward chaining 正向链 starts from the facts.
  • Backward chaining 反向链 starts from the query.
Inference chain
Course rules for delivery: the backward chain from Delayed walks up through Storm and HeavyTraffic to the known facts

Why the conclusions are sound. Each rule is an implication that is assumed true, and each step of inference is modus ponens (from $P$ and $P \to Q$, conclude $Q$). So everything the chain derives follows logically from the facts and rules: the reasoning cannot invent a false conclusion. (Completeness, whether every true consequence can be reached, is the harder property.)

The course knowledge base:

id content
F1 Storm
F2 Weekend
R1 Storm → Delayed
R2 Weekend → HeavyTraffic
R3 HeavyTraffic → Delayed
R4 Delayed → RefundRisk

Forward chaining derives Delayed and HeavyTraffic in the first round, and RefundRisk in the second: three conclusions in two rounds.

Worked example 1: the backward chain for RefundRisk. The goal is RefundRisk. R4 says it follows from Delayed; R1 says Delayed follows from Storm; and Storm is a fact. Proved in three steps, using only the rules that matter. Backward chaining is aimed at the goal, so it never looks at R2 or R3.

Worked example 2: resolution, proof by contradiction. To prove $Q$, assume $\neg Q$ and derive a contradiction (the empty clause). To prove RefundRisk:

  1. Assume ¬RefundRisk.
  2. With R4 (Delayed → RefundRisk), conclude ¬Delayed.
  3. With R1 (Storm → Delayed), conclude ¬Storm.
  4. This contradicts F1 (Storm).

So RefundRisk must be true. This method, called refutation, is the machinery behind SAT solvers and the NP-completeness chain of unit 10.

Common mistakes.

  • Mixing up sound (never wrong) with complete (always finds the answer).
  • Reading $P \to Q$ as $Q \to P$ (the converse error).
  • Using forward chaining when there is one goal that could guide the search.

Summary. Rules plus modus ponens make derivations sound by construction. Forward chaining spreads out from the facts; backward chaining works back from the goal. Refutation proves by contradiction.

Probability models

Why it matters. Real knowledge is uncertain: sensors are noisy, people are unpredictable, and causes are hidden. Probability is the mathematics of belief under uncertainty.

The idea. A Bayesian network 贝叶斯网络 is a graph of variables with arrows and no cycles. Each variable has a table of conditional probabilities, and the arrows show direct dependencies. Inference multiplies along the graph.

Network graph
The course network: Storm raises Delay; Delay explains both Late and Complaint; P(Storm | Complaint) is the inference

Bayes' theorem, worked through. The course numbers:

  • $P(S) = 0.3$ (storm);
  • $P(D \mid S) = 0.8$ and $P(D \mid \neg S) = 0.1$ (delay);
  • $P(C \mid D) = 0.6$ and $P(C \mid \neg D) = 0.05$ (complaint).

Step by step:

  1. With a storm: $P(C \mid S) = 0.8 \times 0.6 + 0.2 \times 0.05 = 0.49$.
  2. Without a storm: $P(C \mid \neg S) = 0.1 \times 0.6 + 0.9 \times 0.05 = 0.105$.
  3. Overall: $P(C) = 0.49 \times 0.3 + 0.105 \times 0.7 = 0.2205$.
  4. Bayes:
$$P(S \mid C) = \frac{P(C \mid S)\,P(S)}{P(C)} = \frac{0.49 \times 0.3}{0.2205} = \mathbf{0.667}$$

A complaint raises the belief in a storm from $0.3$ to $0.667$, more than double. It does not go higher because complaints also happen without storms.

Worked example 1: listing the full joint distribution. This network has 4 variables (Storm, Delay, Late, Complaint), so the full joint distribution has $2^4 = 16$ rows. Any query is a sum over those rows, and adding them up confirms $0.667$. On small networks, exact inference is just careful bookkeeping.

Worked example 2: the prior matters. Now make storms rare, $P(S) = 0.03$:

$$P(C) = 0.49 \times 0.03 + 0.105 \times 0.97 = 0.11655$$
$$P(S \mid C) = \frac{0.0147}{0.11655} = \mathbf{0.126}$$

The same evidence now gives a belief of only about 1 in 8. Rare causes need strong evidence: base rates are not a footnote.

Common mistakes.

  • Forgetting the normaliser $P(C)$, the sum over all causes.
  • Mixing up $P(C \mid S)$ and $P(S \mid C)$ (the prosecutor's fallacy).
  • Treating two variables as independent because there is no direct arrow between them. The correct test is d-separation.

Summary. A network splits the joint distribution into small tables. Bayes' theorem turns evidence into updated belief. The normaliser and the base rate carry the arithmetic; getting either wrong can reverse a conclusion.

Regression and classification

Why it matters. Learning from data means choosing a family of models and fitting it: a line through points, or a boundary between classes. The balance between fit and complexity decides whether the model works on new data.

The idea.

  • Linear regression 线性回归 fits $\hat{y} = w x + b$ by least squares.
  • Logistic regression 逻辑回归 fits a probability, using the sigmoid function, with a straight-line boundary.
  • A decision boundary 决策边界 is where the model changes its answer.
Decision boundary and data
Overnight with two features (distance, traffic): the fitted line separates on-time from late; two points sit inside the margin of doubt

Least squares, worked through. Minimise $\sum (y_i - w x_i - b)^2$. The course set has five points: $(1, 2)$, $(2, 3)$, $(3, 5)$, $(4, 4)$, $(5, 6)$.

  1. Means: $\bar{x} = 3$, $\bar{y} = 4$.
  2. Slope:
$$w = \frac{\sum (x_i - \bar{x})(y_i - \bar{y})}{\sum (x_i - \bar{x})^2} = \frac{9}{10} = 0.9$$
  1. Intercept: $b = 4 - 0.9 \times 3 = 1.3$, so $\hat{y} = 0.9x + 1.3$.
  2. Residuals: $-0.2, -0.1, 1.0, -0.9, 0.2$; the sum of squared errors (SSE) is $1.9$.

Worked example 1: the boundary of a logistic model. With weights $w_1 = 2$, $w_2 = -1$ and $b = -1$ (for distance and traffic), the boundary is $2 x_1 - x_2 - 1 = 0$, which is the line $x_2 = 2x_1 - 1$.

  • A parcel at $(2, 2)$ scores $2(2) - 2 - 1 = 1 > 0$: predicted late.
  • A parcel at $(2, 5)$ scores $2(2) - 5 - 1 = -2 < 0$: predicted on time.

The size of the score shows how sure the model is; the two doubtful points are the ones nearest the line.

Worked example 2: measuring overfitting. A degree-4 polynomial passes exactly through all five points, so its training SSE is $0$. On five held-out points, $(1.5, 2.8)$, $(2.5, 3.6)$, $(3.5, 4.9)$, $(4.5, 4.8)$, $(5.5, 6.4)$, its SSE is about $42.7$, against $0.55$ for the line. Training error is an advertisement; held-out error is the real product. Choose models by held-out error, not by how well they fit the training data.

Common mistakes.

  • Reading fitted weights as causes. A weight shows association, and a hidden factor may explain it.
  • Reporting training accuracy as the model's performance.
  • Leaving features on very different scales, so that the loss surface becomes a narrow valley (the subject of unit 13.5).

Summary. Least squares has an exact formula. Logistic regression turns scores into probabilities with a straight-line boundary. Extra complexity is paid for in held-out error, which is the real product.

Optimisation and learning

Why it matters. Most real models have no exact formula. Fitting them means walking downhill on a loss surface, and the shape of that walk decides how fast and how stably it goes, and where it stops.

The idea. Gradient descent 梯度下降:

$$\theta_{t+1} = \theta_t - \eta \nabla L(\theta_t)$$

The learning rate 学习率 $\eta$ sets the size of each step. The shape of the loss surface 损失面, its curvature and its narrow valleys, sets how hard the problem is.

Loss surface and updates
Contour ellipses around the minimum; three learning rates: small crawls, good descends, large overshoots

The quadratic case, exactly. For $L(w) = (w - 3)^2$, the gradient is $2(w - 3)$, so $w_{t+1} = w_t - 2\eta (w_t - 3)$.

$\eta$ update from $w_0 = 0$ behaviour
0.1 $w_{t+1} = 0.8 w_t + 0.6$ 0.6, 1.08, 1.464, 1.77, 2.02, … the error shrinks by a factor of 0.8 each step; it converges to 3
1 $w_{t+1} = -w_t + 6$ 6, 0, 6, 0, … swings for ever
0.6 $w_{t+1} = -0.2 w_t + 3.6$ 3.6, 2.88, 3.02, … swings, but settles quickly

The stability condition: $|1 - 2\eta| < 1$, which means $0 < \eta < 1$.

Worked example 1: the least-squares gradient. For the line in unit 13.4, the negative gradient of the mean squared error over $(w, b)$ points downhill except at a stationary point. Two gradient steps from $(0, 0)$ with $\eta = 0.02$ reach about $(0.84, 0.25)$. A thousand steps come close to the exact answer, $(0.9, 1.3)$.

Worked example 2: why features are scaled. Take $L = (x_1 - 1)^2 + 100(x_2 - 1)^2$. This surface is a narrow valley: the curvature along $x_2$ is 100 times the curvature along $x_1$, so one learning rate cannot suit both.

  • To stay stable along $x_2$, $\eta$ must be below $0.01$. With $\eta = 0.009$, the error in $x_1$ shrinks by only a factor of $0.982$ per step, so shrinking it a million times takes about 760 steps.
  • Rescale $x_2$ so that both directions have the same curvature. Now $\eta = 0.4$ is stable, and both errors shrink by a factor of $0.2$ per step.

Standardising features is basic good practice for optimisation, not decoration.

Common mistakes.

  • Taking the latest loss value as proof of convergence. Look at how much it is still changing.
  • Using one learning rate for everything when the surface has narrow valleys.
  • Forgetting that the noise in stochastic gradient descent (SGD) is both the cure (it escapes shallow dips) and the cost (it never quite settles).

Summary. Step against the gradient, with $\eta$ inside the stability limit set by the curvature. Narrow valleys come from unscaled features. Use an exact formula where one exists, and gradient descent where it does not.

Evaluation and leakage

Why it matters. A score is a claim about the future. The process that produced it can quietly lie, through leakage or through one lucky split of the data.

The idea. Split the data into training, validation and test sets. The test set is used only once. The confusion matrix 混淆矩阵 counts true positives (TP), false positives (FP), false negatives (FN) and true negatives (TN), and the metrics accuracy 准确率, precision 查准率 and recall 召回率 are read from it.

Split and confusion matrix
Left: the Overnight split — test is spent once. Right: the late-prediction matrix with its derived metrics

The metrics, from the matrix. The course matrix for predicting late deliveries covers all 200 records, each one scored by a model that was not trained on it: TP 36, FP 10, FN 6, TN 148.

metric formula value
accuracy $(36 + 148)/200$ $\mathbf{0.92}$
precision $36/(36 + 10) = 36/46$ $\mathbf{0.783}$
recall $36/(36 + 6) = 36/42$ $\mathbf{0.857}$
$F_1$ $2 \times 36 / (2 \times 36 + 10 + 6) = 72/88$ $\mathbf{0.818}$

Late deliveries are $42/200 = 21\%$ of the data. A useless model that always says "on time" would score $158/200 = 0.79$ accuracy. So 0.92 does mean something, but the recall is where the real meaning is.

Worked example 1: building a leak. Suppose one feature is the delivery-status code recorded at midnight. It already contains the answer. Training accuracy jumps to 0.99, but a proper held-out test (where that feature is not yet known) drops to 0.90. The 0.99 came from the answer leaking in through the feature. Leakage is a fact about how the data was collected, not a fine point of modelling, and the provenance column of the data card (where each feature comes from, and when) is the defence.

Worked example 2: the resampling story. One split's 0.92 is an anecdote. 5-fold cross-validation on Overnight gives 0.905, 0.925, 0.915, 0.90 and 0.935: a mean of 0.916, with a standard deviation of about 0.014. So the honest score is about $0.916 \pm 0.014$, and a competing model that scores 0.921 is within the noise.

Common mistakes.

  • Using the test set to choose a model. It then becomes a second validation set.
  • Averaging accuracies when the folds have different sizes. Add up the counts from each fold instead.
  • Scaling the features before splitting the data. The test set's statistics then leak into training.

Summary. Use the test set once. The metrics come from the matrix. Leakage comes in through the data pipeline, and provenance is the defence. A score without a resampling story is an anecdote.

Fairness and limitations

Why it matters. Models decide who gets things: a refund, an interview, a diagnosis. When errors fall more on one group than another, that is a real harm, and classical machine learning does nothing about it unless we add a goal that measures it.

A white Waymo self-driving car on a city street, with a spinning lidar sensor unit on its roof and extra cameras at the front corners
A self-driving car uses cameras and lidar sensors to see the road around it

The idea. To measure error disparity 误差差异, compare the confusion matrices for each group. The Overnight model predicts late deliveries in two regions, city and rural: the same model makes different mistakes in each.

Error disparity chart
Recall by region: city 0.90, rural 0.75 — the model under-serves rural lates; the disparity bar is the audit

The arithmetic of the gap.

region TP FN recall
city 27 3 $27/30 = 0.90$
rural 9 3 $9/12 = 0.75$

The gap is 15 percentage points of recall: the model misses 1 in 4 late rural deliveries, but only 1 in 10 late city deliveries. Different thresholds for each group may help reduce error-rate disparities. Demographic parity (equal rates of positive predictions) is a different criterion, and it can conflict with equal error rates. Fairness is a design choice with named options, not a box to tick.

Worked example 1: the cause, in the data card. Late deliveries are 12 of the 95 rural records (13%), against 30 of the 105 city records (29%). The rural late class is smaller, and the fitted boundary serves it less well. The fix starts in the data (more rural records, or class weights), not in the metric.

Worked example 2: stating the limits. Overnight is made up: 200 records, two regions, one season. Its 0.92 accuracy says nothing about your city, your season or your delivery company. The model card states the intended use (teaching), the measured disparities (the 15-point gap) and the uses it is not suitable for (real deployment decisions). A limitation you state honestly builds trust; one your users discover destroys it.

Common mistakes.

  • Declaring a model fair because its overall accuracy is high. The gap is hidden underneath.
  • Fixing a disparity only by moving the threshold, without asking why it exists (a small class, or weak features).
  • Treating a benchmark score as a promise about real use. The scope section of the data card is the contract.

Summary. Check the confusion matrix for each group. Fairness has named criteria, and some of them conflict. A disparity usually starts in the data. The limitations section of the model card is where honesty is written down.

词汇
English 中文 拼音
artificial intelligence and machine learning/ˌɑːtɪˈfɪʃl ɪnˈtelɪdʒəns ænd məˈʃiːn ˈlɜːnɪŋ/ 人工智能与机器学习 rén gōng zhì néng yǔ jī qì xué xí
search tree/sɜːtʃ triː/ 搜索树 sōu suǒ shù
uninformed/ˌʌnɪnˈfɔːmd/ 无信息 wú xìn xī
breadth-first/bredθ fɜːst/ 广度优先 guǎng dù yōu xiān
depth-first/depθ fɜːst/ 深度优先 shēn dù yōu xiān
informed/ɪnˈfɔːmd/ 有信息 yǒu xìn xī
heuristic/hjuːˈrɪstɪk/ 启发函数 qǐ fā hán shù
symbolic reasoning/sɪmˈbɒlɪk ˈriːzənɪŋ/ 符号推理 fú hào tuī lǐ
propositional logic/ˌprɒpəˈzɪʃənl ˈlɒdʒɪk/ 命题逻辑 mìng tí luó jí
inference/ˈɪnfərəns/ 推理 tuī lǐ
forward chaining/ˈfɔːwəd ˈtʃeɪnɪŋ/ 正向链 zhèng xiàng liàn
backward chaining/ˈbækwəd ˈtʃeɪnɪŋ/ 反向链 fǎn xiàng liàn
Bayesian network/beɪˈiːzɪən ˈnetwɜːk/ 贝叶斯网络 bèi yè sī wǎng luò
linear regression/ˈlɪnɪə rɪˈɡreʃn/ 线性回归 xiàn xìng huí guī
logistic regression/ləˈdʒɪstɪk rɪˈɡreʃn/ 逻辑回归 luó jí huí guī
decision boundary/dɪˈsɪʒn ˈbaʊndəri/ 决策边界 jué cè biān jiè
gradient descent/ˈɡreɪdɪənt dɪˈsent/ 梯度下降 tī dù xià jiàng
learning rate/ˈlɜːnɪŋ reɪt/ 学习率 xué xí lǜ
loss surface/lɒs ˈsɜːfɪs/ 损失面 sǔn shī miàn
confusion matrix/kənˈfjuːʒn ˈmeɪtrɪks/ 混淆矩阵 hùn xiáo jǔ zhèn
accuracy/ˈækjʊrəsi/ 准确率 zhǔn què lǜ
precision/prɪˈsɪʒn/ 查准率 chá zhǔn lǜ
recall/ˈriːkɔːl/ 召回率 zhào huí lǜ
error disparity/ˈerə dɪˈspærɪti/ 误差差异 wù chā chā yì
A* A* 搜索 A* sōu suǒ

该知识点的互动课程

逐步完成,配合即时检查练习。

更多 大学计算机科学 知识点

登录或创建账户

IGCSE, A-Level & AP