COMP 4930SEF Deep Learning —— Unit 1 Machine Learning Concepts 逐页精讲

讲义:lecture/u01.pdf(Kayley Ma,共 53 页,按原页码逐页讲解,一页不落)
配套:Lab 1 = Tutorial 1(t01-s13903054.ipynb)· 2026 试卷 Q1 / Q6 / Q7 / Q8 · Course Review(Unit 1 考点)· 后续单元衔接

怎么用这份讲义:每一页是一张卡片,固定六个栏目 ——
① 页首:原页码 + 该页主题 + 标签(★复习课点名 / 🧮计算 / 试卷 / Lab 1 / 原图) ② 原文要点:讲义原句,方便对照幻灯片
③ 核心概念 ④ 详细讲解(课堂式:背景 → 逻辑 → 例子) ⑤ 题目 / Tut / Lab 关联 ⑥ 必要扩展 ⑦ 易错点 · 理解提示
讲义里的全部数字(p33 数据、p46 的 6.0、p49 梯度下降五行轨迹、p51 的 73.59、p52 的 4.28927 / 9.25193 / 0.93609)都已用程序逐位复算通过。

🗺 全讲地图(点击页码跳转)

部分页码回答的问题Course Review p3 对应考点
A 什么是机器学习p1–p9ML 是什么、与传统软件的区别、为何 2010 年代才成功、有什么好处Machine learning concepts
B 机器学习术语p10–p23features / labels / examples、训练集与测试集、两类数据、分类与回归Training (features) and prediction (labels);Two types of data;Two types of supervised ML
C 三类机器学习 + 深度学习p24–p30监督 / 无监督 / 强化学习;DL 在 ML 中的位置Three types of ML
D 训练一个线性回归模型p31–p41数据 → 直线模型 → MSE → 梯度下降 → 学习率 → 超参数Gradient descent
E 附录:完整代码p42–p53NumPy 手写梯度下降 → sklearn → TensorFlow/Keras(Lab 1 的 NumPy 技能全部在此落地)

红色页码 = 复习课点名或试卷直接考到的页。讲完 53 页后还有:Lab 1 全解 · 试卷相关题 · 梯度下降交互实验室 · Unit 1 总结 + 自测

A 部分|什么是机器学习(p1–p9)

p.1封面:Unit 1 – Machine learning concepts定位
COMP 4930SEF Unit 1 - Machine learning concepts · Kayley Ma
核心概念本讲是整门课唯一一个"纯概念"单元:不讲任何网络结构,只回答四件事——数据长什么样(features / labels / examples)、任务有哪几类(classification / regression …)、深度学习在机器学习里处于什么位置、"训练一个模型"到底在做什么(用线性回归 + 梯度下降完整走一遍)。
详细讲解为什么第一讲要花这么多页讲"看起来很虚"的概念?因为后面 11 个单元都在复用这套词汇:Unit 2 的 logistic 回归,本质是把本讲的 y = mx + b 套上一个 sigmoid;Unit 3 用微积分把本讲 p47 那两行梯度代码推导出来;Unit 4–5 把"一条直线"换成"多层网络",但"训练 = 用 loss 衡量好坏 + 用 optimizer 调参数"的框架一步不变。所以本讲的目标不是"会算",而是建立一套贯穿整门课的语言。考试里 Unit 1 几乎全以短问题(state / determine / name)出现,例如 2026 年试卷 Q1 让你判断任务类型,答案就在 p23。
题目 / Tut / Lab 关联① Course Review p3 把 Unit 1 的考点压成 5 条:features/labels 的训练与预测、两类数据、两类监督学习、三类机器学习、梯度下降——分别对应本讲 p12–p19、p20–p22、p23–p25、p24–p27、p38–p39(详见文末总结的对照表)。② Lab 1(t01 notebook) 是 Python / NumPy 工具热身,为 p43–p53 的附录代码做准备——讲义正文不直接考 Lab 1,但附录代码全靠它。③ 试卷 Q1、Q7 的任务类型判断全部出自本讲。
必要扩展课程评分(intro.pdf p10):Lab exercises 15%(每周交,下一次讲课日 18:00 截止)、Test 20%、Project 15%、期末 50%;OCAS 与 OES 都要 ≥ 50 才及格。课堂上不定期出 bonus 题(每次讲课最多 1 分、全学期最多 5 分),题目就来自讲义里的例子和概念——所以讲义里每个例子都值得看懂。
易错点 · 理解提示本讲说的"模型"就是一条直线(两个数 m、b),不是后面那种上百万参数的网络。先把小模型吃透,后面只是把同样的流程放大。
p.2目录(Contents)
What machine learning is · Machine learning terminologies · Types of machine learning · What deep learning is · Training a linear regression model
核心概念五个部分 = 是什么 → 术语 → 分类 → 深度学习在哪 → 动手训练。
详细讲解这张目录是一条因果链,不是并列清单。要先定义 ML(p4–p9),因为要谈"从数据学习"就必须先说清数据——于是引出术语(p11–p22);有了术语才能给任务分类(p23–p27);分类清楚了才能说清 DL 只是 ML 的一个子集(p29–p30);最后 p32–p40 用一个最小的例子(10 个学生、1 个特征、1 条直线)把前四部分全部"用一遍"。读每一部分时问自己:它在回答什么问题?
题目 / Tut / Lab 关联Lab 1 练的 NumPy / Python 技能对应第五部分 "training a linear regression model" 的代码附录(p42–p53)。Course Review p3 的五条考点与这五个部分一一对应。
必要扩展后续单元的讲义都是同样的组织方式:概念 → 术语 → 结构 → 代码。养成"先看目录猜逻辑"的习惯,课堂 bonus 题常问"本讲有哪几部分"。
易错点 · 理解提示自测:合上讲义,能否用一句话说出五个部分各回答什么?说不出的那部分就是你的薄弱点。
p.3分节页:What machine learning is分节
What machine learning is
核心概念第一部分开始:机器学习是什么。
详细讲解这页本身没有内容,作用是把讲义切成"概念块"。接下来 p4–p6 回答"ML 是什么"(定义与来历),p7 回答"它和传统软件有什么不同"(范式),p8–p9 回答"为什么现在才流行、它有什么好处"(背景)。课堂讲到这里通常是一个停顿点,老师会在此处提 bonus 问题,例如 "Who coined the term machine learning?"——答案在 p6。
题目 / Tut / Lab 关联Course Review p3 的第一条 "Machine learning concepts" 就从这里开始。
必要扩展本讲的分节页(p3、p10、p24、p28、p31、p42)就是复习时的一级大纲:四个概念块 + 一个代码附录。
易错点 · 理解提示不必在分节页上花时间,但要知道它后面每一页属于哪个概念块。
p.4Deep learning vs machine learning vs AI★定义题原图
AI, is intelligence demonstrated by computer systems · ML, is intelligence learned from example data and building a model · DL, is a type of ML techniques that use artificial neural networks
核心概念AI ⊃ ML ⊃ DL——三个嵌套的椭圆:AI 最外、ML 居中、DL 最内。
详细讲解三个定义的关键差别在于"智能从哪来"。AI(Artificial intelligence)只要求 computer systems 表现出智能,不限定实现方式——可以是人写死的规则(专家系统)。ML(Machine learning)要求智能是从 example data 里学来的,并表现为一个 model。DL(Deep learning)进一步限定:ML 的实现手段必须是 artificial neural networks。所以图是三层嵌套。反过来记更牢:所有 DL 都是 ML,所有 ML 都是 AI;但 AI 不一定是 ML(手写规则的专家系统),ML 不一定是 DL(决策树、k-means 聚类都不是神经网络)。
Deep learning Machine learning Artificial intelligence
讲义 p4 原图:三个嵌套椭圆,越往里范围越小。
题目 / Tut / Lab 关联本讲 p25–p27 的三类 ML 都在中间圈里;p29–p30 的 DL 在内圈。试卷 Q1 / Q7 考的是"用神经网络(DL)解监督学习问题"——三个圈同时涉及。Lab 1 不涉及。
必要扩展课程大纲 Topic 1 的标题是 "Review of Fundamental Machine Learning Concepts",并明确要求比较 shallow learning 与 deep learning——"shallow" 指传统 ML(特征靠人工设计),"deep" 指用多层网络自动学特征(见 p29–p30)。
易错点 · 理解提示三个定义建议用英文原句背。短答题 "Define deep learning" 的满分答案就是第三条:a type of ML techniques that use artificial neural networks。
p.5What machine learning is(定义)★定义题
Learn from (past) data to perform useful tasks, e.g. predicting (future) values, without using specific algorithms · seen data → model → unseen data · No need to design/program a specific algorithm
核心概念从(过去的)数据中学习以完成有用任务(例如预测未来的值),而不需要为手头的问题专门设计算法;监督学习用 seen data 建模型,去预测 unseen data 的结果。
详细讲解这段定义最容易被误解的是 "without using specific algorithms"。它不是说机器学习没有算法——梯度下降(p38)本身就是算法——而是说:你不需要为"预测分数"这个问题专门手写一套规则,规则(模型)是从数据里自动总结出来的。第二个要点是 seen data → model → unseen data:用见过的数据建模型,去预测没见过的数据的结果。这个"见过 → 没见过"的跳跃叫泛化(generalization),是整个机器学习的核心难题,到 Unit 6–7 讲 train / validation / test 时正式展开。
题目 / Tut / Lab 关联p7 的图把这段话画成流程;p32 的三步流程是它的操作版;试卷 Q8 用 training accuracy(96%)与 validation accuracy(60%)的差距考"seen 与 unseen 上表现不一致"——那就是过拟合。
必要扩展"supervised" 一词来自训练数据里带有"标准答案"(label),答案像老师一样监督学习过程;没有答案的就是 unsupervised(p26)。
易错点 · 理解提示答题写定义要带上 "from data" 和 "build a model" 两个关键词,漏掉任何一个都会被扣分。
p.6The term "machine learning"(一词的来历)常识题
Coined by Arthur Samuel, IBM, in 1959 · a program that played the game of checkers · He was not good at checkers! · The program learned by itself, and beat Samuel and checkers champions
核心概念"machine learning" 一词由 IBM 的 Arthur Samuel 于 1959 年提出;他写了一个下跳棋(checkers)的程序,程序通过自学击败了他本人和跳棋冠军。
详细讲解这个例子是整门课的"精神来源"。Samuel 写了一个下跳棋的程序,但他自己棋艺并不好——关键在于这不妨碍程序变强:程序通过大量对局,从结果中学习哪些走法更好,最终击败了 Samuel 本人乃至跳棋冠军。它证明了一件事:只要机器能从"做过的尝试和得到的结果"里改进,写程序的人就不必是领域专家。这正是今天你不需要懂"猫长什么样"的规则,也能训练出猫狗分类器的原因。
题目 / Tut / Lab 关联项目 Task 2 让你们自己采图并训练分类器——你就是那个"不擅长"的人类,模型自己从照片里学。Lab 1 不涉及。
必要扩展时间线:1956 年 Dartmouth 会议提出 "artificial intelligence";1959 年 Samuel 提出 "machine learning";2012 年 AlexNet 之后 DL 爆发(对应 p8 的"为什么是 2010 年代")。
易错点 · 理解提示填空三件套:Arthur Samuel · IBM · 1959。注意是跳棋 checkers,不是国际象棋 chess——国际象棋的例子出现在 p27 的强化学习里。
p.7Traditional software vs machine learning(范式对比)★画图题原图
The mechanism of traditional software · The mechanism of machine learning(整页是一张图)
核心概念传统软件:Data → Traditional software → Result;机器学习:Examples → Machine learning → Model(Training 阶段),Data → Model → Result(Prediction 阶段)。
详细讲解上半部分是传统软件的机制:人把知识写成程序,数据进去、结果出来,"智能"在 Traditional software 这个盒子里。下半部分是机器学习的机制,被拆成两个阶段:蓝色虚线框 Training——把 Examples 喂给 Machine learning 算法,产出 Model;红色虚线框 Prediction——把 Data 喂给 Model,产出 Result。差别一目了然:传统软件是"人写盒子",ML 是"机器造盒子",而造出来的盒子(Model)在预测阶段扮演了传统软件里"程序"的角色。Model 既是训练的输出、又是预测的输入,是整张图的枢纽。
① 传统软件 Data Traditional software Result ② 机器学习 Training Prediction Examples Machine learning Model Data
讲义 p7 原图:蓝色虚线框 = Training,红色虚线框 = Prediction;Model 是两个阶段共享的枢纽。
题目 / Tut / Lab 关联p12 是这张图的"术语升级版"。Lab 1 训练的 Python / NumPy 技能,就是在为 "Machine learning" 这个盒子写代码(p43–p49)。后面 Keras 的 model.fit() 对应 Training、model.predict() 对应 Prediction(p53;试卷 Q7 的代码正是这两步)。
必要扩展因为知识在 Model 里而不在代码里,所以同一个 Keras 程序换一份数据就能做完全不同的任务——这就是 p9 说的"便于定制化"。
易错点 · 理解提示考试画图题:务必画出两个虚线框并标 Training / Prediction,箭头方向别反(Examples → ML → Model;Data → Model → Result)。
p.8Enabling technologies(为什么是 2010 年代)★短答题
Much about ML/DL was known long ago; why do ML/DL succeed in 2010s but not earlier? · High processing power and cheap GPUs · Fast, large, cheap data storage · Massive available data, e.g. on the Web · New and improved algorithms and practices
核心概念ML / DL 的原理早就知道,2010 年代才成功的四个条件:算力(便宜 GPU)· 存储 · 海量数据 · 新算法与实践。
详细讲解这页回答一个自然疑问:神经网络几十年前就有雏形,为什么现在才火?答案是四个条件同时成熟。① 高处理能力和便宜的 GPU——GPU 原本为游戏渲染设计,它擅长的恰好是大量并行的小乘加,而神经网络的核心运算就是矩阵乘法(Unit 3 会讲)。② 快速、大容量、便宜的数据存储。③ 海量数据——互联网让标注数据变得可得(例如 ImageNet 有上百万张人工标注的图片)。④ 新的和改进的算法与实践(例如 ReLU 激活函数、更好的参数初始化,Unit 4–7 会讲)。一句话:DL = 旧算法 + 新燃料。
题目 / Tut / Lab 关联项目 Task 1 要求用 MobileNet 预训练模型做迁移学习——预训练模型正是"大数据 + 大算力"的产物;你们 25,000 张图不够从零训练,所以借用别人用海量数据学到的特征(p29–p30)。试卷 Q4c 提到 ReLU 的优点(计算快),属于第四点"改进的算法"。
必要扩展四个条件缺一不可,可以反推:数据少 → 容易过拟合(试卷 Q8);算力少 → 训练太慢。这也是课程强调"数据收集与准备占 50%–70% 资源"的原因(p11)。
易错点 · 理解提示短答题 "Why did ML/DL succeed in the 2010s but not earlier?" 的标准答案就是这四条,用英文关键词作答:GPUs / storage / massive data / improved algorithms。
p.9Benefits of ML (Google)
Reduce development time · Facilitate software customization for users · Help solve problems that we don't know how to solve manually
核心概念ML 的三大好处:缩短开发时间 · 便于定制化 · 解决人们不知道如何手动解决的问题。
详细讲解每条好处都配了同一个例子(语法检查器)的三种情境。① Reduce development time:获取大量"语法错误"的数据,比请语言专家写出所有语法规则容易得多。② Facilitate software customization:要适配另一种语言,只需换一批数据重新训练,而不是重写规则。③ Help solve problems we don't know how to solve manually:有些问题人根本写不出规则——图像分类就是典型,没有人能用 if-else 描述"什么是猫";但用数据训练模型却能做到。第三条最本质,前两条其实是它的副产品。
题目 / Tut / Lab 关联项目 Task 2 要你们自己采图做分类——没有任何人能手写"识别这个小组的水瓶"的规则,只能靠数据。p29 的 DL "自动发现高层特征"是第三条的延伸。Lab 1 不涉及。
必要扩展这三条来自 Google 的机器学习入门材料,很多教科书的"为什么用 ML"一节也有同样的表述。
易错点 · 理解提示"customization(定制化)"这个词容易被忽略,但它是第二条的关键词,答题要写出来。

