跳到主要内容

A.4 · 机器学习

IB 计算机科学 HL · 知识点 4

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

机器学习

垃圾邮件过滤器并非由规则列表驱动。相反,它被展示成千上万封标记为垃圾邮件或非垃圾邮件的电子邮件,并自行发现模式。当垃圾邮件发送者……

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

4.1

范围与先修条件

English

This handout teaches Theme A4, Machine learning, for the course first assessed in 2027: what machine learning is, its main types, how models are judged, and its ethical issues. Sections marked AHL are for Higher Level only.

Prerequisites: reading a scatter graph and a percentage. The datasets here are small and fictional.

4.2

什么是机器学习?

English

A program that learns from examples

A spam filter is not given a list of rules such as "block any e-mail containing 'prize'". Instead it is shown thousands of e-mails labelled "spam" or "not spam" and finds the patterns itself. When spammers change their wording, it is retrained on new examples. This is machine learning 机器学习 (ML): a program improves at a task by learning patterns from data rather than following rules written by a programmer.

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

ML is one part of artificial intelligence 人工智能 (AI), the wider field of making computers do tasks that seem to need human intelligence. Deep learning 深度学习 is a kind of ML that uses neural networks with many layers.

Types of machine learning

Type Learns from Typical task Example
supervised learning 监督学习 labelled data: inputs with the right answers classify, predict a number spam or not; a house price
unsupervised learning 无监督学习 unlabelled data find groups or patterns grouping shoppers by habits
reinforcement learning 强化学习 rewards and penalties from trial and error choose actions a robot learning to walk; a game player

Supervised learning splits into classification 分类 (the answer is a category: cat or dog) and regression 回归 (the answer is a number: a score or a price).

Scatter graph of hours of revision against test score for five students, rising from 52 at 1 hour to 74 at 5 hours, with the straight best-fit line y = 5.6x + 46.2 and a prediction of 79.8 at 6 hours
Supervised learning: the model learns a line from labelled examples, then predicts a new case

Training and testing

  1. Collect and label data.
  2. Split it: most for training 训练 the model, the rest held back as test data 测试数据.
  3. Train the model on the training data.
  4. Measure it on the test data, which it has never seen.

Testing on unseen data shows whether the model has learned the general pattern. A model that memorises its training data but fails on new data is overfitting 过拟合. A model too simple to capture the pattern is underfitting.

Measuring a classifier

Accuracy 准确率 is the share of predictions that are correct:

$$\text{accuracy} = \frac{\text{correct predictions}}{\text{total predictions}} \times 100\%$$

A model correct on 90 of 100 test cases has 90% accuracy. Accuracy can mislead when the classes are unbalanced:

Bar chart of 100 cases: 90 in the majority class and 10 in the minority class
With 90 of 100 cases in one class, always predicting that class scores 90% yet misses every minority case

A "model" that always answers "healthy" for a disease affecting 10% of patients scores 90% and finds no one who is ill. So check how the model does on each class, not just overall.

Hardware for machine learning

Training repeats the same arithmetic on huge amounts of data, so it runs on GPUs and special chips with thousands of cores working in parallel, often rented in the cloud. Using a trained model (inference) needs far less power and can run on a phone.

探索

准确率与类别分布

比较总体准确率、各类别召回率与正类精确率。不同分母回答不同的问题,类别分布会影响总体准确率。

词汇 训练
English 中文 拼音
machine learning/məˈʃiːn ˈlɜːnɪŋ/ 机器学习 jī qì xué xí
artificial intelligence/ˌɑːtɪˈfɪʃl ɪnˈtelɪdʒəns/ 人工智能 rén gōng zhì néng
deep learning/diːp ˈlɜːnɪŋ/ 深度学习 shēn dù xué xí
supervised learning/ˈsuːpəvaɪzd ˈlɜːnɪŋ/ 监督学习 jiān dū xué xí
unsupervised learning/ʌnˈsuːpəvaɪzd ˈlɜːnɪŋ/ 无监督学习 wú jiān dū xué xí
reinforcement learning/ˌriːɪnˈfɔːsmənt ˈlɜːnɪŋ/ 强化学习 qiáng huà xué xí
classification/ˌklæsɪfɪˈkeɪʃn/ 分类 fēn lèi
regression/rɪˈɡreʃn/ 回归 huí guī
training/ˈtreɪnɪŋ/ 训练 xùn liàn
test data/test ˈdeɪtə/ 测试数据 cè shì shù jù
overfitting/ˌəʊvəˈfɪtɪŋ/ 过拟合 guò nǐ hé
accuracy/ˈækjʊrəsi/ 准确率 zhǔn què lǜ
4.3

机器学习的伦理

English

Who is affected?