B 部分|机器学习术语(p10–p23)

p.10分节页:Machine learning terminologies分节
Machine learning terminologies
核心概念第二部分:机器学习术语。
详细讲解接下来 p11–p19 是一条"从粗到细"的定义链:先说数据最重要(p11),用一张总图给出训练 / 预测的术语(p12),然后逐个定义 features(p13)、labels(p14)、examples 与 training / test set(p15),讨论特征的 relevant 与 examples 的数量(p16),最后把这些术语落在一页表格(p17)和矩阵 / 向量记号上(p18–p19)。p20–p23 转向"数据类型"——它决定了任务的类型。
题目 / Tut / Lab 关联Course Review p3 第一条 "Training (features) and prediction (labels)" 与第二条 "Two types of data" 都出自这一部分。试卷 Q7a(输入数据的维度)考 p18。
必要扩展这些术语在不同教材里有不同叫法,讲义把同义词都列出来了(p13–p15);考试用哪个都对,但要认得题目里出现的任何一个。
易错点 · 理解提示本部分是全讲"名词解释"最密集的地方,建议做一张同义词卡片:features / attributes / properties / independent variables / dimensions / covariates。
p.11Machine learning is all about data
Data have a critical role in all ML systems · Data collection and preparation may take up 50% to 70% of resources in an ML project · Many data terminologies (features, labels, samples) applicable to other types of ML
核心概念数据在所有 ML 系统中起关键作用;数据收集与准备可能占项目资源的 50%–70%。
详细讲解初学者以为机器学习 = 调模型,实际项目里最花时间的是拿数据、清洗数据、标注数据。原因有二:模型只能学到数据里有的东西(garbage in, garbage out),而标注往往需要人工(p16 会讲为什么贵)。讲义还提醒:features、labels、samples 这些术语虽然是在监督学习里定义的,但同样适用于其他类型的 ML——所以花时间把它们弄清楚是划算的。
题目 / Tut / Lab 关联项目 Task 2 占项目分的 35%,核心就是"数据集的采集与标注"——这是把 p11 的 50%–70% 直接变成了分数。Lab 1 Q2c / Q2d 让你生成 10000 个随机数并画直方图——这是在"制造并检查数据"。
必要扩展数据准备的常见步骤:清洗(去重、补缺失值)、变换(归一化 p45)、切分(p32、p45)。
易错点 · 理解提示50%–70% 这个数字适合作为短答题的一个具体例证。
p.12Terminologies and notations(术语总图)★画图题原图
Training: Labelled examples (features + labels) → Supervised machine learning → Model · Prediction: Unlabelled examples (features) → Model → Labels(整页是一张图)
核心概念训练阶段:Labelled examples(features + labels)→ Supervised machine learning → Model;预测阶段:Unlabelled examples(features)→ Model → Labels。
详细讲解这页把 p7 的图用术语重画了一遍。训练阶段的输入是 labelled examples——每个样本既有 features(输入)又有 label(答案);经过 Supervised machine learning 得到 Model。预测阶段的输入是 unlabelled examples——只有 features 没有 label;Model 的输出就是预测出的 Labels。用本讲的分数例子来说:labelled example 是 (hour = 8, score = 43.7),unlabelled example 是 (hour = 15),模型输出的 label 是 score = 73.59(p51)。整张图记住一句话:训练吃"带答案的",预测吃"不带答案的"、吐出"答案"。
Training Prediction Labelled examples (features + labels) Supervised machine learning Model Unlabelled examples (features) Labels
讲义 p12 原图:与 p7 相比,Examples 被细分为 features + labels,输入输出都用了术语。
题目 / Tut / Lab 关联p17–p19 把这张图里的 features / labels / examples 写成 X、y、xᵢ 的记号。试卷 Q7a "State the dimensions of the input dataset" 问的就是 feature matrix 的形状 (20000, 8)——20000 个 examples、8 个 features。
必要扩展在 Keras 里,training 对应 model.fit(X_train, y_train),prediction 对应 model.predict(X_new);X 是 features,y 是 labels——变量名就是这套记号体系的惯例。
易错点 · 理解提示容易混:预测阶段 Model 的输出也叫 labels(是 predicted labels,p19 写作 y′ 或 ŷ),要与训练时人工给定的 labels 区分开。
p.13Features(特征)★名词解释
Features are data input into a model for making predictions · Also called attributes, properties, independent variables, dimensions, and covariates
核心概念features 是输入模型用来做预测的数据;又叫 attributes、properties、independent variables、dimensions、covariates。
详细讲解讲义用两个贯穿全讲的例子:收入预测(income prediction)的 features 有姓名、年龄、身高、受教育程度和年限;垃圾邮件检测(spam detector)的 features 有邮件正文、发件人地址、邮件长度。六个名字都要认识:统计学里叫 independent variables(自变量),因为它们是"输入";dimensions(维度)在数据表里指"一列"。注意 features 可以是文本(正文、姓名)、数值(年龄、长度)、类别(是否说法语)——类型本身不限制它能否做特征。
题目 / Tut / Lab 关联试卷 Q7 的数据有 8 个 features(等位时间、菜品质量……),Keras 里的 input_shape 对应它;p18 的 X 矩阵每一列是一个 feature;Lab 1 Q2b 练的"取第二列" arr[:, 1],取出来的正是一个 feature。
必要扩展特征的好坏直接决定模型的上限——p16 会说有些特征更 relevant,p29 说深度学习能自动学出好特征。
易错点 · 理解提示答题给定义时写 "input to a model for making predictions";同义词至少能写出两个。
p.14Labels(标签)★名词解释
Labels are results predicted by a model · Generally what we are interested in · Also called dependent variables, target variables, and responses
核心概念labels 是模型预测的结果,是我们真正关心的东西;又叫 dependent variables、target variables、responses。
详细讲解label 就是"你想预测的那个量":收入预测里是收入,垃圾邮件检测里是"是否垃圾邮件"。注意定义的措辞:labels 是模型"预测的结果"(results predicted by a model),并且一般是我们感兴趣的东西(what we are interested in)。统计学叫 dependent variables(因变量),因为它"依赖"于 features。三个同义词 target / response / dependent variable 都要认得。
题目 / Tut / Lab 关联试卷 Q1 的三小问全是在判断 label 的类型;Q7c 把 label 从 1–5 的整数改成 4.45 这样的小数,任务性质随之改变——这正是"label 决定任务"(p20)。p19 的 y 是 label 向量。
必要扩展label 的类型(类别 or 数值)决定了用哪种模型和算法(p20–p23),是全讲最重要的分岔点。
易错点 · 理解提示在训练集里 label 是人工给定的"标准答案";只有在预测阶段它才是"模型预测的结果"。两种语境都叫 label。
p.15Examples(样本)与 training set / test set★名词解释
Examples: input data to a ML algorithm · Also called observations, instances, cases, data tuples, data objects, and data points · Training set: a set of labelled examples (features + label) · Test set: a set of unlabelled examples (features only)
核心概念examples 是输入 ML 算法的数据;又叫 observations、instances、cases、data tuples、data objects、data points。training set = labelled examples 的集合;test set = unlabelled examples 的集合(只有 features),用于模型评估和预测。
详细讲解一个 example 就是"一行数据"——一个人、一封邮件、一张图(p17 的表格会让这个概念一目了然)。六个同义词在教材里都有,认得即可。重点是两个集合的划分:training set 的每个样本 = features + label,用来训练;test set 的每个样本只有 features,用来评估和预测。为什么训练集必须带 label?因为模型靠"预测与答案的差距"来学习(p37 的 error)。为什么测试集不给 label?因为要模拟真实使用场景——新来的数据没有答案。
题目 / Tut / Lab 关联项目 Task 1 明确规定:25,000 张带标签训练图再分成 training set 与 validation set,5,000 张测试图作 test set——这是 p32 说的 "three sets" 版本,Unit 6–7 会讲。试卷 Q8 用 training accuracy 与 validation accuracy 的差别判断过拟合。
必要扩展实际研究中 test set 通常也有标签(否则无法算准确率),只是训练时不用它。讲义定义强调"只有 features",是从"输入模型"的角度说的;答题按讲义原文,可补一句 "labels are used for evaluation"。
易错点 · 理解提示别把 example 和 feature 混为一谈:一个 example 包含多个 features(试卷 Q7:一个 sample 有 8 个 features)。
p.16Using examples(特征相关性、样本数量与成本)
Some features are more relevant and important · Feature selection or extraction is key in data preprocessing · In general, using more examples improves a model's performance · But it is expensive to obtain lots of examples, especially their labels
核心概念有些 features 更 relevant;feature selection / extraction 是预处理的关键;更多 examples 通常提升性能,但获取成本高(尤其是 label)。
详细讲解两个事实。第一,不是所有特征都有用:收入预测里年龄和受教育程度比姓名和身高 relevant 得多。无关特征会让模型学到噪声,所以预处理要做 feature selection(挑出有用的子集)或 feature extraction(变换出更有用的特征,比如 PCA,见 p26)。第二,数据越多通常越好,但很贵:敏感 / 机密信息难以获取,专业数据需要专家录入,标注尤其贵。这解释了 p11 的"50%–70%"。
题目 / Tut / Lab 关联p29–p30:深度学习的卖点就是自动发现高层特征,减轻人工选特征的负担。项目 Task 2 每人每类只拍 10–20 张,数据量小 → 过拟合风险 → 要用迁移学习、数据增强(试卷 Q8d 的答案之一)。
必要扩展"更多 examples 提升性能"有前提:数据质量要够,且分布要有代表性;单纯堆量不解决分布偏差。
易错点 · 理解提示selection(选)与 extraction(提取 / 变换)是两个词,别混。
p.17Table of data(把术语落在一张表上)★必看原图
整页是一张表:Name / Age / Height / Years of education / Speak French / Income,三行 Peter、Mary、David
核心概念一张 3 行 × 6 列的表:5 个 features(Name、Age、Height、Years of education、Speak French)+ 1 个 label(Income),共 3 个 examples。
详细讲解这是全讲最重要的一张图,因为它把 p12–p16 的所有术语落在一张具体的表上。表的每一行是一个 example(图中用大括号标 "3 examples");每一列是一个 feature(大括号 "5 features" 标在前 5 列下方);最后一列 Income 是 label(虚线框 + "Label")。图里还单独圈了 Peter 那一行 "An example" 和 Years of education 那一列 "A feature"。注意表里混用了多种数据类型:Name 是文本、Age / Height / Years of education / Income 是数值、Speak French 是 Yes / No。p18 把前 5 列写成矩阵 X,p19 把最后一列写成向量 y。
NameAgeHeightYears of educationSpeak FrenchIncome
An example →Peter201.7512No12000
Mary351.6220Yes35000
3 examplesDavid331.7016No28000
← 5 features(每列一个)← Label
题目 / Tut / Lab 关联Lab 1 Q2a / Q2b:np.arange(10,30).reshape(4,5) 造出一个 4×5 的二维数组,然后练习取单个元素、取一行、取一列、取中间一块——特征矩阵 X 就是这样一张二维表:行 = examples,列 = features。试卷 Q7a 的 (20000, 8) 就是这张表放大后的形状。
必要扩展真实数据表通常远大于此(20000 × 8),但结构完全相同。
易错点 · 理解提示⚠️ Name 这一列是 feature(p18 明确把它写进 x₁),别漏数——所以是 5 个 features 而不是 4 个。蓝框 = 讲义圈出的 "An example"(一行),绿框 = 讲义圈出的 "A feature"(一列),红框 = label。
p.18Feature matrix and feature vector(记号)★试卷 Q7a
A feature matrix denotes the features of a dataset as a matrix · 𝐗₃ₓ₅ = [Peter 20 1.75 12 No; Mary 35 1.62 20 Yes; David 33 1.70 16 No] · 𝐱 denotes the feature vector of a general example · 𝐱₁ = Peter 20 1.75 12 No
核心概念feature matrix X 用矩阵表示整个数据集的 features:3 个 examples × 5 个 features 写成 X₃ₓ₅;feature vector x 是一个 example 的 features;x₁ 是第 1 个 example 的 features。
详细讲解记号约定:大写粗体 X = 整个数据集的 features(矩阵),小写粗体 x = 一个样本的特征向量,带下标的 x₁、x₂、x₃ 分别是第 1、2、3 个样本。矩阵的形状读作 "3-by-5":(样本数, 特征数) = (3, 5)。每一行对应一个样本,每一列对应一个特征,所以 X 的第 i 行就是 xᵢ。这个"行 = 样本、列 = 特征"的约定贯穿整门课,Keras 里 fit(X, y) 的 X 也按此排列。
X = x₁ → Peter  20  1.75  12  No
x₂ → Mary  35  1.62  20  Yes
x₃ → David  33  1.70  16  No
   形状 (3, 5) = (n 个样本, d 个特征)
题目 / Tut / Lab 关联试卷 Q7a 答案 (20000, 8)。Lab 1 练的 reshape:arr.reshape((3, -1)) 让 NumPy 自动算出第二维;hours.reshape(-1, 1) 把 shape 为 (10,) 的一维数组变成 (10, 1) 的二维——sklearn 要求特征矩阵是二维时需要这步,p52–p53 的代码都用了它。
必要扩展矩阵形状 (n, d) 中 n 常表示样本数、d 表示特征数;Unit 3 的线性代数会正式讲矩阵乘法。
易错点 · 理解提示三级记号要分清:大写 X(矩阵)/ 小写 x(向量)/ 带下标 x₁(某一个样本);X₃ₓ₅ 的下标是 (行数, 列数)。
p.19Label vector(标签向量)
A label vector denotes the labels of a dataset as a vector, denoted by 𝐲 · 𝐲 = [12000 35000 28000] · 𝑦′ or ŷ denotes a predicted label
核心概念label vector y 把数据集的 labels 写成向量:y = [12000, 35000, 28000];y′ 或 ŷ 表示预测的 label。
详细讲解y 是一个列向量,第 i 个元素 yᵢ 是第 i 个样本的 label——与 X 的第 i 行 xᵢ 一一对应。ŷ 读作 "y-hat"(有的书写 y′),是模型对样本的预测值;真实值 y 与预测值 ŷ 之差就是 p37 的 prediction error。本讲的分数例子里 y = [43.7, 84.7, …],ŷ = m × hour + b。
题目 / Tut / Lab 关联代码里的变量名就是这套记号:p46 的 mean_squared_error(y, y2) 中 y 是实际值、y2 是预测值;p47 的 predicted = m * x + b 就是 ŷ。Lab 1 教的 f-string 调试 f"{y=}" 可以在训练循环里打印变量。
必要扩展在 Keras 里,y_train、y_test 就是 label 向量;分类任务里 y 通常还会被转成 one-hot 向量(试卷 Q6 的答案)。
易错点 · 理解提示y 是真实值、ŷ(或 y′)是预测值;MSE 里两者相减再平方,顺序无所谓,但在梯度公式里是 predicted − y,顺序决定更新方向。
p.20Categorical and numerical data(两类数据)★复习课点名
Two main types of data in ML · Each of features and labels can be either categorical and numerical · Different types of labels demand different ML models and algorithms
核心概念两类数据:类别型(categorical)与数值型(numerical);features 和 labels 各自都可以是任一种;label 的类型决定用哪种模型。
详细讲解这页只有三句话,但第三句是整个机器学习"任务分类"的根:不是 feature 的类型、而是 label 的类型决定了任务与模型。为什么?因为模型要做的事就是"输出一个 label"——label 是类别就得输出类别、是数值就得输出数值,输出层和损失函数随之不同(Unit 4–5)。用表格列出来更清楚:feature 类别 / 数值、label 类别 / 数值,2×2 四种组合都可能出现,但只有 label 那一维决定任务类型。
categorical labelnumerical label
categorical features例:用"是否说法语"预测"是否录取"例:用"是否说法语"预测收入
numerical features例:用邮件长度预测"是否垃圾邮件"例:用年龄、身高预测收入
题目 / Tut / Lab 关联试卷 Q1 与 Q7 都是"看 label 定任务"的题:Q1a 等级 A–F 是 categorical;Q1b 租车数量是 numerical;Q7 里 1–5 的整数评分,题目特意说明 "Each rating value represents a discrete satisfaction category"——虽然是数字,但表示类别,仍是 categorical!
必要扩展Course Review p3 原文:"Two types of data ➢ Categorical (discrete) ➢ Numerical (continuous)"——括号里的两个词是同义词,考试两个名字都要认得。
易错点 · 理解提示⚠️ "看起来是数字" ≠ "数值型":邮编、学号、1–5 的等级评分都是 categorical。判断标准是"求平均有没有意义"。
p.21Categorical data(类别型数据)
Categorical feature or label is a data field that can take on a finite number of possible values (classes or categories) · Also called a discrete variable
核心概念类别型 feature 或 label 只能取有限个值(classes / categories);又叫 discrete variable(离散变量)。
详细讲解定义的关键词是 finite number of possible values:取值范围是有限的、可列举的。最常见的是二值(Yes / No、spam / not spam)。例子:收入预测里"是否说法语"、垃圾邮件检测里"是否垃圾邮件"(这是输出)。注意类别之间没有大小或顺序关系——"说法语"并不比"不说法语"大。
题目 / Tut / Lab 关联试卷 Q1a(5 个等级)、Q1c(欺诈 / 合法);Q6 的 one-hot encoding 是把类别标签转成向量喂给网络;Q1 的第 2、3 列(输出层神经元数、激活函数)要用 Unit 4–5 的知识,第一列全是本讲内容。
必要扩展有序类别(ordinal)如等级 A–F 有顺序,在这门课里仍按 categorical 处理(多分类)。
易错点 · 理解提示categorical = discrete = 类别,三者是同一个东西的三个名字。
p.22Numerical data(数值型数据)
Numerical feature or label is a data field that has a numerical value (integer or floating point) · Often take on an infinite number of possible values · Also called a continuous variable
核心概念数值型 feature 或 label 具有数值(整数或浮点数),常可取无穷多个值;又叫 continuous variable(连续变量)。
详细讲解数值型的本质是"可以做算术":求平均、比大小都有意义。例子:身高、受教育年限(features),收入(label),邮件长度(feature)。讲义用 "often take on an infinite number of possible values"——是"常常"而不是"一定",因为整数这种可数的取值也是数值型。
题目 / Tut / Lab 关联试卷 Q7c 把 label 从整数 1–5 改成小数 4.45——类别变成连续值,任务从分类变成回归,代码要改四处(试卷答案)。Lab 1 Q2c 的 np.random.randn(10000) 生成的就是连续型数值(正态分布)。
必要扩展本讲的分数例子(p33)里,feature(学习小时数)和 label(分数)都是 numerical,所以是回归任务。
易错点 · 理解提示numerical = continuous;判断一个数据是 categorical 还是 numerical 时,先看它是 feature 还是 label,再判断。
p.23Classification and regression(分类与回归)★试卷 Q1 原题出处
There are two types of supervised ML · Classification is predicting a categorical label · Binary/binomial: label in 1 of 2 classes · Multiclass/multinomial: label in 1 of ≥ 3 classes · Regression is predicting a numerical label
核心概念监督学习的两种类型:classification 预测 categorical label(binary = 2 类;multiclass = ≥ 3 类);regression 预测 numerical label。
详细讲解这是 Unit 1 最常考的一页,也是试卷 Q1 的直接出处。判断任务类型的流程只有两步:看 label → categorical → classification → 有几类?2 类是 binary,3 类及以上是 multiclass;看 label → numerical → regression。讲义的两个例子:垃圾邮件检测是 binary classification;收入预测是 regression。"classification" 是把一个给定的 feature vector 归到 label 的某一类(class or category)里;"regression" 这个词来自统计学,在这里就是"确定 label 的数值"。记忆法:分类 = 把样本放进某个格子;回归 = 在数轴上找一个点。
看 label 的类型
→
categorical
→ Classification
→
2 类 → Binary
≥ 3 类 → Multiclass
看 label 的类型
→
numerical
→ Regression
题目 / Tut / Lab 关联试卷 Q1(12 分):a) 等级 A–F → multiclass classification;b) 每小时租自行车数 → regression;c) 信用卡欺诈 → binary classification(完整答案见文末"试卷相关题")。项目三个任务全是 classification(Task 1:50 类 multiclass;Task 3 若做文本分类也是 classification)。p53 的代码是 regression 的 Keras 写法;试卷 Q7c 的标准答案几乎就是 p53 的代码。
必要扩展Unit 2 的 logistic 回归名字里有 "regression" 但做的是 classification(输出概率);Unit 4–5 会讲输出层与损失函数的搭配:回归 → 1 个神经元 + linear + MSE;二分类 → 1 个 + sigmoid + binary cross-entropy;多分类 → 类别数个 + softmax + categorical cross-entropy。
易错点 · 理解提示⚠️ 不要根据 feature 的类型判断任务;binary 的"2 类"与 multiclass 的"≥ 3 类"这两个阈值要记准。

C 部分|三类机器学习与深度学习(p24–p30)