Issue What can go wrong Example
bias 偏见 training data under-represents a group, so the model works worse for them face recognition less accurate for darker skin
privacy personal data collected or used without consent photos scraped from social media
transparency no one can explain why the model decided a loan refused with no reason given
accountability unclear who is responsible for a harmful decision a self-driving car accident
jobs tasks automated checkout staff, translators
misuse realistic fake images, audio or text deepfakes spread as news
A CCTV control room: surveillance systems trade safety gains against privacy concerns
A CCTV control room: surveillance systems trade safety gains against privacy concerns

Ways to reduce harm: train on data that represents everyone the model affects; test accuracy separately for each group; keep a human in the loop for serious decisions; collect data with consent and remove what is not needed; explain decisions to the people affected.

词汇 训练
English 中文 拼音
bias/ˈbaɪəs/ 偏见 piān jiàn
4.4

AHL:准备数据

English

Data preprocessing

Real data is messy. Data preprocessing 数据预处理 prepares it before training:

A raw table of ID, age and colour with an impossible age of 250 struck out passes through cleaning, encoding colours as numbers, normalising age to 0 to 1 and dropping the ID, giving a model-ready table of age 1.0 and 0.0 with colour codes 0 and 2
Clean, encode, normalise and select features before training, and keep out any feature that leaks the answer
Step What it does Example
cleaning fix or remove missing, duplicate and wrong values delete a row with age 250
encoding turn categories into numbers red, green, blue → 0, 1, 2
normalisation (scaling) put features on a similar range, such as 0 to 1 income in thousands and age in years
feature selection 特征选择 keep only the inputs that help prediction drop a student's ID number
dimensionality reduction combine many features into fewer thousands of pixel values → a few patterns

A feature 特征 is one input variable, such as hours of revision; the label 标签 is the answer to be predicted, such as the score.

Watch for data leakage 数据泄漏: a feature that would not be known when the prediction is made, such as using "days in hospital" to predict whether a patient will be admitted. The model then looks excellent in testing and fails in real use.

词汇 训练
English 中文 拼音
data preprocessing/ˈdeɪtə prɪˈprəʊsesɪŋ/ 数据预处理 shù jù yù chǔ lǐ
feature selection/ˈfiːtʃə sɪˈlekʃn/ 特征选择 tè zhēng xuǎn zé
feature/ˈfiːtʃə/ 特征 tè zhēng
label/ˈleɪbl/ 标签 biāo qiān
data leakage/ˈdeɪtə ˈliːkɪdʒ/ 数据泄漏 shù jù xiè lòu
4.5

AHL:机器学习算法

English

Linear regression

Linear regression 线性回归 fits the straight line $y = mx + c$ that best matches the data, then uses it to predict. For the revision data above, the best-fit line is $y = 5.6x + 46.2$:

$$y = 5.6 \times 6 + 46.2 = 79.8$$

so 6 hours of revision predicts a score of about 80. Predicting far outside the data, such as for 30 hours, is unreliable.

k-nearest neighbours

k-nearest neighbours 近邻算法 (k-NN) classifies a new item by the classes of the $k$ training items closest to it.

A scatter graph of two classes: A (circles) at the lower left and B (squares) at the upper right; a new point (star) lies between them; of its three nearest neighbours, inside a dashed circle, two are A and one is B, so the new point is classed A
With $k = 3$ the new point is classed A, although its single nearest neighbour is B
  1. Work out the distance from the new item to every training item.
  2. Take the $k$ nearest.
  3. Give the new item the most common class among them.

An odd $k$ avoids ties between two classes. k-NN needs no training, but each prediction compares with every stored item, so it is slow on large datasets.

Decision trees and clustering

  • A decision tree 决策树 asks a sequence of yes/no questions about the features, such as "Is the e-mail from a known contact?", ending at a leaf that gives the class. It is easy for people to follow and explain.
  • k-means clustering 均值聚类 is unsupervised: choose $k$ centres, put each item in the cluster of its nearest centre, move each centre to the mean of its cluster, and repeat until nothing changes. Used to group customers or documents.

Neural networks

An artificial neural network 人工神经网络 is made of layers of simple units (nodes). Each connection has a weight 权重; each node adds up its weighted inputs and passes the result on.

A neural network with an input layer of three nodes taking pixel values, a hidden layer of four nodes and an output layer of two nodes, such as cat or dog; every node is connected to every node in the next layer, and each line has a weight adjusted during training
Training adjusts the weights until the outputs match the labels

Training compares the network's output with the right answer and adjusts every weight a little to reduce the error, over many thousands of examples. A convolutional neural network (CNN) has layers that scan small patches of an image to find edges, shapes and then objects, and is used for image recognition.