p.24分节页:Three types of machine learning分节
Three types of machine learning
核心概念第三部分:机器学习的三种类型。
详细讲解上一部分按"label 是什么"分任务(classification / regression);这一部分换一个维度:按"有没有 label、怎么学"把整个 ML 分成三类——supervised(有 label,学预测)、unsupervised(无 label,找模式)、reinforcement(有 reward,学决策)。注意两个分类维度不同:classification / regression 是监督学习的两个子类(p23、p25),不是与三类并列的东西。
Machine learning Supervised learning Classification · Regression Unsupervised Clustering · … Reinforcement Agent · Reward
本部分的结构树:三类 ML;分类/回归只是监督学习下面的两个子类。
题目 / Tut / Lab 关联Course Review p3 "Three types of ML"。试卷 Q1 是 supervised;Lab 2(t02)训练的也是 supervised 模型。
必要扩展深度学习(p30)三类任务都能用——"DL" 与 "supervised" 不是并列关系。
易错点 · 理解提示考试问 "types of ML" 答三类;问 "types of supervised ML" 答两类(classification、regression)——别答串。
p.25Supervised learning(监督学习)★复习课点名
Supervised learning is to make predictions using a model that associates input data (features) with output data to predict (labels) · Classification: spam detection, image classification, cancer diagnosis · Regression: predicting income from personal particulars, predicting the price of real estate
核心概念用一个把 features 与 labels 关联起来的模型做预测;两类:classification(垃圾邮件、图像分类、癌症诊断)与 regression(收入、房价)。
详细讲解定义的关键词是 associates:模型学的就是"输入 → 输出"的映射(association)。讲义给的例子值得全记——classification:spam detection, image classification, cancer diagnosis;regression:predicting income from personal particulars, predicting the price of real estate。这些例子在考试题干里会"换皮"出现(试卷 Q1 的"预测等级 / 租车数 / 欺诈"就是换了三个场景)。
题目 / Tut / Lab 关联试卷所有建模题(Q1、Q6、Q7、Q8)都是监督学习;项目的三个任务也是。
必要扩展"supervised" = 训练数据带 label(p12 的 labelled examples)。回答 "What is supervised learning?" 的模板:一句定义 + 两个子类 + 各一个例子。
易错点 · 理解提示把 p23 的两个子类和这一页的四个例子连起来记:classification ↔ spam / image / cancer;regression ↔ income / real estate price。
p.26Unsupervised learning(无监督学习)
Unsupervised learning is to identify patterns from data (unlabelled examples) · Clustering: T-shirt size design, grouping customers (k-means) · Association analysis: outlier analysis, dimensionality reduction (principal component analysis)
核心概念从(无标签的)数据中识别模式;两大类:clustering(k-means;T 恤尺码设计、客户分组)与 association analysis(离群点分析、降维 PCA)。
详细讲解没有 label,就没有"标准答案"可对照,算法只能找数据内部的结构。Clustering:把相似的点分成组(clusters)——例:按人体数据分组来设计 T 恤尺码、按客户分组做营销,经典算法 k-means。Association analysis:探索属性之间的关系——讲义举了 outlier analysis(找异常点)和 dimensionality reduction(降维,减少特征 / 维度,方法如 principal component analysis,PCA)。为什么降维属于"无监督"?因为它不需要 label,只根据特征之间的相关性来压缩数据。
题目 / Tut / Lab 关联p29 的图右侧同时标了 "unsupervised learning" 与 "supervised learning"——低层的特征提取不需要标签,顶层的分类需要标签。Unit 12 的 autoencoder / GAN(Course Review p10)也属于无监督 / 生成式学习。
必要扩展clustering 与 classification 的区别:classification 的类别是预先定义的(由 label 给出);clustering 的"类"是算法自己发现的,事先不知道有几类(k-means 的 k 要你定)。
易错点 · 理解提示别把 clustering 当成 classification;答题写两大类名字 + 各一个例子即可。
p.27Reinforcement learning(强化学习)原图
Reinforcement learning is to develop a system (an agent) that improves performance by interacting with the environment · The agent performs actions, while the environment has states and provides rewards · E.g. a chess engine
核心概念开发一个通过与 environment 交互来提升性能的 system(agent);agent 执行 actions;environment 有 states 并给出 rewards(对 action 好坏的反馈);例子:国际象棋引擎。
详细讲解看图的箭头方向:Environment → Agent 有两条向下的箭头 Reward 和 State(环境把"现在棋盘什么样"和"上一步走得好不好"告诉 agent);Agent → Environment 一条向上的箭头 Action(agent 走一步棋)。与监督学习最大的区别:没有"每一步的正确答案"(label),只有延迟、稀疏的奖励——整局棋只有最后"赢 / 输"这一个 reward,agent 要自己推断是哪一步导致了胜负。三个词的角色:agent = 学习者 / 决策者;environment = 它所处的世界;reward = 反馈信号。
Environment Agent Reward State Action
讲义 p27 原图:Reward 与 State 从环境流向 agent,Action 从 agent 流向环境。
题目 / Tut / Lab 关联Unit 12 会讲 deep reinforcement learning(Course Review p10);本讲只需分得清它与 supervised / unsupervised 的区别。
必要扩展典型应用:游戏(围棋)、机器人控制、推荐系统。深度强化学习 = 用神经网络(DL)来估计"某个状态下某个动作的价值"。
易错点 · 理解提示⚠️ reward 不是 label:label 告诉你正确答案,reward 只告诉你好或坏。短答题三个关键词:agent、environment、reward。
p.28分节页:What deep learning is分节
What deep learning is
核心概念第四部分:深度学习是什么。
详细讲解前三部分讲的是整个 ML 领域;从 p29 起,镜头推到 DL——这门课的主角。只有两页:p29 给定义和"逐层提取特征"的核心思想;p30 补充三个性质(三类任务都能用、自动特征、适合大数据)。p4 那个最内圈的椭圆在这里被展开。
题目 / Tut / Lab 关联课程大纲 Topic 1 明确写了 "Comparison between shallow and deep learning"——所以 p29–p30 可能以短题出现。
必要扩展后续 Unit 2–12 讲的都是 DL 的各种架构(DNN、CNN、RNN、autoencoder、GAN)。
易错点 · 理解提示把 p29 的定义与 p4 的第三条 bullet 对照着背,两者是同一句话。
p.29Deep learning(定义与逐层特征)★定义题原图
Deep learning is a type of ML technique that uses artificial neural networks, ANN or NN · It uses multiple layers of operations to gradually convert raw features to higher-level, more complex, and more meaningful features · E.g. in image classification, layers of deep learning turn feature of raw pixels to lines
核心概念DL 是使用人工神经网络(ANN or NN)的 ML 技术;用多层运算把 raw features 逐步转换为 higher-level、更复杂、更有意义的 features;图像分类里:raw pixels → lines → …
详细讲解看图(Wikipedia 的经典图):最底层 Inputs 是三张照片(大象、狗、企鹅)——只有像素;往上一层出现线条 / 边缘;再往上是局部部件的组合;再往上是完整的物体轮廓;最顶层 Labels 输出 Penguin / Elephant / Kangaroo。左侧竖排文字 "increasingly complex features" 说明特征逐层变复杂;右侧 "unsupervised learning / supervised learning" 表示低层的特征学习不需要标签、顶层的分类需要标签。讲义第三条 bullet 只说了第一步(像素 → 线条),图则画出完整链条。核心思想:每一层把下一层的输出当作输入,提取更抽象的特征——所以需要"多层",这就是 "deep" 的含义。
increasingly complex features supervised / unsupervised learning Inputs:原始像素 线条 / 边缘 局部部件 整体轮廓 Penguin Elephant Kangaroo Labels
讲义 p29 原图(示意重绘):从左到右特征逐层变复杂,最后一层输出 labels。
题目 / Tut / Lab 关联项目 Task 1 的 MobileNet 预训练模型:它的卷积层就是这些"逐层特征"的成品——底层识别边缘、中层识别纹理、高层识别物体部件,你们只是替换最后的分类层。Unit 8–9(CNN)会讲这些层怎么算。
必要扩展对比 p16:传统 ML 要人工做 feature selection / extraction;DL 把这一步也交给模型学——这就是 shallow 与 deep 的本质差别。
易错点 · 理解提示"ANN" 与 "NN" 两个缩写都要认得;图中最上层的 "labels" 就是 p14 的 label。
p.30Deep learning (cont.)(三个补充性质)★短答题
Can be used in supervised, unsupervised, and reinforcement learning tasks · Automatic discovery of high-level features alleviating the need for selecting and extracting features · Particularly suitable for complex machine learning problems that involve huge amounts of data · May ... involve tens or hundreds of layers
核心概念DL 可用于 supervised / unsupervised / reinforcement 三类任务;自动发现高层特征,减轻特征选择与提取的需求;特别适合涉及海量数据的复杂问题,可能有几十到几百层。
详细讲解三条性质逐条理解。① "Can be used in supervised, unsupervised, and reinforcement learning tasks"——DL 是方法,三类任务是问题类型,二者是正交的:别把 "DL" 与 "supervised learning" 当成并列的两类(p24 的三类是 ML 的分类,DL 只是 ML 的子集,p4)。② "Automatic discovery of high-level features"——好处是省去人工特征工程(对比 p16);代价是需要更多数据。③ "Particularly suitable for … huge amounts of data"——层多、参数多,小数据容易过拟合;可能几十到几百层,所以叫 deep。
题目 / Tut / Lab 关联p8 的四个 enabling technologies 解释了"为什么现在才能这么干";项目 Task 1:25,000 张图对从零训练来说太少 → 用迁移学习(借用在大数据上学到的特征);试卷 Q8 讨论过拟合(数据少 / 模型复杂时发生)。
必要扩展短题 "State two advantages of deep learning over traditional ML":automatic feature discovery;suitable for complex problems with huge amounts of data。反过来问缺点:需要大量数据与计算能力。
易错点 · 理解提示"DL = supervised learning" 是错的;也不存在"DL 只能做分类"这回事——文本生成(项目 Task 3 的选项之一)也是 DL。

D 部分|训练一个线性回归模型(p31–p41)

p.31分节页:Training a ML model分节
Training a ML model
核心概念第五部分:训练一个机器学习模型(以线性回归为例)。
详细讲解这是全讲最"硬"的一段,也是复习课点名的 "Gradient descent"。逻辑链:p32 给出通用三步流程(切分 → 训练 → 评估);p33–p35 用分数预测例子说明人类会怎么做;p36 把人类的"画条直线"写成数学模型;p37 把"画得好不好"量化成 MSE;p38–p39 用梯度下降和学习率把"找最好的直线"变成可执行的迭代;p40 总结哪些是人设的超参数。一句话:把"人凭直觉画线"翻译成"机器按规则迭代"。
题目 / Tut / Lab 关联试卷 Q7(回归代码);Lab 1 的 NumPy 技能(附录 p43–p53 全部要用)。
必要扩展这套流程(model → loss → optimizer)就是后面所有 Keras 代码的三要素:compile(loss=..., optimizer=...)。
易错点 · 理解提示读 p33–p40 时始终带着一个问题:"这一步把人类的哪一步直觉变成了数学?"
p.32Model training(训练流程三步)★必背
Labelled examples (features plus labels) are input into an algorithm to train a model, which is then used to make predictions from unlabelled examples · 1) Partition examples into a training set and a test set · 2) Train, or fit, the model using the training set · 3) Evaluate the model using the test set · A more robust process splits examples into three sets
核心概念把 labelled examples 输入算法来训练模型,再用模型对 unlabelled examples 预测。基本流程三步:① 切分 training set / test set → ② 用 training set 训练(train / fit)→ ③ 用 test set 评估。更稳健的流程切三个集合(后面讲)。
详细讲解三步流程里有两个考点。第一,"train" 与 "fit" 是同义词——sklearn 和 Keras 的方法都叫 fit(),讲义用 train,考试两个词互换。第二,为什么必须先切分再训练?因为评估必须在模型"没见过"的数据上做(p5 的 unseen data),否则模型把训练数据背下来也能拿高分——这就是过拟合(试卷 Q8:Model A 训练准确率 96%、验证准确率只有 60%)。"A more robust process splits examples into three sets" 指 training / validation / test:validation 用来调超参数和判断何时停止训练,test 只在最后用一次——Unit 6–7 讲。
① Partition
切成 training set 与 test set
→
② Train / fit
用 training set 训练模型
→
③ Evaluate
用 test set 评估
题目 / Tut / Lab 关联项目 Task 1 的要求就是这段话的实践:"divide the 25,000 training images into the training set and the validation set … use the 5,000 test images as the test set"。试卷 Q8a–c:判断 underfitting / overfitting 必须同时看 training 与 validation accuracy。
必要扩展代码层面常用 train_test_split(X, y, test_size=0.3)(scikit-learn)完成第一步;Keras 的 validation_split 或 validation_data 参数对应"三个集合"。
易错点 · 理解提示⚠️ 顺序不能反:先切分再训练。训练集参与训练,验证集参与调参,测试集在最终评估之前谁都不许碰。
p.33Score prediction example(数据表)🧮数据Lab 1
Predicting a course score (label) from the number of study hours per week (feature) · We collected the following data of 10 examples
核心概念用每周学习小时数(feature)预测课程分数(label);10 个 examples。
详细讲解读表:横轴 index 0–9 是 10 个 samples;Hour 是 feature(x),Score 是 label(y)。把每一列竖着读,就得到 10 个 labelled examples:(8, 43.7)、(16, 84.7)、(12, 61.7)、(9, 48.2)、(8, 47.2)、(12, 54.4)、(12, 55.4)、(5, 29.7)、(9, 45.4)、(4, 29.6)。观察规律:Hour 越大,Score 总体越高(正相关);但同一个 Hour 对应的 Score 不一样(12 小时有 54.4、55.4、61.7 三个分数)——说明数据带噪声。这份数据不是真实调查,而是 p43 的代码生成的:score = 4.5 × hour + 10 + 噪声(均值为 0、标准差为 5 的正态分布),再保留一位小数。下表把"隐藏的真规则"摊开(噪声一列是我按生成代码复算的):
indexHour (x)真值 4.5×hour+10噪声Score (y,观测值)
0846.0−2.3543.7
11682.0+2.7184.7
21264.0−2.3261.7
3950.5−2.3348.2
4846.0+1.2147.2
51264.0−9.5754.4
61264.0−8.6255.4
7532.5−2.8129.7
8950.5−5.0645.4
9428.0+1.5729.6
题目 / Tut / Lab 关联Lab 1 Q2c / Q2d:np.random.seed(42) + np.random.randn(10000) 生成标准正态分布并画直方图——这里的噪声就是同一种分布(均值 0、标准差 5)。Lab 1 练的列表下标 0–9 与表中 index 一致。
必要扩展真实数据来自调查 / 实验;教学用"已知真规则的模拟数据",这样可以检验模型学到的参数 (m, b) 是否接近真值 (4.5, 10)——结果是 (4.29, 9.25),很接近但不相等,因为只有 10 个带噪声的样本(见 p51)。
易错点 · 理解提示feature = Hour,label = Score,label 是数值 → 这是 regression(用 p23 的判断流程验证一遍)。
p.34Score prediction example (cont.)(散点图与问题)原图
The 10 examples are plotted below · How can we use them to predict the score if one studies 15 hours per week?
核心概念10 个 examples 的散点图;问题:如何用它们预测每周学习 15 小时的分数?
详细讲解读图:横轴 Weekly study hours(0–20),纵轴 Scores(0–100);10 个点大致沿一条斜线分布,小时数越多分数越高。问题"学 15 小时得多少分"的难点在于:数据里没有 Hour = 15 的样本(只有 12 和 16)——所以不能直接查表,需要一个模型来"插值"。任何合理的模型都应给出 60 分(12 小时)到 85 分(16 小时)之间的数。这就是"预测 unseen data"。
0.02.55.07.510.0 12.515.017.5 20.0 020406080100 Weekly study hours Scores 15 小时 → 多少分? ?
讲义 p34 原图(按真实数据重绘):蓝色点是 10 个 examples;红色虚线是我加的——x = 15 处没有任何样本,这就是为什么需要模型。
题目 / Tut / Lab 关联p44 的代码用 plt.plot(hours, scores, "o") 画出这张图;Lab 1 Q2d 用 plt.hist 画直方图——都是 matplotlib 的"先看数据"习惯。p35–p36 给出对这一问题的回答。
必要扩展15 小时在数据范围 [4, 16] 之内 → 叫内插(interpolation);如果问 30 小时 → 外推(extrapolation),线性模型外推很危险(分数会超过 100)。
易错点 · 理解提示先画散点图再选模型——这是做回归的第一步。
p.35Human thought process(人类思路三步)
1) Observe that the data points roughly lie on a straight line · 2) Draw a straight line that best fits the points · 3) Use the line to read the score for studying 15 hours
核心概念合理的人类思路:① 观察到数据点大致在一条直线上 → ② 画一条最拟合的直线 → ③ 用这条直线读出 15 小时对应的分数。
详细讲解这三步看似平常,其实分别对应机器学习的三件事:第 ① 步是选模型(假设 feature 与 label 线性相关——p36 的 linear regression);第 ② 步是训练("best fits"需要一个好坏标准 p37 + 一个寻找方法 p38);第 ③ 步是预测(把 x = 15 代入方程 p51)。人类靠目测完成第 ② 步,机器需要把"目测"量化。这三步是理解 p36–p51 的纲。
题目 / Tut / Lab 关联p36(直线 → 方程)、p37("最好" → MSE)、p38–p39("画线" → 梯度下降迭代)、p40(步长与次数由人设)。
必要扩展如果第 ① 步观察到的不是直线而是曲线(例如分数随小时数先快后慢),就应换非线性模型(例如多项式回归或神经网络)。
易错点 · 理解提示第 ① 步是一个假设(assumption)——线性回归 "works when features are linearly related to the label"(p36 原文)。
p.36ML straight line model: linear regression★核心公式原图
Linear regression is a ML model that works when features (xᵢ) are linearly related to the label (y) · Simple linear regression has 1 feature: y = mx + b, where m is slope and b is y-intercept, e.g. score = m × hour + b · To train the model means to determine the best values for m and b · Multiple linear regression: y = m₁x₁ + m₂x₂ + m₃x₃ + ⋯ + b
核心概念linear regression 适用于 features (xᵢ) 与 label (y) 线性相关的情形;simple linear regression 只有 1 个 feature:y = mx + b(m 斜率,b y 轴截距),例:score = m × hour + b;训练 = 找到最好的 m 和 b;multiple linear regression:y = m₁x₁ + m₂x₂ + m₃x₃ + ⋯ + b。
详细讲解人类"画一条直线",在数学上就是确定两个数:m 和 b——它们是这个模型要学的全部参数(parameters)。看讲义的三幅小图:左图 y = mx + b——横坐标走 1 个单位、纵坐标上升 m(斜率),直线与 y 轴交于 b(截距);中图一组平行线,箭头 b 表示"b 变大 → 直线整体上移,斜率不变";右图几条绕同一点旋转的直线,箭头 m 表示"m 变化 → 直线旋转"。所以"找最好的直线" = 在所有 (m, b) 组合里挑一对。"simple" 的意思是只有 1 个 feature,不是"简单";有多个 feature 时叫 multiple linear regression,每个 feature 配一个系数。
xy y = mx + b 1m b b:上下平移 m:旋转
讲义 p36 三幅小图(重绘):左 = 斜率 m 与截距 b;中 = 改变 b 使直线上下平移;右 = 改变 m 使直线旋转。
题目 / Tut / Lab 关联Unit 2 的 logistic 回归 y = σ(mx + b) 是同一形式加一个 sigmoid;Unit 3 用微积分推导 MSE 对 m、b 的梯度(p47 的两行代码);Unit 4 的 Dense(1) 层计算的就是 y = wx + b(w = m);试卷 Q7c 回归输出层 Dense(1, activation="linear") 就是线性函数。
必要扩展本讲代码里的变量名 m、b 与 Keras 的 weight、bias 一一对应:m ↔ kernel(权重),b ↔ bias(偏置)。p53 的 get_weights() 返回 [[4.23927]], [9.201929],前者是 m、后者是 b。
易错点 · 理解提示m 是斜率、b 是截距,别写反。"训练 = 确定 m 和 b 的值"这句话是 p40 "parameter vs hyperparameter" 的基础。
p.37ML model goodness: prediction errors(误差与 MSE)★核心公式原图
Prediction error is the difference between predicted and actual values · Provide a performance measure of the machine learning model · Form the loss function or cost function of the model · Mean squared error: MSE = (1/n) Σ (yᵢ − yᵢ′)²
核心概念prediction error = 预测值与实际值之差,是模型性能的度量;误差汇总成 loss function / cost function;MSE = (1/n) Σ (yᵢ − yᵢ′)²(yᵢ 实际值,yᵢ′ 预测值,n 预测个数)。
详细讲解看图:实心点是 actual value y,空心点是 predicted value y′(落在直线上),两者之间的竖直距离就是 Error——预测偏高或偏低都会产生误差。但"误差"有正有负,单看每个样本的误差无法比较两条直线谁更好。于是需要一个汇总指标:把所有误差平方后求平均,这就是 Mean Squared Error。为什么平方?① 正负误差不会互相抵消;② 大误差受到更重的惩罚;③ 平方函数处处可导,便于求梯度(p38 的梯度下降需要导数)。为什么除以 n?让数值与样本数量无关,便于不同数据集之间比较。MSE 越小,直线拟合得越好。
MSE = (1/n) · Σi=1..n (yi − yi′)²    yi = actual value · yi′ = predicted value · n = number of predictions
Actual value y Predicted value y′ Error
讲义 p37 原图(重绘):实心 = 实际值,空心 = 预测值(在直线上);一个预测偏低、一个预测偏高,但误差都算数。
题目 / Tut / Lab 关联p46 的 mean_squared_error 代码;p49 表里的 error 列就是 MSE;Keras 里 loss="mse"(p53;试卷 Q7c 答案 mean_squared_error)。
必要扩展同一族的其他损失:MAE(平均绝对误差,p53 的 metrics=["mae"])、RMSE(均方根误差,单位与 label 相同);分类任务用 cross-entropy(Unit 5)。loss function 与 cost function 在本讲同义。
易错点 · 理解提示⚠️ MSE 的单位是"label 的平方"(本例是"分数的平方"),要与 RMSE 区分;MSE 永远 ≥ 0,越小越好。
p.38ML finding the best: gradient descent optimizer★复习课点名原图
Gradient descent is an optimizer that determines optimal parameter values in iterations · Update parameters to reduce loss function · Use the slope, or gradient, of the curve at the current parameter value · Negative gradient → increase parameter · Positive gradient → decrease parameter
核心概念gradient descent 是一种 optimizer,在迭代中确定最优参数值——更新参数以降低 loss function;用当前参数值处曲线的斜率(gradient):负梯度 → 增大参数;正梯度 → 减小参数。
详细讲解先看懂图的坐标轴:横轴是参数(例如 m 的取值),纵轴是loss(把每个 m 代入 MSE 算出的损失)——这条碗形曲线不是数据散点图,而是"参数好坏地图"。三张小图讲了一个完整故事:① 小球在左壁,往左还是往右?② 左壁的切线是下坡(negative slope),往右走 loss 下降 → "increase parameter";③ 小球在右壁,切线上坡(positive slope),往左走 → "decrease parameter"。把两种情况合成一个公式:新参数 = 旧参数 − 学习率 × 梯度。梯度为负时,"减去一个负数"就是增大;为正时就是减小——符号自动给出正确方向。因为每一步只看"当前位置的斜率",所以必须迭代,一步一步走向碗底。
new parameter = old parameter − learning rate × gradient  (本讲两个参数:m 和 b 各更新一次)
LossParameter LossParameter LossParameter ?? Negativeslope Increaseparameter Positiveslope Decreaseparameter
讲义 p38 原图(重绘):① 往哪边走?② 左壁:斜率为负 → 增大参数;③ 右壁:斜率为正 → 减小参数。
题目 / Tut / Lab 关联p47 的代码 new_m = m - learning_rate * m_gradient 就是这条公式;Unit 3 讲微积分求梯度;Unit 6–7 的 optimizer(sgd / momentum / adam / RMSprop)都是梯度下降的改进版(Course Review p7 "Gradient descent with momentum");试卷 Q4b 的 vanishing gradient 也是"梯度"在反向传播中的问题。
必要扩展"optimizer" 就是负责更新参数的算法;本讲"全部数据一起算梯度"的方式叫 batch gradient descent,Keras 里的 "sgd" 是随机 / 小批量版本。
易错点 · 理解提示⚠️ 记准方向:负梯度 → 增大参数。另外注意横轴是参数、纵轴是 loss,不要与 p34 的数据散点图混淆。
p.39ML finding the best: learning rate★复习课点名原图
Learning rate is the amount of change to increase or decrease a parameter value · Too small the learning rate → learning is too slow to obtain useful parameter values in practical time · Too large the learning rate → parameter values bounce and algorithm does not learn
核心概念learning rate 是增大或减小参数值时的改变量;太小 → 学得太慢;太大 → 参数值来回弹跳(bounce)、学不到东西。
详细讲解三张小图对应三种学习率:① 太小——每一步只挪一点点,要走非常多的步才能接近碗底,"在可行时间内学不到有用的参数";② 合适——几步就稳定在碗底;③ 太大——一步跨过碗底冲到对面,再一步又弹回来,在两壁之间来回跳,永远落不下去,"algorithm does not learn"。学习率本身不是学出来的,是人设的(p40 的 hyperparameter)。那么本讲用 0.005(p49)合不合适?我复算的结论:对这份数据,普通梯度下降的稳定上限约为 0.0097——0.01 就会发散(数字越滚越大直到溢出),0.005 大约是上限的一半,所以讲义选它;但它也只是"不发散",收敛并不快(p49 要 10000 轮)。原因和解决办法见 p45 的归一化。
LossParameter LossParameter LossParameter
讲义 p39 原图(重绘):① 太小——碎步慢走;② 合适——几步到底;③ 太大——在两壁之间弹跳。
题目 / Tut / Lab 关联p40 把它列为 hyperparameter 的例子;p49 的 learning_rate = 0.005;p53 的 Keras 用 RMSprop(learning_rate=.1)——那是"自适应"优化器,每个参数有自己的有效步长,不能与这里的普通梯度下降直接比较(Unit 6–7 讲)。想亲眼看"弹跳"?用文末的交互实验室把学习率调到 0.011。
必要扩展调学习率的经验:从 0.001 / 0.01 / 0.1 这类数量级开始试;loss 变成 NaN 或越来越大 → 太大;loss 下降极慢 → 太小。
易错点 · 理解提示"bounce"(弹跳)是描述学习率过大的标准用词,答题要写出来。
p.40ML hyperparameters(超参数)★短答题
Variables or settings of training or optimization algorithm that creates or learns a ML model · E.g. the learning rate and the number of iterations of gradient descent · Usually set manually before the algorithm executes · May also be adjusted automatically by the algorithm
核心概念hyperparameters 是创建 / 学习模型的训练或优化算法的变量或设置;例如学习率、梯度下降的迭代次数;通常在算法执行前由人手动设定,也可以由算法自动调整。
详细讲解到这里可以分清两种"数":parameters(m、b)是模型学出来的;hyperparameters(learning rate、iterations)是人设定、用来控制"怎么学"的。"hyper"(超)= 在参数之上。讲义说"通常手动设定",也说"可以由算法自动调整"——后者叫超参数搜索。这门课里你会接触的超参数还有:Keras 的 epochs、batch_size、每层神经元数、层数、dropout 比例等。
parameters(参数)hyperparameters(超参数)
本讲的例子m、blearning rate、number of iterations
谁决定算法在训练中学出来人在训练前设定
在哪里模型内部(p53 的 get_weights())训练 / 优化的设置里(p49 的 learning_rate、p53 的 epochs)
题目 / Tut / Lab 关联p49 代码里的 learning_rate = 0.005 和 iterations 元组 (1, 10, 100, 1000, 10000);p53 的 epochs=1000、learning_rate=.1;项目 Task 1 要求设计三个"候选模型"并比较——比较的就是不同结构 / 超参数。
必要扩展短题 "Give two examples of hyperparameters":learning rate、number of iterations(epochs)。
易错点 · 理解提示⚠️ 考试喜欢让你区分:m 和 b 是 parameters;learning rate 和 number of iterations 是 hyperparameters。
p.41The end(正文结束)分节
The end
核心概念正文到此结束,p42 起是附录代码。
详细讲解正文 40 页在这里结束。回想全讲:A 部分定义(p4–p9),B 部分术语(p11–p23),C 部分分类与 DL(p25–p30),D 部分训练流程(p32–p40)——正对应 p2 目录的五个部分(第五部分"训练线性回归"的代码在附录)。
题目 / Tut / Lab 关联Course Review p3 列的 Unit 1 五条考点全部在 p41 之前;附录代码(p43–p53)是"把正文跑一遍"。
必要扩展复习方法:合上讲义,按 p2 目录的五个部分各自复述;再打开文末自测题检验。
易错点 · 理解提示不要忽略附录——p49 的输出表、p52 的 R² 都可能考,而且 Lab 1 的技能只在附录里被用到。

E 部分|附录:训练模型的完整代码(p42–p53)

p.42分节页:Appendix – Training a ML model code分节
Appendix: Training a ML model code
核心概念附录:用代码把正文 p32–p40 的流程跑一遍。
详细讲解11 页代码分三段:p43–p45 准备(造数据、画图、归一化与切分);p46–p49 自己用 NumPy 写 MSE 与梯度下降(对应正文 p37–p40);p50–p53 画结果、做预测,再用 scikit-learn 和 TensorFlow/Keras 各做一遍作对照。读懂 p47–p49,你就用不到 20 行代码把"训练"这件事亲手做了一次。
题目 / Tut / Lab 关联Lab 1(t01 notebook)教的每个 Python / NumPy 技能都在这里用到:seed、随机数、reshape、arange、sum / len、f-string。文末"Lab 1 全解"逐题标出对应的讲义页码。
必要扩展这份代码可以直接在 Colab 运行(p43–p51 只需 numpy、matplotlib;p52 需 scikit-learn,p53 需 tensorflow)。
易错点 · 理解提示读代码的顺序:先看 p49 的输出(想得到什么),再回头读 p47(怎么得到的)。
p.43Creating data(生成数据)Lab 1 Q2c
np.random.seed(42) · hours = np.random.randint(2, 20, n) · scores = hours * 4.5 + 10 + np.random.normal(0, 5, hours.shape) · return hours, scores.round(1)
核心概念用固定随机种子生成 10 个 (hour, score) 数据点:hour 是 [2, 20) 的随机整数;score = hour × 4.5 + 10 + 正态噪声 N(0, 5),保留一位小数。
import numpy as np
def create_dataset(n=10):
    np.random.seed(42)                                     # 固定种子 → 可复现
    hours = np.random.randint(2, 20, n)                     # [2, 20) 的随机整数
    scores = hours * 4.5 + 10 + np.random.normal(0, 5, hours.shape)  # 真规则 + 噪声
    return hours, scores.round(1)