Precision and recall

For a classifier that flags positives (such as "has the disease"), compare predictions with reality in a confusion matrix 混淆矩阵:

Actually positive Actually negative
predicted positive true positive (TP) 4 false positive (FP) 10
predicted negative false negative (FN) 1 true negative (TN) 85
$$\text{accuracy} = \frac{TP + TN}{\text{total}} = \frac{4 + 85}{100} = 0.89$$
$$\text{precision} = \frac{TP}{TP + FP} = \frac{4}{14} \approx 0.29 \qquad \text{recall} = \frac{TP}{TP + FN} = \frac{4}{5} = 0.80$$

Recall asks "of the real positives, how many did we find?"; precision asks "of those we flagged, how many were right?". A disease screen wants high recall, so few sick patients are missed; a spam filter wants high precision, so real e-mails are not lost.

词汇 训练
English 中文 拼音
linear regression/ˈlɪnɪə rɪˈɡreʃn/ 线性回归 xiàn xìng huí guī
k-nearest neighbour/keɪ ˈnɪərɪst ˈneɪbə/ 近邻算法 jìn lín suàn fǎ
decision tree/dɪˈsɪʒn triː/ 决策树 jué cè shù
k-means clustering/keɪ miːnz ˈklʌstərɪŋ/ 均值聚类 jūn zhí jù lèi
artificial neural network/ˌɑːtɪˈfɪʃl ˈnjuːrəl ˈnetwɜːk/ 人工神经网络 rén gōng shén jīng wǎng luò
weight/weɪt/ 权重 quán zhòng
confusion matrix/kənˈfjuːʒn ˈmeɪtrɪks/ 混淆矩阵 hùn xiáo jǔ zhèn
4.6

练习

English
  1. Define machine learning, and explain how it differs from a program with written rules.
  2. State the type of ML for each: (a) grouping songs by similarity with no labels; (b) predicting tomorrow's temperature from past records; (c) a program learning to play chess by playing itself.
  3. State whether each is classification or regression: (a) a house price; (b) whether a photo shows a cat.
  4. Explain why a model is tested on data it was not trained on.
  5. A model makes 72 correct predictions out of 80. Calculate its accuracy.
  6. A model for a rare disease (2% of patients) has 98% accuracy. Explain why this may be useless.
  7. Explain two ethical issues of using ML to shortlist job applicants, and suggest a way to reduce each.
  8. AHL Explain what data leakage is, with an example.
  9. AHL Use $y = 5.6x + 46.2$ to predict the score for 3.5 hours of revision.
  10. AHL In the k-NN figure, state the class given to the new point with $k = 1$ and with $k = 3$.
  11. AHL A classifier has TP = 30, FP = 10, FN = 20, TN = 140. Calculate its accuracy, precision and recall.

Answers.

  1. ML is a program that improves at a task by learning patterns from data. A rule-based program follows rules a programmer wrote; an ML model finds its own rules from examples.
  2. (a) unsupervised; (b) supervised (regression); (c) reinforcement.
  3. (a) regression; (b) classification.
  4. To check that it has learned the general pattern rather than memorised the training examples (overfitting); unseen data shows how it will work in real use.
  5. $\dfrac{72}{80} \times 100\% = 90\%$.
  6. Always predicting "healthy" would also score 98% while finding no sick patients; the model must be judged on how many real cases it finds.
  7. E.g. bias: past hiring data may favour one group, so the model repeats it; train on balanced data and test results for each group. Transparency: applicants cannot learn why they were rejected; use an explainable model and keep a human reviewer.
  8. Using information that would not be available when the prediction is made, so test results are falsely good; e.g. predicting who will fail a course using their final exam mark.
  9. $5.6 \times 3.5 + 46.2 = 19.6 + 46.2 = 65.8$.
  10. $k = 1$: the nearest point is B, so B; $k = 3$: two A and one B, so A.
  11. Accuracy $= \dfrac{30 + 140}{200} = 0.85$; precision $= \dfrac{30}{40} = 0.75$; recall $= \dfrac{30}{50} = 0.60$.
4.7

考试技巧

English
  • Name the type of learning from the data: labels → supervised; no labels → unsupervised; rewards → reinforcement.
  • Say why test data is kept separate: to measure performance on unseen data and detect overfitting.
  • Do not trust accuracy alone with unbalanced classes; mention per-class results.
  • Ethics answers: name the issue, explain the harm in the scenario, then give a specific way to reduce it.
  • AHL Show the formula before substituting for regression predictions, precision and recall.
  • AHL For k-NN, state $k$, the neighbours found and the majority class.

更多 IB 计算机科学 HL 知识点

登录或创建账户

IGCSE, A-Level & AP