hours, scores = create_dataset()
# (array([ 8, 16, 12,  9,  8, 12, 12,  5,  9,  4]),
#  array([43.7, 84.7, 61.7, 48.2, 47.2, 54.4, 55.4, 29.7, 45.4, 29.6]))
详细讲解逐行:
① np.random.seed(42):固定随机数生成器的种子,之后每次运行得到的"随机"数完全相同——这是可复现(reproducible)的保障;Lab 1 Q2c 和 p53 的 set_random_seed(42) 都是同一目的。
② np.random.randint(2, 20, n):生成 n 个 [2, 20) 的随机整数——含 2、不含 20,和 Lab 1 里 range / 切片的"含头不含尾"是同一条规则。
③ hours * 4.5 + 10:隐藏的真规则(一条斜率 4.5、截距 10 的直线,p36 的 y = mx + b)。
④ np.random.normal(0, 5, hours.shape):加均值 0、标准差 5 的正态分布噪声,形状与 hours 相同——这就是 p33 表里"真值"与"观测值"差的那几分的来源。
⑤ .round(1):保留一位小数。输出与 p33 的表完全一致(我已复算)。
题目 / Tut / Lab 关联Lab 1 Q2c:np.random.seed(42) + np.random.randn(10000)——randn 是标准正态 N(0, 1),这里的 normal(0, 5) 是 N(0, 5),同一家族;Q2d 的直方图就是正态分布的样子。
必要扩展换一个 seed 就会得到另一组数据、另一条拟合线——所以报告 / 论文里要写明 seed。
易错点 · 理解提示randint(2, 20) 取不到 20;分数带小数是因为加了噪声再 round(1)。
p.44Creating data (cont.)(画散点图)Lab 1 Q2d
plt.plot(hours, scores, "o") · plt.xlabel("Weekly study hours") · plt.ylabel("Scores") · plt.axis([0, 20, 0, 100])
核心概念用 matplotlib 画散点图:plt.plot(hours, scores, "o");设 x / y 轴标签;axis([0, 20, 0, 100]) 设坐标范围。
import matplotlib.pyplot as plt
def plot_dataset(hours, scores):
    plt.plot(hours, scores, "o")          # "o" = 只画点,不连线
    plt.xlabel("Weekly study hours")
    plt.ylabel("Scores")
    plt.axis([0, 20, 0, 100])             # [xmin, xmax, ymin, ymax]
plot_dataset(hours, scores)
详细讲解逐行:plt.plot(hours, scores, "o")——第三个参数 "o" 表示只画圆点、不连线(默认是折线);plt.xlabel / plt.ylabel 设轴标签;plt.axis([0, 20, 0, 100]) 一次设定横轴 0–20、纵轴 0–100(顺序是 [xmin, xmax, ymin, ymax])。调用 plot_dataset(hours, scores) 得到 p34 的散点图。
题目 / Tut / Lab 关联Lab 1 Q2d 的 plt.hist(xs, bins=100);——末尾分号抑制输出;Lab 2(t02)正式学 matplotlib 的 plot / xlabel / legend;本页是最小用法。
必要扩展常用样式字符串:"o"(点)、"-"(线,默认)、"o-"(点 + 线)、"r"(红色)。
易错点 · 理解提示"o" 不能漏,否则 10 个点会被连成一条折线;axis 的四个数顺序容易写反。
p.45Normalization, training set and test set★试卷 Q6🧮
Normalization is to scale data values to smaller and similar ranges · Min-max normalization to range [0, 1]: x′ = (x − min x) / (max x − min x) · Needed for many ML algorithms, but we skip it here for simplicity · In a practical ML task, the data should be divided into a training set and test set (e.g. 70% vs 30%) · We don't split the tiny dataset here as it has only 10 examples
核心概念normalization 把数据缩放到较小且相近的范围,例如 min-max 归一化到 [0, 1]:x′ = (x − min x)/(max x − min x);很多算法需要,但这里为简单起见跳过。实际任务要把数据分成 training set 和 test set(如 70% vs 30%);这个数据集只有 10 个 examples,所以不切分:x_train = x_test = hours、y_train = y_test = scores。
详细讲解三个要点。
① 公式手算:hours 的 min = 4、max = 16,分母 = 12。x′(4) = 0;x′(16) = 1;x′(8) = (8 − 4)/12 = 0.333。归一化后所有特征都落在 0–1,不同量纲的特征"平等"。
② 为什么很多算法需要?对梯度下降而言,特征尺度不均匀会让 loss 碗变成一条"狭长的斜沟":有的方向陡、有的方向缓,学习率只能按最陡的方向选小值,缓的方向就走得很慢。本讲恰恰因为这个原因收敛很慢——我复算:不归一化时 lr = 0.005 跑 1000 轮 MSE 才到 15.54;把 x 归一化后用 lr = 0.1,只跑 400 轮就到 14.635(约快 25 倍),而且换算回原尺度仍是 m = 4.2893、b = 9.2519。讲义说 "skip it here for simplicity",代价就是 p49 要跑 10000 轮。
③ 切分:70% / 30% 对 10 个样本来说是 7 个和 3 个,太少;所以这里四个名字指向同一个数组(Python 的"别名",不是复制)。后果是 p49 表里的 error 是在训练数据上算的,严格说叫"训练误差"而不是"测试误差"。
x′ = (x − min x) / (max x − min x) → 归一化后 x′ ∈ [0, 1]
题目 / Tut / Lab 关联试卷 Q6(把图像特征缩放到 0–1、reshape、one-hot)正是"归一化"的实战版;Lab 1 的 min / max / mean(arr.max()、np.mean)是算 min-max 的工具;Unit 6–7 讲数据集切分与验证集。
必要扩展其他归一化:标准化(减均值除标准差,z-score);Keras 的 Rescaling(1./255) 把像素从 0–255 缩放到 0–1。
易错点 · 理解提示⚠️ 归一化用的 min / max 应来自 training set,再应用到 test set(否则测试信息泄露到训练里)。考试答题照常写"要切分",不要引用本页"不切分"的简化做法。
p.46Mean squared error(MSE 代码)🧮手算Lab 1
def mean_squared_error(y, y2): return np.sum((y - y2) ** 2) / len(y) · mean_squared_error(np.array([0, 2, 5]), np.array([1, 1, 1])) → 6.0
核心概念把 p37 的公式写成函数:np.sum((y - y2) ** 2) / len(y);示例 mean_squared_error([0, 2, 5], [1, 1, 1]) = 6.0。
def mean_squared_error(y, y2):          # y = 实际值, y2 = 预测值
    return np.sum((y - y2) ** 2) / len(y)   # 相减 → 平方 → 求和 → 除以个数

mean_squared_error(np.array([0, 2, 5]), np.array([1, 1, 1]))   # → np.float64(6.0)
详细讲解代码只有一行:相减、平方、求和、除以个数。手算示例:三个样本的误差是 0 − 1 = −1、2 − 1 = 1、5 − 1 = 4;平方得 1、1、16;求和 18;除以 3 = 6.0 ✔。这个示例顺便告诉你 MSE 的量级:偏差 1 的两个样本合计贡献 2,偏差 4 的一个样本贡献 16——大误差主导,这就是 p37 说的"惩罚大误差"。
题目 / Tut / Lab 关联p49 的 error 列调用它;Lab 1 的 np.array 与数组运算(**、减法按元素进行)正是这里的基础;Keras 的 loss="mse" 内部就是它。
必要扩展若 y 是二维数组,len(y) 返回行数;更稳妥的写法是 y.size(Lab 1 Q2c 用过)。
易错点 · 理解提示参数顺序 (y, y2) = (实际, 预测);由于平方,顺序不影响结果。
p.47Computing gradients and learning rate(梯度代码)★核心🧮手算
MSE = (1/n) Σ (yᵢ − (m xᵢ + b))² · Gradients of m and b can be calculated using calculus · Learning rate is the amount of update to the parameters · gradient_descent_step
核心概念把 ŷ = mx + b 代入 MSE,用微积分求 ∂MSE/∂m 与 ∂MSE/∂b;学习率是每次更新的量;一次 gradient_descent_step = 更新一轮 m、b。
def gradient_descent_step(m, b, x, y, learning_rate):
    predicted = m * x + b                                  # ŷ
    m_gradient = 2 * np.dot(x, predicted - y) / len(x)      # ∂MSE/∂m
    b_gradient = 2 * (predicted - y).sum() / len(x)         # ∂MSE/∂b
    new_m = m - learning_rate * m_gradient                 # 新 = 旧 − lr × 梯度(p38)
    new_b = b - learning_rate * b_gradient
    return new_m, new_b
详细讲解先推两个梯度(Unit 3 会正式推):MSE = (1/n) Σ (yᵢ − (m xᵢ + b))²。对 m 求导,每个样本贡献 2(yᵢ − ŷᵢ)·(−xᵢ),整理得 ∂MSE/∂m = (2/n) Σ xᵢ (ŷᵢ − yᵢ);对 b 求导,每个样本贡献 2(yᵢ − ŷᵢ)·(−1),整理得 ∂MSE/∂b = (2/n) Σ (ŷᵢ − yᵢ)。代码正是这两式:np.dot 算 Σ xᵢ·(ŷᵢ − yᵢ),sum 算 Σ (ŷᵢ − yᵢ)。
再手算第 0 轮(m = b = 0):ŷ = 0,所以 ŷ − y = −y;已知 Σxy = 5249.7、Σy = 500、n = 10:
dm = −2 × 5249.7 / 10 = −1049.94  db = −2 × 500 / 10 = −100
m = 0 − 0.005 × (−1049.94) = 5.2497  b = 0 − 0.005 × (−100) = 0.5 → 正好是 p49 表的第一行 ✔
详细讲解(续)注意一个现象:m 一步就冲到 5.25(超过了最优值 4.29),而 b 才到 0.5(最优 9.25)——因为 dm 带着 x 的量纲(Σxy 很大),db 不带。两个参数"尺度"不同,这就是 p45 归一化要解决的问题。
题目 / Tut / Lab 关联Unit 3 的 MSE 梯度推导得到同样的 −1049.94 / −100;Lab 1 的 np.dot / sum / len 虽未直接练,但 arr.max(axis=0) 这类"沿轴聚合"是同一类运算;试卷不要求手算梯度(Course Review 把微分标为 optional),但要懂 update rule。
必要扩展predicted − y 的顺序为什么重要?若写成 y − predicted 却不变号,更新方向会反过来,loss 越来越大。
易错点 · 理解提示⚠️ 两个梯度都带系数 2(来自平方的导数);有人把 2 并进学习率里,数值会差一倍。
p.48Gradient descent iterations and errors(循环)
def gradient_descent(x, y, learning_rate, iterations, initial_m=0, initial_b=0) · def predict_error(m, b, x, y)
核心概念gradient_descent:从初始 m、b 出发,循环 iterations 次调用 step;predict_error:用最终的 m、b 返回预测值和 MSE。
def gradient_descent(x, y, learning_rate, iterations, initial_m=0, initial_b=0):
    m = initial_m
    b = initial_b
    for i in range(iterations):                        # 迭代 iterations 次
        m, b = gradient_descent_step(m, b, x, y, learning_rate)
    return m, b

def predict_error(m, b, x, y):
    predicted = m * x + b
    error = mean_squared_error(y, predicted)        # 调用 p46 的函数
    return predicted, error
详细讲解两段代码都只有几行。gradient_descent 每次调用都从 initial_m、initial_b(默认 0)重新开始,循环 iterations 次;predict_error 用最终的 m、b 算预测值 predicted 和误差 error。这里所有 10 个样本一起算一次梯度、更新一次,叫一轮(iteration)。
题目 / Tut / Lab 关联iterations 是 p40 的 hyperparameter;Keras 的 epoch 概念类似(一个 epoch = 遍历一次训练数据),但 Keras 默认把数据切成 mini-batch,一个 epoch 内会更新多次;p53 的 epochs=1000。
必要扩展初始值设为 0 对线性回归没问题(loss 是凸碗,从哪出发都能到底);深度网络不能把所有权重都设成 0(Unit 6–7 的 random initialization)。
易错点 · 理解提示⚠️ p49 表中每一行都是一次独立的、从 0 开始的完整训练,不是接着上一行继续跑。
p.49Putting it all together(训练结果表)★必看🧮
learning_rate = 0.005 · for iterations in (1, 10, 100, 1000, 10000): … · print(f"{iterations:6}: {m=:.4f}, {b=:.4f}, {error=:.4f}")
核心概念learning_rate = 0.005;对 iterations ∈ (1, 10, 100, 1000, 10000) 分别独立训练并打印 m、b、error。
learning_rate = 0.005
for iterations in (1, 10, 100, 1000, 10000):
    m, b = gradient_descent(x_train, y_train, learning_rate, iterations)
    predicted, error = predict_error(m, b, x_test, y_test)
    print(f"{iterations:6}: {m=:.4f}, {b=:.4f}, {error=:.4f}")   # f-string:宽度 6、保留 4 位小数
详细讲解读表(五行全部复算一致;第 0 行是我加的起点,方便比较):
iterationsmberror(MSE)解读
(0,起点)002728.97直线 y = 0,误差最大
15.24970.500025.5179m 一步过冲(p47 手算)
105.09900.575723.2394m 开始回落,b 几乎没动
1005.02051.417621.6503b 爬得极慢
10004.55286.428715.5444接近了
100004.28939.251814.6332与精确解 (4.28927, 9.25193) 几乎相同
详细讲解(续)三条规律:① m 第一步就冲到 5.25(过冲),然后慢慢回落到 4.29;② b 爬得极慢——100 轮才到 1.42,1000 轮才到 6.43,10000 轮才接近 9.25;③ error 从 2728.97 一步降到 25.52,然后缓慢逼近最小值 14.63。为什么不快?两个原因:学习率 0.005 已接近稳定上限 0.0097(p39),不能再大;特征没归一化,b 方向的坡太缓(p45)。
题目 / Tut / Lab 关联p38–p40 概念的落地;p52 sklearn 一步得到同一答案;文末交互实验室可以重跑这张表(点"复现 p49 表")。f-string 里的 {m=:.4f} 写法就是 Lab 1 cell 8 教的 f"{exp=}" 加格式控制。试卷 Q7c 的回归训练同样是"选 loss(MSE)+ 迭代优化"。
必要扩展这里的 error 是在全部 10 个样本上算的(p45 没切分),是训练误差;真正评估要看测试集(p32)。
易错点 · 理解提示⚠️ 迭代次数越多越好吗?对线性回归(凸碗)是的;对深度网络不是——训练太久会过拟合(试卷 Q8),所以要 validation set 和 early stopping。
p.50Putting it all together (cont.)(画拟合直线)原图Lab 1
plot_dataset(hours, scores) · xs = np.arange(1, 20) · plt.plot(xs, m * xs + b, linewidth=2)
核心概念把训练 10000 轮得到的直线画在散点图上:xs = np.arange(1, 20) 作画线用的 x 网格,plt.plot(xs, m * xs + b, linewidth=2) 画拟合线。
plot_dataset(hours, scores)                 # 先画散点(p44)
xs = np.arange(1, 20)                     # 1, 2, …, 19(不含 20)
plt.plot(xs, m * xs + b, linewidth=2);   # 画拟合直线
详细讲解逐行:先调用 plot_dataset 画散点(p44);np.arange(1, 20) 生成 1, 2, …, 19 作为画线用的 x 网格——注意不是原始的 hours,画一条平滑的线需要连续的 x;plt.plot(xs, m * xs + b) 画拟合线。看图:直线穿过点群的中心,从 (1, 13.5) 到 (19, 90.7);离线最远的点是 x = 16 的那个(实际 84.7,预测 77.88,残差 +6.82)和 x = 12 的两个(实际 54.4 / 55.4,预测 60.72,残差约 −6)——这些残差就是 p33 表里的噪声。
0.02.55.07.510.0 12.515.017.5 020406080100 Weekly study hours Scores score = 4.29 × hour + 9.25
讲义 p50 原图(按真实数据重绘):橙色直线 = 训练 10000 轮后的模型;点离线的竖直距离就是残差。
题目 / Tut / Lab 关联Lab 1 的 np.arange(0, 5, 0.5)(含头不含尾 → arange(1, 20) 不含 20);"点 + 线"同时画的做法在 Lab 2(t02)里会再学。
必要扩展如果直接 plt.plot(hours, m*hours + b),线只会连 10 个小时数处的点——对直线没影响,但对非线性模型就必须用密集的 xs。
易错点 · 理解提示np.arange(1, 20) 的最后一个数是 19,所以线画到 x = 19。
p.51Try a prediction(预测 15 小时)🧮★试卷 Q1b
# Predict the score for studying 15 hours per week · (15, m * 15 + b) → (15, np.float64(73.59102882562235))
核心概念预测 = 把 x = 15 代入训练好的方程:(15, 73.591…)——学 15 小时的预测分数约 73.59。
ŷ = m × 15 + b = 4.2893 × 15 + 9.2518 = 64.34 + 9.25 = 73.59  (真规则:4.5 × 15 + 10 = 77.5)
详细讲解预测就是把 x = 15 代入训练好的方程(p35 人类思路的第 ③ 步)。对照"真规则"4.5 × 15 + 10 = 77.5,相差约 3.9 分——因为模型是从 10 个带噪声的样本里学到的 (4.29, 9.25),而不是真实的 (4.5, 10);数据越多,学到的参数越接近真值。还要注意:15 不在训练集的小时数 {4, 5, 8, 9, 12, 16} 里——这是对"没见过的输入"做预测,p34 的问题在这里得到回答。
题目 / Tut / Lab 关联试卷 Q1b(回归任务 → 输出层 1 个神经元、线性激活)输出的就是这样一个数值;sklearn 的 reg.predict([[15]]) → 73.591(p52);Keras 的 model.predict → 72.79(p53)。
必要扩展预测的不确定性(置信区间)属于统计学内容,本课程不要求;但报告里最好说明预测值与真实值有偏差。
易错点 · 理解提示回归输出是连续值(73.59 分),带小数很正常,不要四舍五入成类别。
p.52Using scikit-learn's LinearRegressionLab 1 reshape
hours_2d = hours.reshape(-1, 1) # sklearn uses 2D input features · reg.fit(hours_2d, scores) · reg.coef_, reg.intercept_ · reg.score(...) · reg.predict([[15]])
核心概念用 scikit-learn 的 LinearRegression 做同一件事:fit → coef_(m)= 4.28927039、intercept_(b)= 9.25193133;score(R²)= 0.93609081;predict([[15]]) = 73.59098712。
from sklearn.linear_model import LinearRegression
hours, scores = create_dataset()
hours_2d = hours.reshape(-1, 1)            # (10,) → (10, 1):sklearn 要二维特征
reg = LinearRegression()
reg.fit(hours_2d, scores)                  # fit = 训练(p32)
print(reg.coef_, reg.intercept_)         # m 和 b → [4.28927039] 9.251931330472111
print(reg.score(hours_2d, scores))       # R² score → 0.9360908126974805
print(reg.predict([[15]]))               # 预测分数 → [73.59098712]
详细讲解逐行:
① hours_2d = hours.reshape(-1, 1):把 shape (10,) 的一维数组变成 (10, 1) 的二维——sklearn 要求特征是二维的 "(样本数, 特征数)"(p18 的 (n, d));-1 让 NumPy 自动算这一维(Lab 1 的 reshape((3, -1)))。
② reg.fit(hours_2d, scores):fit = 训练(p32 的 train / fit)。sklearn 内部直接用最小二乘法的解析解,一步算出最优 m、b,不需要迭代——所以没有学习率、迭代次数这些超参数。
③ reg.coef_ → [4.28927039](m);reg.intercept_ → 9.25193133(b):与 p49 跑 10000 轮的 (4.2893, 9.2518) 一致。
④ reg.score(...) → R² = 0.936:R²(coefficient of determination)衡量"模型解释了 label 多少比例的变化",R² = 1 − SS_res / SS_tot = 1 − 146.33 / 2289.68 = 0.936;越接近 1 越好——学习小时数解释了分数变化的 93.6%。
⑤ reg.predict([[15]]):输入也必须是二维的(一个样本、一个特征)。
题目 / Tut / Lab 关联Lab 1 的 reshape((6, 1) 与 (6,) 的区别,cells 45–46);试卷 Q7a 的 (20000, 8);Unit 4 的 Keras 也用 fit / predict 这套 API。
必要扩展手算闭式解:m = Σ(x − x̄)(y − ȳ) / Σ(x − x̄)²,b = ȳ − m·x̄,其中 x̄ = 9.5、ȳ = 50(我已用此式验证与 sklearn 输出逐位相同)。
易错点 · 理解提示⚠️ reg.score 不是分类里的"准确率"——回归里的 score 是 R²;predict 的输入要写成 [[15]]。
p.53Using TensorFlow/Keras★试卷 Q7c 模板
keras.layers.Dense(1, activation="linear") · keras.optimizers.RMSprop(learning_rate=.1) · model.compile(loss="mse", optimizer=opt, metrics=["mae"]) · model.fit(..., epochs=1000) · model.get_weights() → [[4.23927]], [9.201929] · model.predict([[15]]) → 72.790985
核心概念用 Keras 做线性回归:Sequential([Dense(1, activation="linear")]);RMSprop(learning_rate=.1);compile(loss="mse", optimizer=opt, metrics=["mae"]);fit(epochs=1000);权重 4.23927、偏置 9.201929;predict → 72.79。
from tensorflow import keras
hours, scores = create_dataset()
hours_2d = hours.reshape(-1, 1)
keras.utils.set_random_seed(42)                              # 固定随机种子(同 p43)
model = keras.models.Sequential([                            # very simple NN to simulate linear regression
    keras.layers.Dense(1, activation="linear")           # 1 个神经元、线性激活 → y = w·x + b
])
opt = keras.optimizers.RMSprop(learning_rate=.1)             # 自适应学习率的优化器
model.compile(loss="mse", optimizer=opt, metrics=["mae"]) # loss = MSE(p37)
history = model.fit(hours_2d, scores, epochs=1000, verbose=0)
print(model.get_weights())   # → [array([[4.23927]]), array([9.201929])]
print(model.predict(np.array([[15]]), verbose=0))   # → [[72.790985]]
详细讲解逐行:
① Dense(1, activation="linear"):一个全连接层,1 个神经元、线性激活——计算 y = w·x + b,就是线性回归(p36);只有 2 个参数:kernel(= m)和 bias(= b)。注释 "very simple NN to simulate linear regression" 的意思就是:一个神经元、没有隐藏层。
② RMSprop(learning_rate=.1):优化器用 RMSprop(自适应学习率的梯度下降变体,Unit 6–7 讲)。这里的 0.1 不会像普通梯度下降那样发散(p39 的上限 0.0097 是对普通 GD 而言的)。
③ compile(loss="mse", optimizer=opt, metrics=["mae"]):loss = MSE(p37);metrics 是训练时顺带显示的指标——mae 是平均绝对误差,不是准确率。
④ fit(hours_2d, scores, epochs=1000, verbose=0):训练 1000 个 epoch;verbose=0 不打印进度。
⑤ get_weights() → [array([[4.23927]]), array([9.201929])]:前者是权重矩阵(m),后者是偏置(b)。与精确解 (4.289, 9.252) 略有差别——因为 1000 个 epoch 还没有完全收敛;预测 72.79 vs 73.59。
⑥ predict(np.array([[15]])):输入同样是二维。
题目 / Tut / Lab 关联这段代码就是试卷 Q7c 答案的模板:回归 = Dense(1, activation="linear") + loss="mean_squared_error" + metrics 用 mse / mae。Unit 4 的 Keras 流程(建模 → compile → fit → evaluate → predict)在这里第一次出现;Lab 1 的 reshape 在这里再次出现。
必要扩展为什么要用 Keras 做这么简单的事?因为同样的代码模板可以直接扩展:加 Dense 层、换 activation 和 loss,就变成 Unit 4–5 的深度分类网络。
易错点 · 理解提示⚠️ metrics=["mae"] 不是准确率;get_weights() 的顺序是 [kernel, bias];Dense(1, linear) 对应 p23 的 regression,也是试卷 Q1b 三格答案(Regression / 1 / Linear)。

🕹 梯度下降交互实验室(对应 p38–p39、p47–p50)

用讲义的 10 个数据点,亲手跑一遍 p47 的 gradient_descent_step。选学习率 → 点按钮推进迭代 → 实时画出当前的直线(左)和 loss 曲线(右)。试一试:lr = 0.005 跑 10000 次得到 4.2893 / 9.2518(p49 最后一行);lr = 0.011 看它"弹飞"(p39 第三张图);lr = 0.001 感受"太慢"。

学习率
0.02.55.07.510.0 12.515.017.5 020406080100 Weekly study hours Scores 精确解 4.2893x + 9.2519(灰虚线)
红色实线 = 当前的模型 y = m·x + b(从 y = 0 开始)
110100100010000 1510010002700 Iterations(对数刻度) MSE(对数刻度)
MSE 随迭代变化;飞出顶部 = 发散(学习率太大)
[就绪] m = 0, b = 0, iteration = 0, MSE = 2728.97。点"步进"或"×100"开始训练。
iterationsmberror(MSE)讲义 p49 原值

说明:"复现 p49 表"会用 lr = 0.005 独立跑五次训练(1 / 10 / 100 / 1000 / 10000 轮),与讲义逐位对比。

🧪 Lab 1 全解(Tutorial 1 = t01-s13903054.ipynb)

Lab 和 Tut 在这门课里是同一份东西:notebook 的标题写着 "COMP S493F Lab 1",而进度表(intro.pdf p9)里它出现在 Tutorial 1 的时段——每周的 notebook 既是 tutorial 练习,也是要交的 Lab exercise(占总分 15%,下一次讲课日 18:00 截止)。Lab 1 的内容是 Python collections / comprehension 和 NumPy basics——不是机器学习概念本身,而是附录 p43–p53 代码的"工具箱"。你的作答(Yin Bang, 13903054)已全部填写,下面逐题核对:Q1a–Q1c、Q2a–Q2d 全对。
题目要求你的答案核对对应讲义页
Q1a嵌套列表 ls = [[1,2,3,4],[5,6],[7,8,9,10]]:用两个正下标、再用两个负下标打印 8print(ls[2][1])
print(ls[-1][-3])
✔ 8 / 8(ls[2] = [7,8,9,10],下标 1 → 8;ls[-1] 是最后一个子列表,−3 → 8)两次索引 ↔ p17–p18:X[i] 取第 i 个 example(行),再取其中第 j 个 feature
Q1bls = list(range(12)):用切片打印 [6..11]、[6,8,10]、[11,8,5,2]ls[6:12]
ls[6::2]
ls[11::-3]
✔ 三行输出全部一致切片"含头不含尾" ↔ randint(2, 20)(p43)、np.arange(1, 20)(p50);取子集 ↔ train / test 切分(p32、p45,如 X[:7] / X[7:])
Q1c用 is_prime 和列表推导式打印 2–1000 的素数[n for n in range(2,1001) if is_prime(n)]✔ [2, 3, 5, 7, … 997],共 168 个列表推导式在后续 Lab 里会大量用于造数据、处理标签
Q2anp.arange(10,30).reshape(4,5),存入 arr 并显示照做✔ 4×5 数组 10…29这就是一个 4×5 的 feature matrix(p18:4 个 examples × 5 个 features);reshape ↔ p52、p53 的 reshape(-1, 1)
Q2b显示 15、27、最后一行、第二列、中间六个数arr[1,0] arr[3,2] arr[3] arr[:,1] arr[1:3,1:4]✔ 五项全部一致arr[3] = 一个 example(行);arr[:,1] = 一个 feature(列)——正是 p17 图里 "An example" 与 "A feature" 的代码写法;arr[1:3,1:4] = 同时选行和列
Q2cnp.random.seed(42);xs = np.random.randn(10000);显示 mean、std、个数xs.mean() xs.std() xs.size✔ −0.00214 / 1.0034 / 10000seed(42) ↔ p43、p53;标准正态 N(0,1) ↔ p43 的噪声 normal(0, 5)(mean≈0、std=1 的直观检查);.size ↔ p46 的 len(y)
Q2dplt.hist(xs, bins=100);照做✔ 钟形直方图matplotlib 入门 ↔ p44 的 plt.plot(hours, scores, "o");钟形就是 p33 "噪声"的分布形状
E1a
附加
打印 {} () (42) (42,) 的值与类型notebook 末尾附参考答案{} → dict;() → tuple;(42) → int;(42,) → tuple括号里有逗号才是元组——写形状 (3, 5)、(10, 1) 时(p18、p52)都是元组
E1b
附加
3×3 随机数组,用 np.mean(arr, axis=n) 求整体 / 每列 / 每行均值notebook 末尾附参考答案4.0;[3.667, 4.0, 4.333];[4.333, 3.333, 4.333]axis=0 沿行向下(跨所有 examples)↔ 对一列 feature 求统计量,如 p45 归一化的 min / max、p52 的 x̄、ȳ;axis=1 沿列向右(跨一个 example 的所有 features)

📝 试卷相关题(COMP 4930SEF Test – 2026,10/22 随堂测验)

试卷 8 题里,Q1 整题、Q6 整题、Q7 的 a / b / c、Q8 全题都直接用到 Unit 1 的概念(其余小问需要 Unit 2–5 的知识)。下表把"考了本讲哪一页"标出来。

Q1(12 分)判断任务类型 + 输出层(p23 + Unit 4–5)

任务Type of task(p23)输出层神经元数输出层激活函数
a) 用出勤率和作业分预测等级 A / B / C / D / FMulticlass classification(5 个类别 → ≥ 3 类)5(每类一个)Softmax
b) 根据天气和时段预测每小时租车数量Regression(数值 label)1Linear / NA / Wx + b
c) 预测信用卡交易是欺诈还是合法Binary classification(2 类)1(若写 2,则激活函数须改为 softmax)Sigmoid

怎么想:第一列 100% 来自 p23 的判断流程(看 label 的类型和类别数);第二、三列来自 p53 的回归模板(1 个神经元 + linear)和 Unit 4–5 的分类模板。

Q6(4 分)数据预处理填空(p45 + p18 / p52 + p21)

28×28 灰度图:特征缩放到 0–1(= p45 的 normalization)→ 每个样本 reshape 成 1D(1×784)(= p18 / p52 的 reshape,全连接层要一维输入)→ 标签转成 one-hot encoding(= p21 的 categorical label 转成向量)。

Q7(20 分)餐厅满意度评分模型(p20、p23、p36、p53)

小问答案用到本讲哪页
a. 输入数据的维度(20000, 8)p18:feature matrix 形状 = (examples, features)
b. 两处 bug(1–5 是类别,模型却按二分类写)Line 13:sigmoid → softmax;Line 17:binary_crossentropy → categorical_crossentropyp20:整数 1–5 看似数值,但表示 5 个类别 → multiclass(p23)
c. 把 label 改成 4.45 这样的小数后做"正确的线性预测"(改 4 处 / 2 行)Line 13:5 → 1,sigmoid → linear(或去掉);Line 17:binary_crossentropy → mean_squared_error(或 mean_absolute_error);metrics=["acc"] → 删除或改为 mse / maep22:label 变 numerical → regression(p23);p36 线性模型;p53 的回归代码模板;p40 知道 epochs / lr 是超参数

Q8(12 分)过拟合与欠拟合(p5、p16、p32)

Model C(训练 57% / 验证 51%)underfitting;Model A(96% / 60%)overfitting;Model B(89% / 85%)well-fitted。处理过拟合:更简单的模型、early stopping、更多训练数据(数据增强)、权重正则化、dropout、batch normalization;要让无用特征的权重恰好为 0 用 L1。
与 Unit 1 的关系:p5 "seen data → unseen data" 的泛化差距、p16 "更多 examples 提升性能"、p32 "必须在没见过的数据上评估"——这三页是理解 Q8 的概念基础;具体技术(正则化、dropout)在 Unit 6–7。

📘 Unit 1 总结

1. 一张概念地图

Machine learning(p4–p9) Supervised(p25) Classification(binary / multiclass) Regression Unsupervised(p26) Clustering · Association analysis Reinforcement(p27) Agent · Environment Action · State · Reward Deep learning(p29–p30)⊂ ML 多层 ANN:raw features → 高层特征 监督学习的训练流程(以线性回归为例,p12、p32、p36–p40) 数据(p12–p19) X:features · y:labels training / test set 模型(p36) y = mx + b 参数 m、b 待学 损失(p37) MSE = (1/n)Σ(yᵢ−ŷᵢ)² 越小越好 优化器(p38–39) gradient descent 新 = 旧 − lr × 梯度 超参数(p40) learning rate iterations 循环:模型预测 ŷ → 与 y 比较 → 算 MSE → 求梯度 → 更新 m、b(p47)→ 再预测 …(p48–p49) 循环结束后 → 预测(p51)· sklearn 一步到位(p52)· Keras 模板(p53)
上:三类 ML(DL 是 ML 的子集,三类任务都能用);下:监督学习训练流程的五要素——数据、模型、损失、优化器、超参数。

2. 对照 Course Review p3:Unit 1 的五条考点

Course Review 原文页码一句话答案
Machine learning concepts – Training (features) and prediction (labels)p12–p19Training 吃 labelled examples(features + labels)产出 model;Prediction 吃 unlabelled examples(features only)产出 labels。X 是 feature matrix(n × d),y 是 label vector,ŷ 是预测值。
Two types of data:Categorical (discrete) · Numerical (continuous)p20–p22categorical = 有限个取值 = discrete;numerical = 数值 = continuous。label 的类型决定任务。
Two types of supervised ML:Classification (binary and multiclass) · Regressionp23、p25classification 预测 categorical label(2 类 binary,≥ 3 类 multiclass);regression 预测 numerical label。
Three types of MLp24–p27supervised(有 label)/ unsupervised(无 label,找模式)/ reinforcement(agent 与 environment 交互,靠 reward)。
Gradient descentp38–p40、p47–p49用当前参数处的梯度迭代更新参数以降低 loss:new = old − lr × gradient;负梯度 → 增大参数。learning rate 与 iterations 是 hyperparameters。

3. 必背英文定义(短问题用)

#术语一句话英文定义(页码)
1AI / ML / DLAI: intelligence demonstrated by computer systems. ML: intelligence learned from example data and building a model. DL: a type of ML techniques that use artificial neural networks.(p4)
2Featuresdata input into a model for making predictions(= attributes, properties, independent variables, dimensions, covariates)(p13)
3Labelsresults predicted by a model(= dependent variables, target variables, responses)(p14)
4Examples / training set / test setExamples: input data to an ML algorithm. Training set: a set of labelled examples. Test set: a set of unlabelled examples (features only).(p15)
5Categorical / NumericalCategorical: a data field that can take on a finite number of possible values (discrete). Numerical: a data field that has a numerical value (continuous).(p21–p22)
6Classification / RegressionClassification: predicting a categorical label (binary: 1 of 2 classes; multiclass: 1 of ≥ 3 classes). Regression: predicting a numerical label.(p23)
7Supervised / Unsupervised / ReinforcementSupervised: make predictions using a model that associates features with labels. Unsupervised: identify patterns from (unlabelled) data. Reinforcement: an agent improves performance by interacting with the environment (actions, states, rewards).(p25–p27)
8Linear regressiona ML model that works when features are linearly related to the label: y = mx + b; training means determining the best values for m and b.(p36)
9MSEMean squared error = (1/n) Σ (yᵢ − yᵢ′)², yᵢ actual, yᵢ′ predicted, n number of predictions.(p37)
10Gradient descent / Learning rateGradient descent: an optimizer that determines optimal parameter values in iterations. Learning rate: the amount of change to increase or decrease a parameter value.(p38–p39)
11Hyperparametersvariables or settings of the training or optimization algorithm, e.g. learning rate, number of iterations; usually set manually before training.(p40)
12Why DL in the 2010shigh processing power and cheap GPUs; fast, large, cheap storage; massive available data; new and improved algorithms and practices.(p8)

4. 易错点 Top 10

  1. DL ≠ 监督学习:DL 是 ML 的子集(p4),三类任务都能用(p30);classification / regression 只是监督学习的子类(p24)。
  2. "看起来是数字" ≠ 数值型:1–5 的评分、邮编是 categorical(p20,试卷 Q7b 的陷阱)。
  3. 任务类型看 label,不看 feature(p23);binary = 2 类,multiclass = ≥ 3 类。
  4. Feature matrix 的形状是 (样本数, 特征数):试卷 Q7a 是 (20000, 8),不是 (8, 20000)(p18)。
  5. 训练集是 labelled,测试集按讲义是 unlabelled(p15);先切分再训练(p32)。
  6. reward 不是 label(p27);clustering 不是 classification(p26)。
  7. 负梯度 → 增大参数(p38);梯度公式里带系数 2(p47)。
  8. m、b 是 parameters;learning rate、iterations 是 hyperparameters(p40)。
  9. p49 表里每一行都是独立训练;其中的 error 是训练误差(p45 没切分)。
  10. reg.score 在回归里是 R²,metrics=["mae"] 是平均绝对误差——都不是"准确率"(p52–p53)。

5. 自测题(先自己答,再点开核对)

1. 用一句话分别定义 AI、ML、DL,并说出三者的包含关系。 AI: intelligence demonstrated by computer systems. ML: intelligence learned from example data and building a model. DL: a type of ML techniques that use artificial neural networks. 包含关系:AI ⊃ ML ⊃ DL(p4)。
2. "machine learning" 一词是谁、哪一年、在哪家公司提出的?他做了什么程序? Arthur Samuel,1959,IBM;一个通过自学变强的跳棋(checkers)程序,击败了他本人和冠军(p6)。
3. 写出 feature 的三个同义词、label 的两个同义词、example 的两个同义词。 feature = attributes / properties / independent variables / dimensions / covariates;label = dependent variables / target variables / responses;example = observations / instances / cases / data tuples / data objects / data points(p13–p15)。
4. 按讲义定义,什么是 training set、什么是 test set? Training set: a set of labelled examples (features + label). Test set: a set of unlabelled examples (features only), used for model assessment and prediction(p15)。
5. 判断任务类型:(a) 预测明天气温 (b) 预测学生是否及格(及格 / 不及格) (c) 把新闻分到 10 个主题之一 (d) 预测房价 (e) 预测等级 A–D。 (a) regression (b) binary classification (c) multiclass classification (d) regression (e) multiclass classification(p23)。
6. 数据集有 250 个样本、6 个特征。X 的形状?y 的形状? X: (250, 6);y: (250,)(p18–p19;试卷 Q7a 同理)。
7. y = [2, 4, 6],ŷ = [3, 3, 5],求 MSE。 误差 −1、1、1 → 平方 1、1、1 → 和 3 → ÷ 3 = 1.0(p37)。
8. 某时刻 ∂MSE/∂m = −20,学习率 0.01,m = 3。一步之后 m = ?m 变大还是变小? m = 3 − 0.01 × (−20) = 3.2;负梯度 → 参数增大(p38)。
9. 举出本讲的两个 hyperparameters。 learning rate、number of iterations(p40)。
10. p47 中 m = b = 0 时,第一步的 dm、db 各是多少?更新后 m、b = ?(lr = 0.005,Σxy = 5249.7,Σy = 500,n = 10) dm = −2 × 5249.7 / 10 = −1049.94;db = −2 × 500 / 10 = −100;m = 0.005 × 1049.94 = 5.2497,b = 0.005 × 100 = 0.5(p47、p49 第一行)。
11. 三类机器学习各举一个例子。 Supervised:垃圾邮件检测 / 收入预测;Unsupervised:客户分组(k-means);Reinforcement:国际象棋引擎(p25–p27)。
12. 为什么 ML/DL 在 2010 年代才成功?给出四个原因。 便宜且高性能的 GPU;快速、大容量、便宜的存储;海量数据(Web);新的和改进的算法与实践(p8)。
13.(Lab)用列表推导式写出 10 以内奇数的平方。 [n * n for n in range(10) if n % 2 == 1] → [1, 9, 25, 49, 81](Lab 1 cell 27)。
14.(Lab)np.arange(10, 30).reshape(4, 5) 得到的数组,arr[:, 1] 和 arr[2] 分别是什么?用讲义术语说。 arr[:, 1] = [11, 16, 21, 26] = 一个 feature(一列);arr[2] = [20, 21, 22, 23, 24] = 一个 example(一行)(Lab 1 Q2b;p17–p18)。

6. 与前后讲的联系

来自本讲用到去往
(起点)p13–p23 features / labels / examples / 术语这七个词在 Unit 2–5 的每一页都会出现,是全部后续讲义的"字母表"
—p25 监督学习的两个子类(classification / regression)Unit 4 回归网络、Unit 5 分类网络——各占一讲
—p36 线性模型 ŷ = mx + b、p37 MSE、p38–p39 梯度下降与学习率Unit 2 把直线弯成 sigmoid;Unit 3 用微积分推导 p47 的梯度公式;Unit 4 把它推广到多层
—p40 超参数(learning rate / iterations)Unit 4 网络结构(层数、神经元数)与 Unit 6 正则化系数也都是超参数
—p43–p53 纯 NumPy 手写训练循环Unit 4 p37 用 Keras 的 compile / fit 把这 11 页压缩成 3 行
本文件覆盖范围:u01.pdf 全部 53 页(逐页六栏目)+ t01-s13903054.ipynb(Lab 1 全部题目核对)+ 试卷 Q1 / Q6 / Q7 / Q8 + Course Review Unit 1 考点对照 + 梯度下降交互实验室。
后续单元(u02–u12)的讲义、t02–t11、项目说明、试卷其余题目、Course Review 均已提取到 extracted_dl/,随时可以按同样格式继续。