COMP 4930SEF Deep Learning —— Unit 12 Generative Deep Learning 逐页精讲

讲义:lecture/u12.pdf(Kayley Ma,共 50 页,按原页码逐页讲解,一页不落)
配套:本讲没有 Lab / Tutorial notebook(tutorial 只到 t11),讲义自带三段完整代码——Autoencoder(p14–p19)、GAN(p28–p36)、WGAN(p44–p50)——本讲义把这三段代码当作"Lab"逐 cell 精读,并在文末给出"代码精读"专卡;Course Review p10(Unit 12 五个考点:① 生成 vs 判别建模的定义 ② 自编码器如何工作 ③ GAN 如何工作 ④ 训练 GAN 的潜在问题 ⑤ GAN 代码示例(optional));10/22 试卷未考本讲内容

怎么用这份讲义:每一页是一张卡片,固定栏目 ——
① 页首:原页码 + 该页主题 + 标签(★Review / 🧮计算 / 代码 / 原图 / 附录) ② 原文要点:讲义原句,方便对照幻灯片
③ 核心概念 ④ 详细讲解(课堂式:背景 → 逻辑 → 例子) ⑤ 题目 / Review 关联 ⑥ 必要扩展 ⑦ 易错点 · 理解提示
讲义里的全部数字(p16 自编码器 1,087,800 参数、p28 生成器 108,092、p29 判别器 207,617、UpSampling / stride-2 的尺寸链 28→14→7→4、MNIST 数字 4+8 共 11,693 张 → batch 512 = 23 批/轮、p35 GAN 十条训练消息、p49 WGAN 十条训练消息、p36 / p50 两张曲线、Wasserstein 损失的符号推导)都已用 dl_u12_verify.py(83 项)逐位复算。讲义原图(p4 判别建模流程图、p10 自编码器结构、p11 潜空间生成、p6 / p7 两页应用图、p35 / p49 两页训练历史、p36 / p50 两张曲线)均用内联 SVG 重绘或转录。

全讲地图(50 页)

段主题页码内容 / Course Review p10 考点
AGenerative modellingp3–p8先回顾判别建模(p4:学 Prob(label | features),= 监督学习)→ 再定义生成建模(p5:学 Prob(features) 或 Prob(features, label),= 无监督)→ 三个应用:造假人脸(p6 thispersondoesnotexist)、风格迁移(p7 CycleGAN)、ChatGPT / MuseGAN / World models(p8)。Review #1 定义
BAutoencoders(原理)p9–p12编码器压缩 → 潜向量(latent code)→ 解码器重建(p10 结构图)→ 瓶颈逼网络学"高效表示";把随机噪声喂给解码器就能生成图(p11)→ 五个应用:生成 / 去噪 / 压缩 / 异常检测 / 降维(p12)。Review #2 AE 原理
CAutoencoder code examplep13–p19工具:加载 MNIST / 255 → (28,28,1)(p14)、plot_samples(p15)→ 编码器 784→512→256→40(sigmoid)、解码器 40→256→512→784(sigmoid)+ Reshape(p16,共 1,087,800 参数)→ 只用数字 4 和 8(11,693 张)、loss mse、100 轮 batch 256(p17)→ 输入 vs 重建(p18)→ np.random.random((10, 40)) 喂解码器生成(p19)。
DGAN 原理p20–p26生成器造假 + 判别器鉴真(p21,Goodfellow 2014)→ "能骗过聪明判别器的假货就是真货";今天 GAN ≈ DCGAN(p22)→ 训练 D:真假二分类(p23)→ 训练 G:冻结 D、假图标真(p24)→ 收敛 = D 50% / G 100%(p25)→ 五大困难:非收敛 / 模式崩溃 / G 梯度消失 / G 损失无信息 / 超参敏感(p26)。Review #3 GAN 原理、#4 训练问题
EGAN code examplep27–p36生成器:Dense(40→49) → BN → Reshape 7×7 → [UpSampling ×2 → Conv2D(64, 5×5, same) → BN] ×2 → Conv2D(1, sigmoid)(p28,108,092 参数)→ 判别器:Conv2D(64, 5×5, s2) + Dropout ×3 → Flatten(1024) → Dense(1, sigmoid),rmsprop(p29,207,617)→ 噪声 normal(0,1)(p30)→ train_on_batch 交替(p31)→ 双层循环 train_gan(p32)→ 每 10 轮打印 + 存样本(p33)→ 整合(p34)→ 10 条消息(p35:gen_loss .65→1.21、dsc_loss .11→.55)→ 曲线(p36)。Review #5 GAN 代码(optional)
FThe end + 附录 WGAN 原理p37–p42p37 正课结束 → WGAN(Arjovsky 2017):critic 而非 discriminator,损失有意义 + 训练更稳(p39)→ 五项改动:Wasserstein 损失 / 标签 ±1 / 去 sigmoid / 裁剪权重 / critic 多训(p40)→ 损失 −mean(y·p)、Lipschitz 约束靠裁剪 [−0.01, 0.01](p41)→ WGAN-GP:用梯度惩罚替代裁剪、critic 不用 BN(p42)。
GWGAN code examplep43–p50wasserstein = backend.mean(y_true * y_pred)、生成器复用(p44)→ 判别器去掉 sigmoid、编译用 wasserstein(p45)→ 训练:y_fake = −1、每层权重 np.clip(w, −0.05, 0.05)(p46)→ 每个 batch 训 critic 3 次、dsc_loss / 3(p47)→ 整合(p48)→ 10 条消息(p49:gen_loss −2036→−210、dsc_loss −286→−28,单调趋 0)→ 曲线(p50)。

主线一句话

前面十一讲学的全是"判别"——给特征贴标签(Prob(label | features));这一讲翻过来学"生成"——学数据本身的分布 Prob(features)。第一条路是自编码器:编码器把 784 维压成 40 维、解码器再还原,瓶颈逼它抓住本质(1,087,800 参数,mse 重建);把随机向量喂给解码器就能"画"出新数字。第二条路是 GAN:生成器造假、判别器鉴真,两个网络对抗着一起进步(生成器 108,092 / 判别器 207,617 参数,train_on_batch 交替);理论上收敛于判别器 50% 猜不准,实际上会遇到模式崩溃、梯度消失、损失无意义等五大困难。附录的 WGAN 用 Wasserstein 距离换掉交叉熵:critic 不带 sigmoid、标签 ±1、权重裁剪、critic 多训 3 次——损失变成一条单调趋 0 的"有意义"曲线。Course Review p10 五考点,代码题标 optional。

逐页导航

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950代码精读Review总结实验台
p.1Unit 12 · 生成深度学习(标题页)标题Unit 12
COMP 4930SEF/S493W Unit12 - Generative deep learning Kayley Ma
核心概念生成深度学习(generative deep learning):训练网络不是为了让它"判断",而是为了让它"创造"——造出训练集里不存在、但看起来像真的新样本。这是课程的最后一个单元,也是前面十一讲的"反面":Unit 1–11 的模型都在回答"这是什么?"(分类 / 回归),本讲的模型在回答"能不能造一个?"。
详细讲解

先想想课程的脉络:Unit 1–2 讲神经网络是什么、怎么训练;Unit 3–5 讲数学、全连接网络、反向传播;Unit 6–7 讲评估、正则化、优化器;Unit 8–9 讲 CNN 和迁移学习;Unit 10–11 讲文本表示和循环网络。这些单元有一个共同点——每个模型都在学一个从特征到标签的映射:图像 → 猫/狗,评论 → 正/负,新闻 → 20 个主题之一。这种"给输入、猜标签"的范式叫判别。

本讲要换一个范式。想象一下:不是给网络看一张手写数字的图让它判断是 4 还是 8,而是让网络自己画一个 4 出来。这就需要网络理解"4 长什么样"——不是"4 和 8 的区别在哪",而是"4 本身的像素分布是什么"。前者学的是 Prob(label | features),后者要学 Prob(features)。数学对象变了,训练方法也就全变了:没有标签可以对照,损失函数怎么写?怎么判断画得好不好?这是本讲要回答的两个问题,分别用自编码器(p9–p19)和 GAN(p20–p36)回答。

标题页的英文 "Generative deep learning" 也是 Goodfellow 等人 2016 年那本教科书《Deep Learning》第三部分的名字——"Modern Practices" 讲判别、"Deep Learning Research" 讲生成。本讲相当于把那本书的三大生成模型(自编码器、GAN、以及附录的 WGAN)各取一个最小可运行的例子。

题目 · Review 关联
  • Course Review p10 #1:"The definition of generative and discriminative modelling"——本讲要能用一句话区分:判别学 Prob(label | features),生成学 Prob(features) 或 Prob(features, label)。
  • 期末考若问"以下任务属于生成还是判别:① 手写数字识别 ② 生成不存在的人脸 ③ 情感分析 ④ 风格迁移"——①③ 判别、②④ 生成。
必要扩展
  • 本讲没讲但同属"生成模型"家族的还有:VAE(变分自编码器,Kingma & Welling 2013)、扩散模型(Diffusion,2020 后成为 Stable Diffusion / DALL·E 的基础)、自回归语言模型(GPT 系列——Unit 11 的文本生成就是一个 5,000 词的小语言模型)。
  • "生成"和"无监督"并不完全等价:自编码器无标签、GAN 也无标签,但 p5 原文用的是 "usually"——因为也有用标签的条件生成(cGAN、image captioning)。
易错点 · 理解提示① 不要把"生成模型"和"生成对抗网络"画等号——GAN 只是生成模型的一种,自编码器也是。② "判别"(discriminative)在这里是"判别建模"的意思,和 GAN 里的"判别器"(discriminator)是同一词根但不是同一个东西:前者指整个范式,后者指 GAN 里的一个子网络。
p.2目录:生成建模 / 自编码器 / GAN / WGAN 附录目录
Contents  Generative modelling  Autoencoders  Autoencoder code example  Generative adversarial networks  GAN code example  Appendix: Wasserstein GANs & code example
核心概念六个部分两两配对:每个模型先讲原理再讲代码——自编码器(p9–12 原理 → p13–19 代码)、GAN(p20–26 原理 → p27–36 代码);附录 WGAN 同样"原理(p38–42)+ 代码(p43–50)"。
详细讲解

把目录和 Course Review p10 对照着看会发现一件有意思的事:Review 的五个考点正好对应目录的前五项——#1 生成/判别建模定义(→ Generative modelling)、#2 自编码器原理(→ Autoencoders)、#3 GAN 原理(→ Generative adversarial networks)、#4 训练 GAN 的问题(→ 在 p26)、#5 GAN 代码(→ GAN code example,标注 optional)。而附录的 WGAN 不在 Review 里——意味着期末考大概率不考 WGAN 的细节,但它恰恰是理解"GAN 损失为什么没意义"的最佳对照,所以本讲义仍然逐页讲。

另一个值得注意的结构:自编码器的代码例(p13–19,7 页)比 GAN 的(p27–36,10 页)短,因为自编码器只有一个模型、一个损失、一个 fit;GAN 要分别建两个模型、分别编译、交替训练,代码量自然翻倍。这也预示了 GAN 的"难"不在概念,而在工程。

题目 · Review 关联
  • Review #5 "GAN code example (optional)"——"optional" 意味着不要求默写整段代码,但要能读懂:哪一行是生成器、哪一行冻结判别器、train_on_batch 在做什么。本讲义的"代码精读"专卡按这个标准写。
  • Review 没列 "Autoencoder code",但 p16 的参数计算(784→512→256→40)是 Unit 4 Dense 参数公式的直接应用,很可能出现在"计算题"里。
必要扩展
  • 为什么 WGAN 放附录?因为它 2017 年才发表(Arjovsky),而且改动看似小(五个改动)但背后是最优传输理论(Earth Mover's distance)——课程定位是"知道有这回事、能读懂代码"即可。
易错点 · 理解提示目录里 "Autoencoder code example" 和 "GAN code example" 都是独立章节,不是原理章节的附页——期末考"long questions: modify code"很可能就从这两段代码里出(例如"把 SZ_LATENT_AE 改成 2 会怎样""把判别器的 Dropout 去掉会怎样")。
p.3分节页:Generative modelling分节
Generative modelling
核心概念进入第一段:先给出"生成建模"的正式定义(p4–5),再用三个应用页(p6–8)让你直观感受"生成"能做什么。
详细讲解

分节页本身没有内容,但顺序值得注意:讲义先讲判别建模(p4)再讲生成建模(p5)——先回顾你熟悉的,再引入陌生的。这是本讲的基本教学策略:每一页生成模型都与对应的判别模型对照。读后面几页时,建议你心里一直放着一个问题:"如果用 Unit 4–11 的判别思路来做这件事,会卡在哪里?"——答案通常是"没有标签"。

另外,这一节的三个应用页(p6 人脸、p7 风格迁移、p8 ChatGPT/音乐/世界模型)分别对应图像、图像到图像、文本/音频/视频三种生成形态——讲义故意跨了三个模态,是为了让你看到"生成"不限于图像。本讲后面的代码只做图像(MNIST),但原理(潜空间、解码器、对抗)对文本和音频同样适用——Unit 11 的文本生成就是"解码器 + 自回归"的一个实例。

题目 · Review 关联
  • Review p10 #1 的定义题,标准答法就是 p4 + p5 两页的四句话(见下两卡)。
必要扩展
  • 生成建模在统计里有更长久的历史:高斯混合模型、隐马尔可夫模型、朴素贝叶斯都是"生成模型"——它们都建模 Prob(x, y)。深度学习只是把 x 换成了高维图像/文本。
易错点 · 理解提示分节页不计入 Review 考点,但本讲义仍然给一张卡片——保持"逐页不落"。
p.4判别建模(Discriminative modelling)★Review定义原图
Discriminative modelling refers to learning a model for predicting labels – numbers or categories – from features ➢ Equal to supervised learning, using labelled examples for training ➢ Solve many machine learning problems faced today ➢ Mathematically, to estimate Prob(label | features)
Labelled examples 0 1 Training Discriminative model Unlabelled example Prediction Predicted value 0.8 判别建模:有标签 → 学 Prob(label | features) → 对新样本输出一个值
图 12.P4 讲义 p4 原图重绘:带标签的样本(星形 0/1)→ 训练 → 判别模型;推理时输入无标签样本 → 输出预测值 0.8。
核心概念判别建模 = 学一个从特征预测标签的模型,数学上是估计 Prob(label | features)。四条要点:① 预测的标签可以是数(回归)或类别(分类);② 等于监督学习,训练要有标签;③ 解决了当今大多数机器学习问题;④ 数学目标是条件概率。
详细讲解

"Prob(label | features)" 这个记号:竖线读"给定"——"在看到特征的条件下,标签是什么的概率"。对 Unit 5 的手写数字分类器,就是"给定这 784 个像素,它是 0 的概率、是 1 的概率……是 9 的概率"——一个 10 维的 softmax 输出。对 Unit 4 的回归(预测房价),就是"给定面积、房间数,价格的条件分布"——网络输出均值。

原图的含义:左边两张带标签的图(星形,标签 0 和 1)是训练集——"labelled examples";经过"Training"得到中间的"Discriminative model";推理时从下方输入一张"Unlabelled example"(没有标签的新星形),模型向右输出"Predicted value 0.8"。注意 0.8 不是标签本身,而是一个分数——二分类里 sigmoid 输出 0.8 意味着"我 80% 认为它是类别 1"。这张图把 Unit 4–11 所有模型的训练/推理流程画成了一行。

为什么强调"supervised"和"labelled":因为这是判别建模的硬性前提——没有标签就没有 Prob(label | features) 可以学。而现实中标签很贵(ImageNet 的 1400 万张图是人工标的)、有些任务根本没有明确标签("一张好看的脸"是什么标签?)。这就是下一页生成建模要解决的痛点。

题目 · Review 关联
  • Review #1 标准答案:"Discriminative modelling learns a model for predicting labels (numbers or categories) from features. It equals supervised learning using labelled examples. Mathematically it estimates Prob(label | features)."
  • Unit 5(softmax + categorical_crossentropy)、Unit 10–11(Dense(1, sigmoid) + binary_crossentropy)全是判别建模的实例——期末考如果让你"举一个判别模型的例子",随手写 Unit 10 的 CNN 情感分类器即可。
必要扩展
  • 判别模型的另一类:不输出概率而直接输出决策边界(SVM)——深度学习里几乎都用概率输出,所以讲义只提 Prob(label | features)。
  • 判别建模的"反面"不只是生成建模:无监督的聚类、降维(PCA)既不判别也不生成(它们学的是数据的结构,不是分布)。自编码器介于两者之间(见 p12)。
易错点 · 理解提示① "Predicted value 0.8" 在原图里是模型的输出,不是样本的真实标签——别把它和训练样本的 0/1 标签混淆。② 判别建模 ≠ 分类:回归(标签是数)也是判别。③ 判别建模 ≠ "判别器":GAN 里的 discriminator 是判别建模思想的一个具体应用(真/假二分类),但两个词的范围不同。
p.5生成建模(Generative modelling)★Review定义
Generative modelling refers to learning a model for generating new data with specific characteristics ➢ Usually equal to unsupervised learning, using unlabelled examples ➢ Create contents and go beyond discriminative modelling alone ➢ Mathematically, to estimate Prob(features) or Prob(features, label)
核心概念生成建模 = 学一个能生成具有特定特征的新数据的模型,数学上是估计 Prob(features)(数据本身的分布)或 Prob(features, label)(联合分布)。四条要点与 p4 一一对照:① 从"预测标签"变成"生成数据";② 通常等于无监督学习,用无标签样本;③ 创造内容,超越判别建模;④ 数学目标是(联合)概率。
详细讲解

Prob(features) 和 Prob(label | features) 的区别:判别模型学的是"给定特征,标签的概率"——它不需要知道特征本身长什么样,只要能画出两者的边界就行。生成模型要学的是"特征本身出现的概率"——它必须知道一张 28×28 的手写数字图里,哪些像素组合常见、哪些不常见。用一个比喻:判别模型学的是"怎么区分鸭子和兔子",生成模型学的是"鸭子长什么样、兔子长什么样"——后者显然要求更多,但学会了就能"画"出一只新鸭子。

为什么写 "Prob(features) or Prob(features, label)":有两种生成模型。无条件的(GAN、本讲的自编码器)只学 Prob(x)——"什么样的图是手写数字"。有条件的(cGAN、图像描述生成)学 Prob(x, y) 或 Prob(x | y)——"给定标签 4,什么样的图是 4"。本讲讲义只涉及前者,但定义里把联合分布也列出来,是为了覆盖有标签的情形。

"Usually equal to unsupervised learning" 里的 "usually":自编码器的训练数据没有标签(只有图像本身),GAN 也是;但 Unit 11 的文本生成模型用的是"前 n 个词 → 下一个词"——它把文本自身切成特征和标签,严格说是自监督(self-supervised)。讲义用 "usually" 是严谨的。

把 p4 和 p5 并排:

判别建模(p4)生成建模(p5)
目标预测标签(数 / 类别)生成新数据(特定特征)
学习范式监督学习,有标签(通常)无监督学习,无标签
数学目标Prob(label | features)Prob(features) 或 Prob(features, label)
输出一个值 / 一组概率一个样本(图 / 文 / 音)
本课程实例Unit 4–11 全部Unit 11 文本生成、Unit 12 AE / GAN
题目 · Review 关联
  • Review #1 标准答案:"Generative modelling learns a model for generating new data with specific characteristics. It is usually unsupervised learning using unlabelled examples. Mathematically it estimates Prob(features) or Prob(features, label)."
  • 常见的 2–3 分简答题:"Discriminative modelling estimates ______ while generative modelling estimates ______."——填 Prob(label | features) / Prob(features)。
必要扩展
  • 生成模型学到 Prob(x) 之后,其实也能做分类:用贝叶斯定理 Prob(y | x) = Prob(x | y) Prob(y) / Prob(x)——这就是朴素贝叶斯、GMM 分类的原理。反过来,判别模型(只学 Prob(y | x))不能生成。所以理论上生成模型"更强",但高维数据上更难学——这是 GAN / VAE / 扩散模型要解决的核心难题。
  • 评价生成模型的困难也源于此:判别模型有准确率,生成模型没有"正确答案"——只能用 Inception Score、FID(Fréchet Inception Distance)这类间接指标,或者人眼判断。
易错点 · 理解提示① 别把 "Prob(features)" 写成 "Prob(features | label)"——后者是条件生成,不是本讲定义。② 生成建模 ≠ 一定无标签(有条件的生成用标签),所以讲义写 "usually"。③ 本讲的自编码器严格来说是"有损压缩 + 重建",它学到的 Prob(features) 是隐式的——这正是 p11 "把随机噪声喂给解码器"能工作的前提。
p.6应用例:创造图像内容(thispersondoesnotexist)原图应用
Deep learning can be applied to generate new data E.g. GAN, a kind of generative model, can create images of people who do not exist ➢ https://www.thispersondoesnotexist.com/
青年男性(示意)微笑女孩(示意) GAN 生成的人脸——这些人并不存在
图 12.P6 讲义 p6 两张 GAN 人脸(左:深色头发的年轻男性;右:微笑的金发女孩)。本图为示意重绘,原图为 StyleGAN 生成结果。
核心概念深度学习可以用来生成新数据。GAN 是一种生成模型,能创造出不存在的人的脸——thispersondoesnotexist 网站每次刷新都生成一张新面孔。
详细讲解

这一页的作用是"震撼"——让你直观看到生成模型的威力。两张人脸看起来完全真实:左图是深色短发、浅色眼睛、微微笑着的年轻男性,穿着深色衣服;右图是金发、露齿笑的女孩,穿着蓝色上衣,背景是暗色夜景。但它们都不是真人——是 StyleGAN(NVIDIA 2019)从随机噪声生成出来的。网站每次刷新都从 512 维的正态分布采一个向量,喂给生成器,输出一张 1024×1024 的人脸。

为什么这是"生成建模":生成器学的是"人脸的分布 Prob(face)"——什么肤色常见、眼睛在哪、牙齿多白、背景和衣服怎么搭。它从未被告诉"这是脸",只是看了几万张真脸,就学会了"脸长什么样"。这和 p5 的定义完全吻合:无标签、学 Prob(features)、创造新内容。

和判别模型对比:如果用 Unit 9 的 VGG16 看这两张脸,它会判断"这是人,不是猫/狗"——这是判别。而生成器画出这两张脸——这是创造。同一个数据集(人脸照片),两种任务,两种数学目标。

题目 · Review 关联
  • Review #1 若考"举一个生成模型的应用例子"——"GAN generates images of people who do not exist (thispersondoesnotexist.com)" 就是标准答案。
  • 若考"这个应用是判别还是生成?为什么?"——生成:它学 Prob(features)(人脸分布),输出的是新样本而不是标签。
必要扩展
  • thispersondoesnotexist 用的是 StyleGAN,不是本讲 p28 的那个小 GAN——后者只能在 28×28 上画数字。区别在于规模(百万级参数 vs 10 万)和训练数据(七万张人脸 vs 一万张数字)。但原理相同:生成器 + 判别器对抗。
  • 这类"deepfake"技术也带来伦理问题:伪造人脸可能被用于诈骗、虚假信息——期末考若问"生成模型的社会影响",可以提这一点。
易错点 · 理解提示讲义原图是真实 GAN 输出,本讲义用示意图代替——考场上描述这页时说"两张看起来真实的人脸,实际由 GAN 生成"即可,不需要描述具体人物。
p.7应用例:风格迁移(CycleGAN)原图应用
Style transfer means combining the content of an image with the style of another image, e.g. the style of a painting from Monet or Van Gogh E.g. CycleGAN, https://github.com/junyanz/CycleGAN
Input Monet Van Gogh Cezanne Ukiyo-e 5 列 × 4 行:同一张风景照分别迁移到 Monet / Van Gogh / Cezanne / Ukiyo-e 四种画风(本图为色块示意)
图 12.P7 讲义 p7 CycleGAN 风格迁移网格(示意重绘):左列 Input,右侧四列分别为四位画家的风格。
核心概念风格迁移(style transfer):把一张图的内容和另一张图的风格结合起来——例如把一张风景照片画成莫奈或梵高的笔触。CycleGAN 是其中一种实现,不需要成对的训练数据。
详细讲解

原图是一个 5 列 × 4 行的网格:第一列 "Input" 是四张真实的风景照(一座皇家建筑、一处城堡废墟、一条运河、一排彩色房子);右边四列分别把同一张照片变成 Monet(莫奈)、Van Gogh(梵高)、Cezanne(塞尚)、Ukiyo-e(浮世绘)的风格。内容不变——建筑还是那座建筑、运河还是那条运河;风格全变——莫奈版笔触柔和偏紫粉、梵高版有旋转的黄色笔触、塞尚版偏绿色块、浮世绘版是日本木刻画的扁平蓝色。

"内容"和"风格"怎么分开:一张图经过 CNN 时,浅层特征记录边缘、纹理(风格),深层特征记录物体、结构(内容)。风格迁移的本质是:保留输入图的深层特征(内容),同时让输出的浅层特征统计量(Gram 矩阵)匹配风格图的——这是 Gatys 2016 的方法。CycleGAN 走另一条路:训练两个生成器 G(照片→画)和 F(画→照片),要求 F(G(x)) ≈ x(循环一致性),这样不需要"同一场景的照片和画"成对出现。

这是生成建模吗:是——它输出的是一张新图(不存在的莫奈风格的这座建筑),不是标签。但和 p6 不同,它学的是 Prob(风格图 | 内容图)——条件生成,对应 p5 的 Prob(features, label) 那一支。

题目 · Review 关联
  • Review #1 的例子库里可以加这条:"Style transfer combines the content of one image with the style of another (e.g., Monet / Van Gogh); CycleGAN is an example."
  • 和 Unit 9 迁移学习对比:迁移学习是"用预训练模型提特征再分类"(判别);风格迁移是"用预训练模型提特征再重组"(生成)——两者都用 VGG 的多层特征,但目标相反。
必要扩展
  • CycleGAN 也有 GAN 的对抗结构:G(照片→莫奈)要骗过一个"莫奈判别器"。所以它是 GAN 的变体——本讲 p21–26 的原理在这里同样适用,只是多了"循环一致性"约束。
  • 常见的失败模式:马→斑马时,如果背景有草地,可能会把草地也变成斑马纹——生成器把"斑马"和"草原"的关联学过了头。这是 GAN "学到捷径"的一个例子。
易错点 · 理解提示① 风格迁移不是"滤镜"——滤镜是固定的像素变换,风格迁移是学出来的、每张图结果不同。② CycleGAN 不需要成对数据,但 Gatys 的神经风格迁移需要一张风格图(单张即可)。③ 考试若问"风格迁移属于哪种建模"——生成(条件生成)。
p.8更多应用例:ChatGPT / MuseGAN / World models应用
A chatbot that chats with people and answers questions ➢ ChatGPT Generating polyphonic music of multiple instruments (i.e., tracks) ➢ MuseGAN Training an intelligent agent using a generative simulated environment instead of a real environment ➢ World models
核心概念三个跨模态的生成应用:① ChatGPT——对话生成(文本);② MuseGAN——多轨复调音乐生成(音乐);③ World models——用生成的模拟环境训练智能体(强化学习)。
详细讲解

ChatGPT:本质是 Unit 11 文本生成的放大版——Unit 11 用 LSTM(128) + Dense(5000) 预测下一个词,ChatGPT 用 GPT(Transformer 解码器)+ 数万维词表预测下一个 token。都是自回归生成:给前面的词,预测下一个,拼上去,再预测。区别只是规模(1750 亿参数 vs 124 万)和训练数据(互联网文本 vs 一本《爱丽丝》)。

MuseGAN:生成多声部音乐——"polyphonic"(复调)指同一时刻有多个音符(多个乐器轨道)。它把每个时间步的钢琴卷帘(piano roll,哪些音在响)当作一张多通道的图来生成,用的也是 GAN 框架:生成器造一段多轨音乐,判别器判断"这像不像真的音乐"。

World models:训练强化学习智能体(玩游戏的 Agent)通常要在真实环境里试错,成本高、危险。World models 的思路:先用 VAE + RNN 学一个环境的生成模型(给定当前画面和动作,预测下一帧),然后让智能体在这个"梦里"训练。这是生成模型的一种间接用途——不是生成最终内容,而是生成训练环境。

三者的共同点:都在学 Prob(features)——文本的分布、音乐的分布、游戏画面的分布;都没有标签;都用深度网络。不同点在数据类型(文本 / 音乐 / 视频)和网络结构(Transformer / GAN / VAE+RNN)。

题目 · Review 关联
  • Review #1 若要求"举三个生成模型的应用"——p6 人脸、p7 风格迁移、p8 任选一个,三个不同模态更好。
  • ChatGPT 和 Unit 11 文本生成的联系很可能被考:"Unit 11 的 generate_text 和 ChatGPT 的原理有何异同?"——同:自回归预测下一个词 + 采样;异:模型(LSTM vs Transformer)、规模、词表、温度/top-p 等采样策略。
必要扩展
  • World models 的 "VAE"(变分自编码器)是本讲自编码器的概率版本——编码器输出的不是确定的潜向量,而是一个均值 + 方差,从中采样。本讲不涉及,但知道这个词有助于读懂相关论文。
  • MuseGAN 对应的是 2017 年的论文,今天的音乐生成已经转向 Transformer(如 MusicLM)——和文本一样,GAN 在序列数据上逐渐被自回归模型取代,在图像上被扩散模型取代。
易错点 · 理解提示① 本页没有图(讲义 p8 是纯文字 + 链接),不要凭空描述"有截图"。② ChatGPT 严格说是"生成式"而非"GAN"——它是自回归模型,不是对抗网络;"生成模型 ≠ GAN"这一点在本页再次体现。
p.9分节页:Autoencoders分节
Autoencoders
核心概念进入第二个模型:自编码器(autoencoder)——最简单的生成模型:一个"压缩再解压"的网络,用重建输入作为训练目标。
详细讲解

讲义对自编码器的安排是"原理 4 页(p10–12)+ 代码 7 页(p13–19)"。原理部分只有三件事:结构(编码器-瓶颈-解码器)、潜空间(为什么瓶颈能学到特征)、应用(p12 列了五个)。代码部分则是完整的 Keras 实现:加载 MNIST → 搭编码器和解码器 → 训练 → 看重建 → 用随机向量生成。

学这一段时,建议一直对照 Unit 4 的全连接网络:自编码器的编码器就是 Unit 4 的 Dense 堆叠(784→512→256→40),只是没有标签——训练时输入和输出都是同一张图。这是一个"把监督网络改成无监督"的最小改动,也是理解后面 GAN 的基础:GAN 的生成器就是一个"没有编码器的解码器"。

题目 · Review 关联
  • Review p10 #2:"Autoencoders"——原理题的标准答案来自 p10–11:编码器压缩到潜向量、解码器重建、瓶颈迫使网络学高效表示、随机潜向量可生成新样本。
  • Unit 4 的 Dense 参数计算((输入+1)×输出)在 p16 会再用一次——如果期末考出"计算自编码器参数量",就是这个公式的直接套用。
必要扩展
  • 自编码器的历史比深度学习早:Rumelhart 等人 1986 年(p10 引用)就提出用它做降维;Hinton & Salakhutdinov 2006 的"深度自编码器"是深度学习复兴的起点之一——先用无监督逐层预训练,再有监督微调。
  • 与 PCA 的关系:如果编码器和解码器都是线性的、损失用 MSE,自编码器学到的前 k 个主成分和 PCA 一致(相差一个旋转)。加上 ReLU 非线性后,它能学到 PCA 学不到的弯曲流形。
易错点 · 理解提示分节页本身不考,但要注意:Course Review 把 "Autoencoders" 列为 #2 考点,没列 "Autoencoder code"——意味着原理(p10–12)必背,代码(p13–19)要能读懂、能算参数,但不要求默写。
p.10自编码器结构(编码器 / 潜向量 / 解码器)★Review结构原图
Autoencoder structure Rumelhart et al, 1986, https://stanford.edu/~jlmcc/papers/PDP/Volume 1/Chap8_PDP86.pdf  An autoencoder consists of an encoder and a decoder  The encoder compresses input data to lower-dimensional data, called the latent code or latent vector  The decoder reconstructs the original data from the latent vector
自编码器:编码器压缩 → 潜向量 → 解码器重建 Inputimage28×28×1 Encoder784→512→256 Compressed representationin latent space · 40 Decoder40→256→512 Reconstructedimage28×28×1 目标:输出 ≈ 输入(重建)
图 12.P10 讲义 p10 原图重绘:Input image → Encoder(绿色梯形,逐层变窄)→ Compressed representation in latent space(黄色窄块)→ Decoder(红色梯形,逐层变宽)→ Reconstructed image。本讲代码的维度 784→512→256→40 已标注。
核心概念自编码器 = 编码器(encoder)+ 解码器(decoder)。编码器把输入数据压缩成低维数据——叫潜码(latent code)或潜向量(latent vector);解码器从潜向量重建原始数据。三个英文别名要记牢:latent code = latent vector = compressed representation。
详细讲解

看图的方法:原图从左到右五个部分,形状是一个"沙漏"——左边宽(输入 784 维),中间窄(潜向量 40 维),右边又宽(输出 784 维)。绿色梯形是编码器,越往右越窄,表示每过一层维度就减少;红色梯形是解码器,越往右越宽。中间黄色的窄块就是潜向量,也叫瓶颈(bottleneck)——p11 会专门讲它的作用。

编码器做什么:以本讲 p16 的代码为例,输入是 28×28 的图,先 Flatten 成 784 维向量,再过 Dense(512, relu) → Dense(256, relu) → Dense(40, sigmoid)。三层权重矩阵的形状分别是 784×512、512×256、256×40——每一层都在"把信息挤进更少的数字里"。最后得到的 40 个 0–1 之间的数就是潜向量。

解码器做什么:反过来,Dense(256) → Dense(512) → Dense(784, sigmoid) → Reshape(28,28,1)。从 40 个数恢复出 784 个像素值。注意最后一层用 sigmoid——因为像素已经除以 255 归一化到 [0,1],sigmoid 的输出范围正好也是 [0,1]。

怎么训练:没有标签。把图 x 喂进去,得到重建 x̂,损失 = x 和 x̂ 的差异(p17 用的是 MSE)。训练目标就是让 x̂ ≈ x——"重建"。这个目标不需要任何人工标注,所以自编码器是无监督的。

一个直观的比喻:编码器像 ZIP 压缩,解码器像解压。但 ZIP 的压缩算法是人设计的、固定的;自编码器的"压缩算法"是从数据里学出来的,而且是有损的——40 个数不可能完美保存 784 个像素,网络必须学会"哪些信息重要、哪些可以丢"。

题目 · Review 关联
  • Review #2 原理题标准答案第一句:"An autoencoder consists of an encoder and a decoder. The encoder compresses input data into a lower-dimensional latent vector; the decoder reconstructs the original data from the latent vector."
  • 本讲 p16 的结构正是这张图的实例:784→512→256→40(编码器)、40→256→512→784(解码器)。期末考若给一段 Keras 代码让你"指出哪部分是编码器、潜向量维度是多少"——看第一个 Sequential 到 Dense(SZ_LATENT_AE) 为止是编码器。
  • Rumelhart 1986 的引用(PDP 第 1 卷第 8 章 "Learning Internal Representations by Error Propagation")是 backpropagation 的奠基论文之一——和 Unit 5 的反向传播同源。
必要扩展
  • "潜"(latent)的意思是"隐藏的、潜在的"——潜向量不是人定义的特征(比如"笔画数""圆圈数"),而是网络自己学出来的内部表示。它的每一维通常没有人类可解释的含义,但这不妨碍解码器用它重建。
  • 自编码器的变体:稀疏自编码器(加 L1 惩罚让潜向量稀疏,潜维度可以比输入还大)、去噪自编码器(输入加噪声、目标仍是干净的原图,p12 会提)、卷积自编码器(用 Conv2D + MaxPooling 代替 Dense,适合大图)。
  • 和 Unit 7 的 Dropout 对比:Dropout 是训练时随机关掉一些神经元、测试时全开;自编码器的瓶颈是永久性的窄通道。两者都是"限制信息流,迫使网络学更鲁棒的表示"——这是正则化思想的另一种体现(Unit 6)。
易错点 · 理解提示① 编码器和解码器不是同一个网络的两半共享权重——它们是两个独立的 Sequential,权重互不相关。② "压缩"是有损的:40 维潜向量不可能无损保存 784 维输入,所以 p18 对比输入和输出时会看到重建图略模糊。③ 自编码器的"训练目标"不是分类——fit(X_train, X_train) 的输入和输出是同一个东西,这是和 Unit 4–11 最大的代码差异。
p.11潜空间与图像生成(瓶颈 / 随机噪声)★Review潜空间原图
Latent space and image generation  The compressed data have lower dimensions, called a latent space ➢ Form a bottleneck in the network  Force the network to learn efficient representations of the data ➢ I.e. capture important features of the data  To generate images, feed a latent vector of random numbers (noise) to the decoder
生成:跳过编码器,直接把随机噪声喂给解码器 Random noisez ∈ (0,1)40 Decoder40→256→512→784 Generated image(s) np.random.random((10, 40)) 解码器已学会"40 个数 → 数字长什么样"
图 12.P11 讲义 p11 原图重绘:Random noise → Decoder → Generated image。原图右侧为多张生成结果;本图标注 p19 代码用的均匀分布噪声 np.random.random((10, 40))。
核心概念压缩后的低维数据所在的空间叫潜空间(latent space)。低维形成了网络中的瓶颈(bottleneck),迫使网络学习数据的高效表示——即捕捉数据的重要特征。要生成图像,只需把一个随机数组成的潜向量(噪声)喂给解码器。
详细讲解

为什么瓶颈能迫使网络学"重要特征":这是本页最核心的逻辑,值得慢慢推。假设没有瓶颈——编码器 784→1024→2048,解码器 2048→1024→784。网络完全可以学一个恒等映射:每一层只把输入原样传下去,重建误差为 0,但它什么也没学到。有了 40 维的瓶颈,784 个数必须被压成 40 个,网络不可能原样传递,只能找一种"压缩方案"——而最省力的压缩方案就是把同类样本的共同结构编码进去(比如"4 的上半部分是开放的两笔、中间一横")。这个"被迫找规律"的过程,就是学习高效表示。

潜空间是什么样:想象 40 维空间里的每一个点都对应一张图。训练后,所有训练样本的潜向量会在这个空间里聚成簇——所有 4 的潜向量靠近一团,所有 8 的靠近另一团。簇内的点解码出来是形状略有不同的 4,簇间的点解码出来可能是 4 和 8 的"混合体"。这就是"潜空间"的几何直观。

为什么随机噪声能生成图:训练完成后,解码器已经学会了"40 维空间里任何一个(0–1 范围内的)点 → 一张 28×28 的图"的映射。所以你随便采一个 40 维向量喂进去,它都会给你一张图——只不过如果采到的点落在训练数据没覆盖的区域,图会很奇怪(模糊的、不像任何数字的形状)。p19 用的 np.random.random((10, 40)) 是 [0,1) 上的均匀分布——和编码器最后一层 sigmoid 的输出范围一致,所以采到的点大概率落在"有数据"的区域。

这就是"生成":p5 说生成建模要学 Prob(features)。自编码器通过"压缩-重建"间接学到了数据流形的结构——潜空间里有数据的区域就是 Prob 高的区域。从那里采样再解码,就得到了"像训练数据"的新样本。这是最朴素的生成方式,也是 p19 的做法。

题目 · Review 关联
  • Review #2 原理题标准答案第二句:"The low-dimensional latent vector forms a bottleneck, forcing the network to learn efficient representations capturing important features. To generate images, feed a random latent vector (noise) to the decoder."
  • 可能的简答题:"Why do we need a bottleneck in an autoencoder?"——答:Without it, the network can learn the identity function; the bottleneck forces it to capture only the important features(见上文推导)。
  • p19 的代码 np.random.random((10, SZ_LATENT_AE)) 是本页"feed a latent vector of random numbers"的直接实现——考"generate samples using an autoencoder"时别忘了写"decoder.predict",而不是"autoencoder.predict"。
必要扩展
  • 潜空间的"插值":取两个潜向量 z₁、z₂ 的中点 (z₁+z₂)/2 解码,通常得到一张"介于两者之间"的图——这是自编码器/V AE 常见的可视化。但普通自编码器的潜空间不连续:有些区域从未被训练数据覆盖,随机采到的点解码出来是噪声——这正是 VAE 要解决的问题(加 KL 惩罚让潜空间接近正态分布)。
  • 为什么 p16 的潜向量用 sigmoid 而不是 relu:sigmoid 把潜向量限制在 (0,1),给潜空间一个有界的取值范围——这样 p19 用均匀分布 U[0,1) 采样才合理。若用 relu,潜向量可能取到 50、100 这样的大值,均匀采样就采不到训练数据所在的区域。
  • 和 Unit 6 降维的对比:PCA 把数据投到前 k 个主成分上(线性);自编码器的瓶颈是非线性降维。两者目的相同——"用更少的数表示数据,同时保留重要信息"。
易错点 · 理解提示① "Latent space" 是一个空间(所有可能的潜向量的集合),"latent vector" 是空间中的一个点——别混用。② 瓶颈的作用是防止学恒等映射,不是"减少参数"——事实上加了瓶颈之后参数可能更多(本讲 1,087,800)。③ 随机噪声生成的是"像训练数据"的图,不是"任意的图"——解码器只见过数字 4 和 8(p17 用 "48" 训练),所以生成结果只会是 4 或 8 的变体。
p.12自编码器的应用(生成 / 去噪 / 压缩 / 异常检测 / 降维)★Review应用
Applications of autoencoders  Image generation using the decoder  Image denoising from noisy images to clean images  Data compression using latent vectors  Anomaly detection by measuring reconstruction errors  Dimensionality reduction and feature extraction
核心概念自编码器的五个应用:① 用解码器生成图像;② 图像去噪(噪声图 → 干净图);③ 用潜向量做数据压缩;④ 用重建误差做异常检测;⑤ 降维与特征提取。
详细讲解

五个应用可以按"用自编码器的哪个部分"分成三组:

应用用到的部分怎么做关键点
图像生成解码器随机采一个潜向量 → decoder.predict潜空间要有数据的区域(p11、p19)
图像去噪整个自编码器输入加噪声的图,目标输出干净的图训练时输入 = 噪图,标签 = 原图(改变训练对)
数据压缩编码器 + 潜向量存 40 维潜向量而不是 784 维像素有损压缩;压缩比 784/40 = 19.6(本讲)
异常检测重建误差正常数据训练;重建误差大的就是异常网络只学过"正常",没见过异常 → 重建不好
降维 / 特征提取编码器输出用 40 维潜向量代替 784 维像素喂给下游分类器相当于 Unit 9 的"预训练 + 微调",但无监督

去噪是这五个里最"反直觉"的:训练自编码器时,输入是加了噪声的图,目标是干净的原图——这样网络学会的就不是"复制输入",而是"去掉噪声、还原结构"。 bottleneck 迫使它只能保留主要结构(数字的笔画),噪声因为随机、无结构,在压缩时被自然丢掉。

异常检测的逻辑很巧妙:用一万张正常的心电图训练自编码器,它学会了重建正常波形。来一张异常的,编码器没见过这种形状,潜向量抓不住特征,重建出来和输入差很远——重建误差大 → 报警。这里"误差大"不是模型的缺陷,而是检测信号。

降维和特征提取与 Unit 9 迁移学习的关系:Unit 9 用 ImageNet 预训练的 VGG16 提取特征(有标签的预训练);自编码器用无标签数据预训练,把编码器当作特征提取器。在标签稀缺的场景(医学影像),这种无监督预训练特别有用。

题目 · Review 关联
  • Review #2 若考"State TWO applications of autoencoders"——五个任选两个,但建议写"image generation using the decoder" 和 "anomaly detection by measuring reconstruction errors"(一个用解码器、一个用误差,覆盖面广)。
  • 和 Unit 6 的联系:"降维"是 Feature Engineering 的一种——期末考若问"如何用无监督方法做特征提取",自编码器的编码器是标准答案。
  • 可能的"modify code"题:"Modify the autoencoder to perform image denoising"——答:autoencoder.fit(X_noisy, X_train, ...),其中 X_noisy = X_train + noise,再 clip 到 [0,1]。
必要扩展
  • 去噪自编码器(Vincent et al. 2008)是深度学习早期最重要的预训练方法之一——比 Dropout 还早。它的核心思想"破坏输入、要求还原"后来演化成 Masked Autoencoder(MAE,2021)——He 等人用"遮住 75% 的图像块让模型还原"做视觉预训练。
  • 数据压缩的局限:普通自编码器的潜空间是"有损且任务相关"的——它只对训练分布内的数据有效。所以实际压缩标准(JPEG、AV1)仍然用人工设计的算法;学习压缩是近年来的研究方向(Ballé 2016 的 end-to-end compression)。
  • 异常检测的工业应用:制造业质检(正常产品图像训练,缺陷品重建误差大)、网络入侵检测、信用卡欺诈检测。
易错点 · 理解提示① 去噪自编码器和普通自编码器的结构完全相同,区别只在训练数据(输入加噪)——不要以为去噪需要特殊的层。② "数据压缩"是有损的,不能像 ZIP 一样完美还原——p18 的重建图会略模糊。③ 五个应用里,只有"生成"用的是解码器单独,其余四个都用到编码器或整个网络。
p.13分节页:Autoencoder code example分节
Autoencoder code example
核心概念进入自编码器的代码段(p14–19):两页工具代码(加载数据、画图)+ 一页建模(p16)+ 一页训练(p17)+ 两页看结果(p18–19)。
详细讲解

这段代码是本讲三段代码中最短的,也是 GAN 代码(p28–36)的"地基"——p14 的 load_and_prep_mnist、p15 的 plot_samples 在 GAN 和 WGAN 代码里被原样复用。所以读懂这两页工具函数,后面两段代码就只剩"建模 + 训练循环"两件事。

阅读代码的建议顺序:先看 p17(怎么用)——load_and_prep_mnist("48") → Sequential([encoder, decoder]) → fit(X, X);再回头看 p16(encoder/decoder 怎么定义);最后看 p18–19(结果)。这种"先看入口、再看细节"的读法比从头到尾顺读更高效。

本讲义把这段代码的 7 页逐页拆解后,在文末"代码精读"专卡里再按"数据流 → 参数量 → 训练配置 → 输出"四步做一次完整 walkthrough,并给出三个"modify code"练手题。

题目 · Review 关联
  • Course Review 没有把 "Autoencoder code" 单列为考点,但 p16 的参数计算、p17 的 fit(X_train, X_train) 是最可能被考的两个代码细节。
  • Unit 5 的 MNIST 加载((X_train, y_train), (X_test, y_test) = mnist.load_data())在这里被改造成"只要训练集、只要特定数字"的版本——对比一下能看出"生成任务不需要测试集"的原因:没有标签,无法算准确率。
必要扩展
  • 为什么生成模型不用测试集?因为评估生成模型没有"正确答案"——没有标签,算不了 accuracy;重建误差在训练集和测试集上的差异也不是重点(自编码器主要担心过拟合,但本讲用 100 轮、11,693 张图,训练误差仍有意义)。严格的评估会用 FID 这类分布距离指标,本讲不涉及。
易错点 · 理解提示分节页不考,但注意 p14 的函数名是 load_and_prep_mnist(下划线连接 prep),考试写代码时别拼成 load_and_prepare。
p.14工具代码:导入与加载 MNIST代码数据
Utility code – imports and loading dataset
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.datasets import mnist

def load_and_prep_mnist(digits="all", ratio=1.0):
    keras.utils.set_random_seed(42)
    (X_train, y_train), _ = mnist.load_data()
    if digits != "all":
        digits = [int(d) for d in digits]
        mask = np.isin(y_train, digits)
        X_train = X_train[mask]
    if ratio < 1:
        sz_train = int(len(X_train) * ratio)
        X_train = X_train[:sz_train]
    X_train = X_train.astype(float) / 255
    X_train = X_train.reshape(-1, 28, 28, 1)
    return X_train
核心概念工具函数 load_and_prep_mnist(digits, ratio):加载 MNIST 训练集,可按数字筛选("48" → 只留 4 和 8)、按比例截取,然后 /255 归一化、reshape 成 28×28×1。只返回图像,不返回标签——因为生成任务不需要标签。
详细讲解

逐行读:

  • keras.utils.set_random_seed(42):一次性设置 Python random、NumPy、TensorFlow 三个随机源——比 Unit 7 里单独调 np.random.seed 更全面。放在函数内部意味着每次调用 load_and_prep_mnist 都会重置随机种子,保证后续 np.random.normal(p30)等的可复现性。
  • (X_train, y_train), _ = mnist.load_data():Unit 5 里是接收四个返回值,这里用 _ 丢弃测试集——理由见 p13 扩展。
  • digits = [int(d) for d in digits]:把字符串 "48" 拆成字符再转整数 → [4, 8]。这是个巧妙的小技巧:调用时写 "48" 比 [4, 8] 简短。注意若写成 "4" 也正常(→ [4])。
  • mask = np.isin(y_train, digits):返回一个布尔数组,y_train[i] 在 [4, 8] 里则为 True。MNIST 训练集 60,000 张里 4 有 5,842 张、8 有 5,851 张,共 11,693 张。
  • if ratio < 1: ... X_train[:sz_train]:按比例截取前 sz_train 张——用于快速实验(如 ratio=0.1 只要 1,169 张)。
  • X_train.astype(float) / 255:把 uint8(0–255)转成 float64 再除以 255 → 范围 [0, 1]。这和 Unit 4–11 的预处理完全一致。注意必须先转 float 再除——若直接 X_train / 255,NumPy 会自动升级类型,但写明确更安全。
  • X_train.reshape(-1, 28, 28, 1):从 (N, 28, 28) 变成 (N, 28, 28, 1)——加一个通道维,Keras 的 Conv2D 要求 4 维输入 (batch, H, W, C)。-1 表示"这一维让 NumPy 自己算"。

函数签名的设计:digits="all", ratio=1.0 是默认参数——不传参数就得到完整的 60,000 张(p15 画样本时用);传 "48" 就只得到两类(p17 训练自编码器、p34 训练 GAN、p48 训练 WGAN 都用这个)。三个模型都用同样的 11,693 张 4 和 8——这是公平比较的前提。

和 Unit 5 加载代码的三个区别:① 不要测试集;② 多了数字筛选和比例截取;③ 没有把标签转成 one-hot(因为不用标签)。

题目 · Review 关联
  • 可能的简答题:"What does load_and_prep_mnist("48") return?"——答:A NumPy array of shape (11693, 28, 28, 1) with values in [0, 1], containing only the training images of digits 4 and 8.
  • "Why is there no test set?"——生成任务无标签、无 accuracy 可算;评估靠人眼观察样本和损失曲线(p35–36、p49–50)。
  • "What is the purpose of reshape(-1, 28, 28, 1)?"——加通道维以兼容 Conv2D;对自编码器(全连接)而言 Flatten 层会先把它拉平,所以这一步对 AE 不是必需的,但对 GAN 的卷积层是必需的。
必要扩展
  • np.isin 的等价写法:(y_train == 4) | (y_train == 8)。数字个数(4 → 5,842;8 → 5,851)是 MNIST 的固定统计量,记住 "4 和 8 共 11,693" 对后面算批次数有用。
  • keras.utils.set_random_seed 是 TF 2.7+ 的 API;老代码可能看到 np.random.seed(42); tf.random.set_seed(42) 两行——功能等价。
  • 为什么选 4 和 8:它们的形状差异大(4 有直线和角、8 有两个闭合圈),生成结果容易辨认——p35 GAN 样本 "8 9 8 4 9 4 …" 和 p49 WGAN 样本 "4 4 8 8 …" 就是靠这个差异看出来的。
易错点 · 理解提示① ratio 只在 < 1 时生效——传 ratio=2.0 不会报错,但也不会复制数据。② 归一化是 /255 不是 /256——范围是 [0, 1] 而不是 [0, 0.996]。③ digits 参数是字符串,如果传 [4, 8](列表),int(d) for d in digits 仍然能工作(对列表元素直接 int),但语义上设计为字符串。
p.15工具代码:绘制样本 plot_samples代码
Utility code – plotting samples
import matplotlib.pyplot as plt

def plot_samples(samples):
    plt.figure(figsize=(15, 3))
    n = len(samples)
    for i in range(n):
        plt.subplot(1, n, (i+1))
        plt.imshow(samples[i].reshape(28, 28), cmap="gray_r")
        plt.axis("off")
    plt.show()

X_train = load_and_prep_mnist()
plot_samples(X_train[:10])
核心概念plot_samples(samples):把一组 28×28 图像并排画在一行(15×3 英寸),用 反向灰度 gray_r(白底黑字),关掉坐标轴。调用 load_and_prep_mnist() 不传参 → 全部 60,000 张,画前 10 张。
详细讲解

逐行读:

  • plt.figure(figsize=(15, 3)):新建画布,宽 15 英寸、高 3 英寸——横向长条,适合并排放 10 张 28×28 的小图。
  • n = len(samples):样本数(第一维),后面 subplot 用。
  • plt.subplot(1, n, i+1):把画布分成 1 行 n 列,选第 i+1 个格子。注意 subplot 的编号从 1 开始,所以 i+1。
  • samples[i].reshape(28, 28):数据形状是 (n, 28, 28, 1),imshow 需要二维(灰度)或三维 RGB(最后一维是 3),所以要 squeeze 掉通道维。
  • cmap="gray_r":reverse gray——0 白、1 黑。MNIST 原图是白底黑字,像素值越大越黑,所以用反向灰度。如果用普通 "gray",就会显示成黑底白字(像底片)。
  • plt.axis("off"):关掉坐标轴和刻度——小图不需要坐标。

这个函数在后面被调用的地方:p18 画输入和重建(调两次,上下对照);p19 画随机生成的 10 张;p33 update_history 里每 10 轮画一次生成样本(GAN);p36 和 p50 画最终样本。它是本讲所有"看结果"的唯一入口——记住它的画法(一行 n 张、白底黑字),后面看 p35、p49 的训练历史截图就不会困惑。

最后两行:X_train = load_and_prep_mnist() 不传参 → 60,000 张全部数字;plot_samples(X_train[:10]) 画前 10 张。这两行是"工具代码的演示",证明加载和画图都正常——和 p17 的训练无关,p17 会重新调 load_and_prep_mnist("48")。

注意:讲义 p15 的截图里显示 10 张数字(5 0 4 1 9 2 1 3 1 4——MNIST 训练集的前 10 张,这是固定的)。Unit 5 的 tutorial 里也见过这 10 张。

题目 · Review 关联
  • 可能的"modify code"题:"Modify plot_samples to show samples in a 2×5 grid"——把 plt.subplot(1, n, i+1) 改成 plt.subplot(2, 5, i+1),figsize 改成 (15, 6)。
  • "What does cmap="gray_r" do?"——Reverse gray colormap: 0 → white, 1 → black; it matches MNIST's white-background-black-digit appearance.
  • 为什么 reshape(28, 28) 而不是 reshape(28, 28, 1):imshow 对二维数组按灰度显示,对 (28,28,1) 会报错或显示异常(matplotlib 不接受单通道的三维数组作为灰度)。
必要扩展
  • matplotlib 的 subplot 是 1-based——这是它和 Python 列表索引(0-based)最容易混的地方。另一种现代写法 plt.subplots(1, n) 返回 (fig, axes) 数组,然后 axes[i].imshow(...),更符合 Python 习惯。
  • gray_r 的 "r" 是 reverse 的缩写;类似的还有 viridis(默认彩色)、hot、RdBu——生成模型的可视化常用灰度,因为 MNIST 是灰度图。
  • p33 的 update_history 在训练过程中每 10 轮调一次 plot_samples——所以训练时会不断弹出 10 张小图。讲义 p35 的截图就是这些图的拼接。
易错点 · 理解提示① subplot 编号从 1 开始(不是 0)。② 不 reshape 掉通道维会出错——这是 GAN 生成器输出 (n, 28, 28, 1) 后画图时必须做的。③ plt.show() 在 Jupyter 里可以省略(cell 末尾自动显示),但在普通脚本里必须有。
p.16自编码器:创建编码器与解码器(SZ_LATENT_AE=40)★Review代码·参数参数
Autoencoder – creating encoder and decoder
SZ_LATENT_AE = 40

encoder = keras.Sequential([
    layers.Flatten(),
    layers.Dense(512, activation="relu"),
    layers.Dense(256, activation="relu"),
    layers.Dense(SZ_LATENT_AE, activation="sigmoid")
])

decoder = keras.Sequential([
    layers.Dense(256, activation="relu"),
    layers.Dense(512, activation="relu"),
    layers.Dense(28*28, activation="sigmoid"),
    layers.Reshape(target_shape=(28, 28, 1)),
])
核心概念潜向量维度 SZ_LATENT_AE = 40。编码器:Flatten → Dense(512, relu) → Dense(256, relu) → Dense(40, sigmoid)。解码器:Dense(256, relu) → Dense(512, relu) → Dense(784, sigmoid) → Reshape(28,28,1)。两个独立的 Sequential,后面 p17 用 Sequential([encoder, decoder]) 串起来。总参数 1,087,800,压缩比 784/40 = 19.6。
详细讲解

编码器的四层:

  • Flatten():把 (28, 28, 1) 拉平成 784 维。无参数。
  • Dense(512, relu):784 → 512。参数 = 784×512 + 512 = 401,920。
  • Dense(256, relu):512 → 256。参数 = 512×256 + 256 = 131,328。
  • Dense(40, sigmoid):256 → 40。参数 = 256×40 + 40 = 10,280。用 sigmoid 是为了把潜向量限制在 (0,1)——p11 讲过原因,和 p19 的均匀噪声采样匹配。

解码器的四层:

  • Dense(256, relu):40 → 256。参数 = 40×256 + 256 = 10,496。
  • Dense(512, relu):256 → 512。参数 = 256×512 + 512 = 131,584。
  • Dense(784, sigmoid):512 → 784。参数 = 512×784 + 784 = 402,192。sigmoid 输出 (0,1),匹配归一化后的像素。
  • Reshape((28, 28, 1)):784 → (28, 28, 1)。无参数。必须 reshape 回图像形状,这样 fit(X_train, X_train) 时输出和目标的形状一致(都是 (n, 28, 28, 1))。

参数汇总:

层形状变化参数计算参数量占比
enc Flatten(28,28,1) → 784—0—
enc Dense 512 relu784 → 512784×512 + 512401,92036.9%
enc Dense 256 relu512 → 256512×256 + 256131,32812.1%
enc Dense 40 sigmoid256 → 40256×40 + 4010,2800.9%
编码器小计784 → 40—543,52849.97%
dec Dense 256 relu40 → 25640×256 + 25610,4961.0%
dec Dense 512 relu256 → 512256×512 + 512131,58412.1%
dec Dense 784 sigmoid512 → 784512×784 + 784402,19237.0%
dec Reshape784 → (28,28,1)—0—
解码器小计40 → 784—544,27250.03%
总计784 → 40 → 784—1,087,800100%

两个观察:① 编码器和解码器参数几乎相等(543,528 vs 544,272)——因为结构镜像对称,只差在输入/输出维度互换。② 参数集中在两端(第一层 36.9% + 最后一层 37.0% = 73.9%),中间的瓶颈层只有 0.9%——"沙漏"形状在参数量上也成立。

Optimizer = 2×Trainable + 2(全课程通用公式,Unit 8 总结):Adam 为每个参数维护 m 和 v 两个滑动平均,再加上迭代计数 t 和它的幂 epsilon(Keras 的 iterations 两个变量)——本讲 Adam 优化器参数 = 2×1,087,800 + 2 = 2,175,602。

为什么用两个独立的 Sequential 而不是一个:因为 p19 要单独调用 decoder.predict(X)——只有把解码器建成独立模型,才能跳过编码器直接用它生成。这是"用解码器生成"(p12)在代码上的前提。

题目 · Review 关联
  • Unit 4 的 Dense 参数公式 (n_in+1)×n_out 在本页用了六次——期末考若出"Calculate the number of trainable parameters of the autoencoder",按上表逐层算、最后相加 = 1,087,800。
  • Review #2 若考"Determine the size of the latent vector"——从代码读 SZ_LATENT_AE = 40,或从 Dense(SZ_LATENT_AE, ...) 推断。
  • 可能的简答题:"Why does the last layer of the decoder use sigmoid?"——Because pixel values are normalized to [0, 1] (p14), and sigmoid outputs (0, 1); MSE loss then compares two same-range tensors.
  • "Why Flatten() in the encoder but Reshape in the decoder?"——Flatten converts the image into a vector for Dense layers; Reshape converts the output vector back into an image so the output shape matches the input (target) shape.
必要扩展
  • 潜向量维度 40 的选择:太小(如 2)→ 重建模糊、只能学到最粗的结构;太大(如 200)→ 网络可能学成近似恒等映射。40 是个经验值,MNIST 上常见 32–128。
  • 如果把 Dense 换成 Conv2D(卷积自编码器):编码器用 Conv2D + MaxPool,解码器用 Conv2D + UpSampling——这正是 p28 GAN 生成器的结构。可以预见:GAN 生成器 = 卷积自编码器的解码器。
  • Keras 的 Sequential([encoder, decoder]) 允许嵌套 Sequential——p17 就这么用。嵌套后 autoencoder.layers 是 [encoder, decoder] 两个"层",每个"层"内部又有自己的 layers。
  • 潜层用 sigmoid 的代价:sigmoid 有饱和区,潜向量容易被推到 0 或 1 附近(梯度小)。VAE 通常改用线性输出 + 采样;普通 AE 这样做问题不大,因为训练目标是重建而不是采样。
易错点 · 理解提示① 参数公式是 (输入+1)×输出,bias 别忘了——Dense(784→512) 是 401,920 而不是 401,408。② 编码器和解码器不共享权重——总参数是两者之和,不是两者之一。③ Dense(28*28, sigmoid) 的输出是 784 维向量,Reshape 之后才是 (28,28,1)——如果忘了 Reshape,fit 时 Keras 会因为输出 (n,784) 和目标 (n,28,28,1) 形状不匹配而报错(或者自动 reshape,取决于版本)。④ "压缩比 19.6" 是维度之比,不是参数量之比,也不是文件大小之比。
p.17自编码器:创建与训练(数字 4 和 8,mse,100 轮)★Review代码·训练
Autoencoder – creating and training autoencoder
X_train = load_and_prep_mnist("48")
autoencoder = keras.Sequential([encoder, decoder])
autoencoder.compile(loss="mse", optimizer="adam")
history = autoencoder.fit(
    X_train, X_train, epochs=100, batch_size=256, verbose=0)

import pandas as pd
df = pd.DataFrame(history.history)
df.index = df.index + 1
df.plot(y="loss", grid=True);
核心概念四步搭好自编码器:① 加载 4 和 8(11,693 张);② Sequential([encoder, decoder]) 把两个模型串起来;③ 编译:损失 mse、优化器 adam;④ 训练:fit(X_train, X_train)——输入和目标都是同一批图,100 轮、batch 256、不打印进度。最后用 pandas 画出 loss 曲线。
详细讲解

第 1 行:load_and_prep_mnist("48") → 形状 (11693, 28, 28, 1)。只用 4 和 8——理由见 p14 扩展:形状差异大、容易看出重建好坏。注意这里重新加载,不是用 p15 的 X_train(那是全部 60,000 张)。

第 2 行:keras.Sequential([encoder, decoder])——Keras 允许把整个模型当作一层塞进另一个 Sequential。数据流:输入 (n,28,28,1) → encoder → (n,40) → decoder → (n,28,28,1)。这样 autoencoder.summary() 会显示两层:"encoder (Sequential)" 和 "decoder (Sequential)",各自可以展开。

第 3 行:compile(loss="mse", optimizer="adam")。为什么用 MSE?因为这是回归问题——预测 784 个连续值(像素),和 Unit 4 的房价回归同类型。MSE = (1/n)Σ(x − x̂)²,x 和 x̂ 都是 [0,1] 的值。为什么不用 binary_crossentropy?也可以——有些教程用 BCE(因为像素在 [0,1]、输出是 sigmoid),但 BCE 对"接近 0 或 1 的像素"惩罚更重,MSE 更直接地衡量"像素差多少"。讲义选 MSE,考场照写。

第 4–5 行:fit(X_train, X_train, epochs=100, batch_size=256, verbose=0)。第一个参数是输入,第二个是目标——两者相同,这是自编码器的标志性写法。100 轮 × 每轮 ⌈11693/256⌉ = 46 步(最后一批 11693 − 45×256 = 173 张)→ 总共 4,600 步。verbose=0 静默训练(Unit 7 的 Lab 也这么用)。

第 7–10 行:把 history.history(字典 {"loss": [100 个数]})转成 DataFrame,df.index = df.index + 1 让横轴从 1 开始(第 1 轮到第 100 轮,而不是 0–99),df.plot(y="loss", grid=True) 画 loss 曲线带网格。这是 Unit 6 画训练曲线的同款方法。

损失量级:初始 loss 大约 0.1 左右(随机权重下,输出 ≈ 0.5,x 多数是 0,MSE ≈ 0.25×(非零像素比例));训练后降到 0.01–0.02——讲义 p17 的截图显示曲线从约 0.06 快速下降,在 10 轮内降到 0.02 以下,之后缓慢收敛。

题目 · Review 关联
  • 最可能考的代码填空:autoencoder.fit(____, ____)——答案是 X_train, X_train。"Why are the two arguments the same?"——Because an autoencoder is trained to reconstruct its input; the target is the input itself.
  • "Why loss="mse"?"——Reconstruction is a regression over 784 pixel values; MSE measures the squared difference between input and reconstruction.
  • "How many training steps per epoch?"——⌈11693/256⌉ = 46(45 批 256 张 + 1 批 173 张)。
  • "What does Sequential([encoder, decoder]) do?"——It stacks the two sub-models so data flows through the encoder first and then the decoder; the composite model's input shape is (28,28,1) and output shape is (28,28,1).
  • Unit 6 的 history = model.fit(...) → history.history["loss"] 在这里再次使用;df.plot 是 pandas 封装的 matplotlib 一行画图法。
必要扩展
  • 训练时间:11,693 张、100 轮、4,600 步、1.09M 参数——CPU 上大约 1–2 分钟,GPU 上十几秒。相比 GAN(p35 显示 7.7 分钟)快得多,因为自编码器每步只做一次前向+反向,而 GAN 每批要训练 D 两次 + G 一次。
  • 没有验证集:fit 没传 validation_split 或 validation_data——因为生成任务没有"标签准确率"可验证,重建误差在训练集上就够看。如果想监控过拟合,可以切 10% 做验证。
  • 100 轮是否过多?对 11,693 张、1.09M 参数的网络,100 轮有过拟合风险——但自编码器的"过拟合"表现为"记住训练样本",而重建误差仍然低,视觉上仍然是好的。真正的坏处是 p19 随机采样时,潜空间未覆盖区域更大。
  • 对比 Unit 7 的 Lab:那里用 EarlyStopping 和 validation_split;这里没有——生成模型的训练更"盲目",靠看样本判断。
易错点 · 理解提示① fit(X_train, X_train) 不是笔误——两个参数相同是自编码器的本质。② 损失是 mse 不是 categorical/binary_crossentropy——这是回归不是分类。③ 每轮 46 步(不是 45、不是 47):⌈11693/256⌉ = 46,因为 45×256 = 11,520 < 11,693。④ verbose=0 只是不打印进度条,不影响训练。
p.18自编码器:对比输入与输出结果
Autoencoder – comparing autoencoder inputs and outputs
plot_samples(X_train[:10])
plot_samples(autoencoder.predict(X_train[:10], verbose=0))
输入 重建 上:X_train[:10](4 与 8 交替) 下:autoencoder.predict 的重建——笔画略粗、略模糊,但类别全部正确
图 12.P18 讲义 p18 结果示意:上行输入 10 张(4、8 交替),下行重建 10 张。原图为 matplotlib 输出,此处为矢量重绘。
核心概念两行代码对比:第一行画输入 X_train[:10],第二行画重建 autoencoder.predict(X_train[:10])。预期结果:重建图类别全部正确,但笔画略粗、略模糊——这是 40 维瓶颈有损压缩的代价。
详细讲解

为什么要看这个:这是自编码器的"考试"——没有标签、没有 accuracy,唯一能判断它学得好不好的方法就是对比输入和输出。如果重建得像,说明编码器抓到了关键特征、解码器能还原;如果重建的是一团噪声,说明训练失败。

读图的方法:上排 10 张是输入(MNIST 中 4 和 8 的前 10 张,交替出现),下排是对应的重建。逐张对照:形状一致(4 还是 4、8 还是 8),但下排的笔画稍粗(sigmoid 输出很难精确到 0,边缘有灰度)、稍模糊(40 维放不下所有细节)。这正是 p10 说的"有损压缩"。

为什么是模糊而不是错:MSE 损失对"每个像素差一点"和"某个像素差很多"的惩罚是平方关系——网络倾向于输出平均的、保守的图像(模糊但各处差得不多),而不是冒险画一个清晰但可能画错的形状。这是 MSE 回归的通病,也是 GAN 要解决的问题(GAN 用判别器代替 MSE,能生成更锐利的图)。

用训练集的图做对比公平吗:严格说,这是"训练集上的重建",模型见过这些图。但对自编码器而言,训练集重建好是底线——连见过的图都重建不好,没见过的更不行。如果想看泛化,可以拿测试集的 4 和 8(但 load_and_prep_mnist 丢弃了测试集,需要改函数)。

代码细节:predict(X, verbose=0)——Unit 7 用过,关掉进度条。输出形状 (10, 28, 28, 1),和输入一样,所以能直接喂给 plot_samples(它内部会 reshape 成 (28,28))。

题目 · Review 关联
  • "How do you evaluate an autoencoder?"——Compare the reconstructions with the inputs visually (p18), and monitor the reconstruction loss (p17). There is no accuracy because there are no labels.
  • "Why are the reconstructed images blurry?"——The 40-dimensional bottleneck is a lossy compression (ratio 19.6:1); MSE loss also favours averaged, conservative outputs.
  • 可能的"modify code"题:"Show the reconstructions of the first 20 images"——把两处 [:10] 改成 [:20];plot_samples 会自动按 n 排成一行。
必要扩展
  • 量化重建质量:除了看图,可以算 autoencoder.evaluate(X_train, X_train) 得到整体 MSE,或对单张图算 MSE 找出"重建最差的样本"——后者就是 p12 异常检测的原理。
  • 和 GAN 样本的对比:p36 的 GAN 样本更锐利但有噪声点、且可能出现"4 和 8 的混合体";p18 的 AE 重建模糊但形状忠实。两种"不完美"来自不同的训练目标——MSE vs 对抗。
  • 潜向量可视化:把 encoder.predict(X_train) 得到的 40 维向量用 t-SNE 降到 2 维画散点,会看到 4 和 8 分成两簇——这是验证"潜空间学到类别结构"的经典方法。
易错点 · 理解提示① 这里调的是 autoencoder.predict(整个网络),p19 调的是 decoder.predict(只有解码器)——前者输入图像,后者输入噪声向量,别混。② 重建模糊是正常的,不代表训练失败;若重建完全不像(一团噪声),才是失败。③ 两行 plot_samples 各弹出一个图窗(不是一个图窗的上下两行)——讲义截图里是上下排列,但实际是两个独立的 figure。
p.19自编码器:用随机潜向量生成样本★Review代码
Autoencoder – generating samples
X = np.random.random((10, SZ_LATENT_AE))
samples = decoder.predict(X, verbose=0)
plot_samples(samples)
核心概念三行生成:① np.random.random((10, 40)) 生成 10 个 40 维均匀分布噪声向量(每个分量 ∈ [0,1));② decoder.predict(X)——只用解码器,跳过编码器;③ 画出来。这是 p11 "feed a latent vector of random numbers to the decoder" 的代码实现,也是 p12 "image generation using the decoder" 的实例。
详细讲解

为什么用 np.random.random 而不是 np.random.normal:np.random.random(size) 采样 U[0, 1) 均匀分布——正好覆盖 p16 编码器最后一层 sigmoid 的输出范围 (0,1)。这样采到的点大概率落在训练数据潜向量所在的区域,解码出来才像数字。如果用正态分布 N(0,1),会有约 1/3 的分量是负数、约 1/6 超过 1——落在 sigmoid 从未输出过的区域,解码结果会奇怪。注意对比:p30 的 GAN 用 np.random.normal(0, 1, (n, 40))——因为 GAN 生成器的第一层是 Dense(7*7, LeakyReLU),没有 sigmoid 限制输入范围,正态分布更合适。

为什么用 decoder 而不是 autoencoder:autoencoder 的输入是 (n,28,28,1) 的图,要先过编码器;而我们要"无中生有",直接给解码器一个潜向量。decoder 是 p16 建的独立 Sequential,输入形状 (n,40)——这正是 p16 把编码器和解码器分开建的原因。

输出是什么样:10 张 28×28 的图,大概率是4 或 8 的变体——因为解码器只见过这两类。有些会很像(采到的点靠近训练簇的中心),有些会"四不像"(4 和 8 的混合、或笔画断裂)——因为普通自编码器的潜空间不连续,均匀采到的点可能落在训练数据没覆盖的空洞里。讲义 p19 的截图显示 10 张里大多数可辨认为 4 或 8,有一两张模糊。

这就是"生成":这 10 张图不在训练集里——它们是从随机向量"画"出来的新样本。虽然质量不高(模糊、偶尔失败),但它满足 p5 的定义:无标签、学 Prob(features)、创造新内容。

和 GAN 生成的对比:GAN(p30 的 generate_samples)结构完全一样——采噪声 → generator.predict → 画图。区别在于生成器怎么训练:AE 解码器靠"重建误差"间接学,GAN 生成器靠"骗判别器"直接学。后者能生成更锐利的图(p36),但训练更不稳定(p26)。

题目 · Review 关联
  • Review #2 若考 "generate samples using an autoencoder"——三行照写:X = np.random.random((10, SZ_LATENT_AE)); samples = decoder.predict(X); plot_samples(samples)。要点:是 decoder.predict,不是 autoencoder。
  • "Why np.random.random (uniform) here but np.random.normal in the GAN?"——AE 潜层用 sigmoid 输出 (0,1),均匀分布匹配;GAN 生成器的输入无 sigmoid 约束,用 N(0,1)。
  • "What is the shape of X?"——(10, 40);"What is the shape of samples?"——(10, 28, 28, 1)。
  • Review #5(optional)的 "GAN code" 里 generate_sample_inputs / generate_samples(p30)是本页的 GAN 版——两段代码对照记忆。
必要扩展
  • 普通自编码器的潜空间"空洞"问题:训练只覆盖了潜空间中与训练样本对应的一小片区域,随机采样的点大多落在空洞里——这是 p19 结果时好时坏的根本原因。VAE 加 KL 散度惩罚,强迫潜向量服从 N(0,I),填平空洞;GAN 则完全不用编码器,让生成器自己学"从噪声到样本"的映射。
  • 更稳妥的采样方法:先 encoder.predict(X_train) 得到所有训练样本的潜向量,算每一维的均值和标准差,再从 N(μ, σ) 采样——这样采到的点更可能在数据流形上。
  • "潜空间插值"练习:取两张训练图的潜向量 z₁、z₂,画 z₁ + t(z₂ − z₁) 在 t = 0, 0.25, 0.5, 0.75, 1 时的解码结果——如果 z₁ 是 4、z₂ 是 8,中间会看到"4 逐渐变成 8"。
易错点 · 理解提示① np.random.random((10, 40)) 的参数是 shape 元组(要加括号),不是 random(10, 40)。② 范围是 [0, 1),和 GAN 的 N(0,1) 不同——考试写代码时别混。③ 用 decoder 不是 autoencoder——写错了会因输入形状不匹配报错。④ 生成的图"像 4 或 8"是因为训练集只有 4 和 8;换 load_and_prep_mnist() 全部数字训练,就能生成 0–9。
p.20分节页:Generative adversarial networks分节
Generative adversarial networks
核心概念进入第三个模型:生成对抗网络(GAN)——用两个网络对抗来学生成:生成器造假,判别器打假。
详细讲解

自编码器的生成方式(p19)有个根本缺陷:没有"好不好"的标准——解码器只学会了重建,随机采样的结果时好时坏,网络自己不知道哪些是好的。GAN 的思路是:再训练一个网络来判断生成的样本好不好(判别器),然后让生成器朝着骗过判别器的方向学习。判别器越好,生成器就被逼得越像真的。

原理部分 7 页(p21–26):定义(p21–22)、分别训练 D 和 G(p23–24)、收敛条件(p25)、训练困难(p26)。这 7 页全部在 Course Review 的 #3、#4 考点里——是本讲最该背的部分。

读这一段时,把 p23 和 p24 并排看:它们是同一个循环的两步——训练 D 时冻结 G、训练 G 时冻结 D。p25 回答"什么时候停",p26 回答"为什么停不下来"。

题目 · Review 关联
  • Review p10 #3 "GANs"——定义(p21–22)+ 训练方法(p23–24)+ 收敛(p25)。
  • Review p10 #4 "Difficulties in training GANs"——p26 五条,必背。
  • Unit 5 的二分类(Dense(1, sigmoid) + binary_crossentropy)是 p23 训练判别器的基础——GAN 的 D 就是 Unit 10 情感分类器换了输入。
必要扩展
  • GAN 是 2014 年 Goodfellow 在酒吧讨论后一夜写出的想法(他在采访里说的);2014–2020 年是图像生成的主流,之后被扩散模型部分取代,但"对抗训练"的思想影响深远(如数据增强、域适应)。
易错点 · 理解提示GAN 原理 7 页里有 3 页(p21、p25、p26)内容密度很高,是简答题的富矿;p22、p23、p24 各只有两三句话,但每一句都可能出"explain why"题。
p.21GAN 的定义(生成器 vs 判别器,Goodfellow 2014)★Review定义
Generative adversarial networks Goodfellow et al, 2014, https://arxiv.org/abs/1406.2661v1  A generative adversarial network, or GAN, is a composite model containing an adversarial pair of two models  A generator generates data instances (also called examples, samples, observations) that appear as if they come from the training dataset  A discriminator predicts whether an instance is real or fake, i.e., whether it comes from the training dataset or is generated by the generator
GAN:生成器造假 vs 判别器打假 噪声 zN(0,1)40 Generator G造假:G(z) ≈ x fake generated Discriminator D打假:D(x) ∈ (0,1) Real (1) or Fake (0)?二分类 real (from dataset) G 的目标:让 D 把 fake 判成 real 无标签
图 12.P21 GAN 的对抗结构(讲义无原图,本图按 p21 文字绘制):生成器把噪声变成样本,判别器同时看真样本和假样本、输出"真"的概率;生成器的训练目标是让判别器把假样本判成真。
核心概念GAN 是一个复合模型(composite model),包含一对对抗的两个模型:生成器(generator)生成看起来像来自训练集的数据实例;判别器(discriminator)预测一个实例是真是假——即它来自训练集还是由生成器生成。四个同义词:data instances = examples = samples = observations。
详细讲解

"Composite model":GAN 不是一个网络,是两个网络装在一起——p29 的 keras.Sequential([generator, discriminator]) 就是这个"复合"的代码实现。这和自编码器(也是两个网络复合)结构上一样,但训练方式完全不同:AE 的两半合作(共同降低重建误差),GAN 的两半对抗(G 想赢、D 也想赢)。

生成器的任务:输入一个随机向量 z(本讲 40 维),输出一张图 G(z)。它从不见真实数据——训练时它的梯度完全来自判别器的输出(p24)。它只能通过"判别器说我的输出像不像真的"来间接学习"真数据长什么样"。这就像一个造假者从没见过真钞,只靠"鉴定师的反馈"来改进技术。

判别器的任务:输入一张图 x,输出一个概率 D(x) ∈ (0,1)——"这是真的的概率"。它既看真样本也看假样本:真样本来自训练集(标签 1),假样本来自生成器(标签 0)。这是一个标准的二分类问题——p23 会说"a usual supervised learning problem of image classification",只不过"标签"是自动生成的(来源决定标签),不需要人工标注。

"对抗"的含义:两人玩一个零和游戏——G 的收益 = D 的损失。原始论文的数学目标:minG maxD Ex~pdata[log D(x)] + Ez~pz[log(1 − D(G(z)))]。D 要最大化(真样本 log D(x) 大、假样本 log(1−D(G(z))) 大),G 要最小化这个值(让 D(G(z)) 大,即 log(1−D(G(z))) 小)。这个公式本讲义没要求,但它是 p23–24 两步训练的数学来源。

为什么这样能学生成:直觉上,鉴定师越厉害,造假者就越得把真钞的每一个细节都学会。当 G 能骗过一个"完美"的 D 时,D 只能输出 0.5(猜)——此时 G(z) 的分布已经和真实数据无法区分,即 G 学会了 pdata。这就是 p22 说的"If a generator can fool a smart discriminator, the generated instances are as good as real ones!"

和自编码器的对比:AE 的解码器 ≈ GAN 的生成器(都是"向量 → 图"),但 AE 没有判别器——解码器靠 MSE 学习,GAN 生成器靠 D 学习。D 比 mse "聪明":mse 只看像素差,D 看的是"像不像真的"(结构、纹理、整体),所以 GAN 能生成更锐利的图(p36 vs p18)。

题目 · Review 关联
  • Review #3 定义题标准答案:"A GAN is a composite model containing an adversarial pair of two models: a generator that generates data instances appearing as if they come from the training dataset, and a discriminator that predicts whether an instance is real or fake."
  • "Does the generator ever see real data during training?"——No. It learns only through the discriminator's feedback (p24).
  • "What kind of problem does the discriminator solve?"——Binary classification: real (1) vs fake (0) (p23).
  • "Compare a GAN with an autoencoder"——Both are composite models; AE = encoder + decoder trained cooperatively to reconstruct; GAN = generator + discriminator trained adversarially. AE's decoder ≈ GAN's generator.
必要扩展
  • Goodfellow 2014 的原始论文只有 4 页 DCGAN 的前身——用全连接网络生成 MNIST。本讲 p28 的生成器已经是 DCGAN(卷积),p22 会讲这个演变。
  • "Adversarial" 一词在机器学习里有三个不同的意思:① GAN 的对抗训练(本讲);② 对抗样本(adversarial examples,Unit 6 的鲁棒性);③ 对抗训练做正则化(Goodfellow 2015)。三者都是"一个网络生成让另一个网络为难的东西",但目标不同。
  • GAN 的博弈论解释:D 和 G 达到纳什均衡时,G 的分布等于数据分布、D 处处输出 0.5。但实际训练是梯度下降,不一定能找到均衡——这是 p26 "non-convergence" 的理论根源。
易错点 · 理解提示① GAN 是两个模型不是一个——"composite model containing an adversarial pair"。② 生成器不看真数据,判别器既看真也看假——别答反。③ "Data instances" 的三个同义词(examples / samples / observations)在考题里会互换使用,指的都是"一张图"。
p.22GAN 续(骗过聪明判别器 / DCGAN)★Review定义
Generative adversarial networks (cont.)  If a generator can fool a smart discriminator, the generated instances are as good as real ones!  Today a GAN essentially means a DCGAN, deep convolutional GAN ➢ The original GAN paper uses DNNs, but nowadays nearly all GANs use CNNs
核心概念两句核心:① 如果生成器能骗过聪明的判别器,生成的样本就和真的一样好——这是 GAN 的逻辑基础;② 今天的 GAN 基本上就是 DCGAN(深度卷积 GAN)——原始论文用全连接网络(DNN),但现在几乎所有 GAN 都用 CNN。
详细讲解

第一句的深意:"smart discriminator" 是关键。如果 D 很笨(比如只会判断"图像中间有没有黑色"),G 只需学会"中间涂黑"就能骗过它——生成的是黑块,不是数字。但如果 D 足够聪明(能看出笔画是否连续、形状是否像手写),G 就必须学会所有这些细节。"骗过聪明判别器"是一个可验证的标准——不像 AE 的 MSE 那样模糊,也不像人眼判断那样主观。

第二句的历史:Goodfellow 2014 的原始 GAN 用的是多层感知机(DNN,全连接)——生成器是 Dense 堆叠,判别器也是。2015 年 Radford 提出 DCGAN:把 CNN 的经验(卷积、BatchNorm、ReLU/LeakyReLU、去掉全连接层、用步长卷积代替池化)用到 GAN 上,效果大幅提升,训练更稳定。从那以后,"GAN" 默认指 DCGAN 结构。

本讲的 GAN 是 DCGAN:看 p28 的生成器——Dense → Reshape → UpSampling → Conv2D(64) → BN → UpSampling → Conv2D(64) → BN → Conv2D(1, sigmoid);p29 的判别器——Conv2D(64, strides=2) ×3 + Dropout → Dense(1)。全是 CNN 组件。所以本讲的 GAN 就是 DCGAN 的一个精简版(Radford 原版生成 64×64 彩色图,本讲生成 28×28 灰度图)。

DCGAN 的设计原则(Radford 2015,本讲代码体现了其中大部分):① 用 strided conv 替代池化(判别器);② 用 strided deconv / 上采样替代池化(生成器,本讲用 UpSampling2D);③ 去掉全连接隐藏层(本讲生成器保留了第一个 Dense,是为了把 40 维投到 7×7);④ 生成器除输出层用 tanh/ sigmoid 外都用 BN + ReLU/LeakyReLU;⑤ 判别器用 LeakyReLU。

和 Unit 9 的联系:DCGAN 的"用 CNN 做生成"和 Unit 9 的"用 CNN 做分类"是同一个卷积运算的两个方向——分类是"图 → 特征 → 标签"(下采样),生成是"噪声 → 特征 → 图"(上采样)。p28 的 UpSampling2D 是本讲新出现的层,相当于"反卷积"的简化版。

题目 · Review 关联
  • Review #3 若考 "What is a DCGAN?"——"A deep convolutional GAN: a GAN whose generator and discriminator are CNNs (convolutional layers, batch normalization, upsampling). Nearly all modern GANs are DCGANs."
  • "Why is fooling a smart discriminator a good training signal?"——Because a smart discriminator checks fine details; a generator that passes it must have learned the data distribution well.
  • "What does the original GAN paper use, DNN or CNN?"——DNNs (MLPs); CNNs came with DCGAN (Radford 2015).
  • Unit 8 的卷积参数公式((k·k·din+1)·n)在 p28–29 会大量使用。
必要扩展
  • Radford 2015 的 DCGAN 论文标题 "Unsupervised Representation Learning with Deep Convolutional Generative Adversarial Networks"——它的本意是用 GAN 做无监督特征学习(判别器的特征拿去做分类),生成只是副产品。但后来 DCGAN 的生成能力更受关注。
  • UpSampling2D vs Conv2DTranspose:本讲用 UpSampling2D(最近邻插值,把 7×7 变成 14×14,无参数)+ Conv2D;Radford 原版用 Conv2DTranspose(转置卷积,有参数、可学习上采样)。两者都能上采样,后者更常见但容易产生 checkerboard 伪影。
  • 本讲判别器用 Dropout(0.5)(p29)——Radford 的指南里判别器不用 BN 但用 Dropout 的变体很常见;Dropout 在这里的作用是防止 D 太强(p26 的 vanishing gradients)。
易错点 · 理解提示① DCGAN 是 GAN 的一种(用 CNN),不是另一种模型——"Today a GAN essentially means a DCGAN"。② "The original GAN paper uses DNNs"——这里的 DNN 指多层感知机(全连接),不是"深度神经网络"的泛称。③ 本讲生成器保留了一个 Dense(7×7) 层——这不算违反 DCGAN 原则,它只是把噪声向量投到空间网格上。
p.23训练判别器(真图 + 假图的二分类)★Review训练
Training the discriminator  The discriminator predicts if an image is real or fake ➢ A usual supervised learning problem of image classification  For training, use both fake images generated by the generator and real images from the training set
核心概念训练判别器 = 一个普通的监督二分类问题:真图标签 1、假图标签 0,损失 binary_crossentropy。训练数据一半来自生成器、一半来自训练集。假图的标签是自动生成的(来源决定),不需要人工标注。
详细讲解

为什么是"usual supervised learning":判别器的结构(p29)是 Conv2D ×3 → Flatten → Dense(1, sigmoid)——和 Unit 10 的 CNN 情感分类器、Unit 9 的猫狗分类器结构完全一样。训练方式也一样:compile(loss="binary_crossentropy") → train_on_batch(X, y)。唯一的区别是标签从哪来——猫狗分类器要人标"猫/狗",判别器的标签是"这张图来自训练集 → 1,来自生成器 → 0",自动可得。

训练数据的组成:p31 的代码 train_discriminator 里,X_real = X_train_batch(真图,y=1)、X_fake = generate_samples(generator, batch_size)(假图,y=0),各 batch_size 张,一一配对(真:假 = 1:1,类别平衡)。两次 train_on_batch 分别训练,然后 loss 取平均——效果等价于把真假混在一起训练。

训练时生成器在做什么:生成器只负责生成假图(generator.predict,前向传播),它的权重不更新——因为 discriminator.train_on_batch 只更新判别器的权重。这是 p24 "set the discriminator to be non-trainable" 的镜像:训练 D 时 G 不动,训练 G 时 D 不动。

判别器的损失:BCE = −[y log p + (1−y) log(1−p)]。对真图(y=1):loss = −log D(x),D(x)→1 时 loss→0;对假图(y=0):loss = −log(1−D(G(z))),D(G(z))→0 时 loss→0。D 的目标是最小化这两个——即真图判真、假图判假。

训练初期:生成器是随机的,输出是一片噪声(p35 ep10 的样本"噪点"),判别器很快学会"有笔画结构的是真、一片噪声的是假"——loss 迅速下降(p36 的 dsc_loss 从 0.42 降到 ep5 的 0.07)。此时 D 太强,G 的训练信号很弱——这是 p26 "vanishing gradients" 的来源,也是 GAN 训练初期最常见的问题。

题目 · Review 关联
  • Review #3 若考 "How is the discriminator trained?"——"As a supervised binary classifier: real images from the training set are labelled 1, fake images generated by the generator are labelled 0; loss is binary cross-entropy."
  • "Does the generator get updated when training the discriminator?"——No, only the discriminator's weights are updated; the generator only produces fake images.
  • "Why is the label 1 for real and 0 for fake?"——Convention: D(x) is the probability of being real; BCE then pushes D(x)→1 for real and →0 for fake.
  • Review #5(optional):y_real = np.ones(batch_size)、y_fake = np.zeros(batch_size)(p31)是本页的代码证据。
必要扩展
  • BCE 的数值感:D(x)=0.5 → loss = ln2 = 0.693;D(x)=0.9 对真图 → −log 0.9 = 0.106;D(x)=0.1 对真图 → −log 0.1 = 2.303。判别器越自信且正确,loss 越接近 0。
  • 类别平衡(真:假 = 1:1)很重要——如果真图远多于假图,D 会偏向"全判真",loss 低但没用。
  • 标签平滑(label smoothing,真图标 0.9 而非 1.0)是 GAN 训练的常见技巧,可以防止 D 过度自信——本讲没用,Salimans 2016 的论文提到。
  • 判别器训练得太好怎么办?p31 的代码每批只训练 D 一次(两次 train_on_batch,各半批)——限制了 D 的进步速度。更复杂的方法有:D 的学习率调低、D 加 Dropout(本讲有 0.5)、给 D 输入加噪声。
易错点 · 理解提示① 判别器的标签不是人标的——是"来源决定标签",所以 GAN 整体仍是无监督。② 训练 D 时G 不更新——G 只是"造假工厂",不是"学生"。③ 判别器是二分类(1 个输出 + sigmoid),不是多分类——别写成 softmax。
p.24训练生成器(冻结判别器 / 假图标真)★Review训练数值
Training the generator  The generator aims to fool the discriminator, i.e. to make the discriminator predict fake images as real ones  When training the generator ➢ Set the discriminator to be non-trainable; otherwise, the discriminator simply "learns to become foolish" ➢ Set the labels of fake images as "real", as the generator performs well if the discriminator predicts them as "real" with small losses
核心概念训练生成器的目标:骗过判别器——让 D 把假图判成真。两条关键操作:① 把判别器设为不可训练(trainable = False),否则 D 会"学会变笨"来配合 G;② 把假图的标签设为"真"(y=1),因为 G 表现好 ⇔ D 把假图判成真 ⇔ 此时损失小。
详细讲解

为什么冻结判别器:想象不冻结会怎样——我们用 gan.train_on_batch(X_fake, y=1) 训练复合模型,梯度会流向 G 和 D 两个网络。D 的"利益"是把假图判成假,但现在损失告诉它"把这些判成真"——D 会调整权重去配合这个错误的标签,即"learn to become foolish":D 变笨了,G 的 loss 变低了,但 G 实际上没有进步。训练结束后 D 已经废了,下一轮训练 D 又得重新学。冻结 D 后,梯度只流向 G,D 保持"聪明",G 的进步才是真实的。

为什么假图标"真":我们希望"G 生成的图让 D 觉得是真的",即 D(G(z)) → 1。用 BCE、标签 y=1,loss = −log D(G(z))——D(G(z)) 越接近 1,loss 越小。所以"假图标真"不是作弊,而是把"G 的目标"翻译成损失函数的标准做法:

D(G(z))G 的 loss = −log D(G(z))含义
0.014.605D 一眼看穿是假的——G 还很差
0.12.303D 很确定是假的
0.50.693D 猜——均衡点
0.90.105D 觉得很可能是真的——G 很好
1.00D 完全被骗

注意 G 的 loss 和 D 的 loss 的关系:同一个 D(G(z)) 值,G 的 loss 是 −log D(G(z)),D 对同一张假图的 loss 是 −log(1 − D(G(z)))。两者方向相反:D(G(z)) 越大,G 的 loss 越小、D 的 loss 越大。所以 p36 的两条曲线,gen_loss 下降时 dsc_loss 上升(或反过来)——它们不会同时下降(那是 AE 的特征)。

原始论文的另一个版本:Goodfellow 2014 用 −log(1 − D(G(z))) 作为 G 的损失。问题:当 D 很强时(D(G(z)) ≈ 0),这个函数的梯度 ≈ 0——G 学不动(饱和)。后来大家改成 −log D(G(z))("non-saturating" 版本),在 D 很强时梯度反而大。本讲用后者(标签 1 + BCE),p26 的 vanishing gradients 讲的是前者的问题。

代码实现(p31):train_generator(generator, gan, batch_size) → X = generate_sample_inputs(batch_size)(噪声,不是假图——假图由 gan 内部的 G 现场生成)、y = np.ones(batch_size)(标真)、gan.train_on_batch(X, y)。注意输入是噪声——因为复合模型 Sequential([G, D]) 的输入是 G 的输入。

题目 · Review 关联
  • Review #3 若考 "How is the generator trained?"——"The discriminator is set non-trainable; fake images are labelled as real (y=1); the composite GAN is trained with binary cross-entropy so that the generator learns to make D(G(z)) close to 1."
  • "Why must the discriminator be non-trainable when training the generator?"——Otherwise the discriminator would adjust its weights to accept fake images as real ("learn to become foolish"), so the generator's improvement would be illusory.
  • "Why label fake images as real?"——Because the generator's objective is to make D(G(z)) → 1; BCE with y=1 gives loss = −log D(G(z)), which is small exactly when the generator succeeds.
  • 数值题:"If D(G(z)) = 0.1, what is the generator's loss?"——−ln 0.1 = 2.30;"If D(G(z)) = 0.9?"——0.11。
必要扩展
  • Keras 里 model.trainable = False 的语义:设置后,该模型的所有层 trainable 变为 False,train_on_batch 时它们的权重不更新,但仍然参与前向传播(梯度照算,只是不应用)。这正是训练 G 时需要的——D 要给出 D(G(z)),但不能变。
  • 注意 p29 的 create_discriminator 在返回前就写了 model.trainable = False——然后 p31 的 train_discriminator 每次又设 trainable = True → 训练 → False。这意味着:单独训练 D 时要显式打开,训练 G 时用默认的关闭。讲义 p24 说"set non-trainable"是训练 G 的操作,但代码里是"默认关闭、训练 D 时临时打开"——同一个效果的两种实现顺序。
  • 把两张表(p23 D 的 BCE、p24 G 的 BCE)合起来看:D 的 loss 对真图 −log D(x)、对假图 −log(1−D(G(z)));G 的 loss 对假图 −log D(G(z))。三个公式、一个变量 D(·)——理解了这三个,GAN 的损失就全懂了。
易错点 · 理解提示① "假图标真"不是在训练 D 时用的——训练 D 时假图标 0(p23),训练 G 时假图标 1(p24)。同一张假图、两个标签,取决于训练谁。② 冻结的是 D 不是 G——训练 G 时当然 G 要更新。③ G 的 loss 低不代表生成的图好——如果 D 很弱(总是输出 1),G 的 loss 接近 0 但生成的可能是噪声——这就是 p26 "uninformative loss"。
p.25GAN 收敛(D 50% / G 100% / 模式崩溃)★Review收敛
GAN convergence  A GAN converges when the discriminator and generator reach equilibrium  Theoretically ➢ The generator has 100% accuracy, always fooling the discriminator — As measured when it is trained using the whole GAN ➢ The discriminator has 50% accuracy, i.e., guessing randomly — Maybe always predict "real" for both real and fake instances  Even when a GAN converges, there may be problems such as mode collapse
核心概念GAN 收敛 = 生成器和判别器达到均衡(equilibrium)。理论上:生成器准确率 100%(在复合 GAN 中训练时测得——即 D 总把假图判成真);判别器准确率 50%(随机猜——可能对真假都判"真")。但即使收敛,也可能有模式崩溃(mode collapse)等问题。
详细讲解

"100% 和 50%" 是同一个硬币的两面:G 的"准确率"是用复合 GAN 训练时的 loss 衡量的——D(G(z)) 越接近 1,G 的 BCE 越小,相当于"G 的预测全对"。D 的准确率是"真图判真 + 假图判假"的正确比例——如果 D 对假图也判真(D(G(z)) ≈ 1),那假图那一半全错;对真图判真,那一半全对;总准确率 50%。所以 G 100% ⇔ D 对假图判不出 ⇔ D 50%。

"Maybe always predict real" 的含义:讲义特意加了这句——50% 不一定意味着 D 输出 0.5,也可能是 D 对所有输入都输出 1("全判真")。这也是 50% 准确率(真图全对、假图全错)。原始论文的均衡是 D(x) = 0.5 处处成立;但实践中 D 可能退化成"常数 1"——G 的 loss 为 0,看起来"收敛"了,但生成的图可能是单一模式。

理想均衡的数学:当 G 的分布 pg = pdata 时,D 的最优解是 D(x) = pdata(x) / (pdata(x) + pg(x)) = 0.5。此时 G 的目标函数取最小值,D 无法更好,G 也无法更好——纳什均衡。

Mode collapse(模式崩溃):G 发现"只生成某一类样本"就能稳定骗过 D(比如只生成一种样子的 8),于是不再生成其他样式——p35 的 GAN 样本 "8 9 8 4 9 4 8 4 4 4" 里只出现 4、8、9 三种(训练集只有 4 和 8,"9" 是 4 和 8 的混合体),而且 4 的形状都差不多——这就是轻度模式崩溃。严重的 mode collapse 下,10 张样本可能完全一样。

为什么 p36 的曲线不能判断收敛:gen_loss 在 ep100 是 1.21(不是 0),dsc_loss 是 0.55(不是 0.69)——两者都不在"理论均衡"位置,但曲线看起来"平了"。这说明 GAN 的"收敛"在实践中是动力学平衡(两条曲线都震荡但幅度不变),而不是数学上的不动点。这也是 p26 "uninformative loss" 的根源。

题目 · Review 关联
  • Review #3 若考 "When does a GAN converge?"——"When the generator and discriminator reach equilibrium: the generator fools the discriminator 100% of the time (measured when trained via the whole GAN), and the discriminator is only 50% accurate (guessing randomly, possibly predicting 'real' for everything)."
  • "Why is 50% accuracy for D equivalent to 100% for G?"——If D cannot reject fakes, its accuracy on fakes is 0% while on reals is 100%, averaging 50%; meanwhile G's fakes are all accepted (100%).
  • "Does convergence guarantee good samples?"——No. Mode collapse may still occur: the generator produces a limited variety that fools D.
  • Review #4 "Difficulties" 里的 mode collapse(p26)与本页最后一句直接对应。
必要扩展
  • Mode collapse 的对策:Minibatch discrimination(Salimans 2016)、Unrolled GAN、WGAN(p39——Wasserstein 距离对模式崩溃更敏感)、ProgGAN / StyleGAN 的多尺度结构。本讲不要求,但知道"mode collapse 是 GAN 的头号难题"即可。
  • "Equilibrium" 在博弈论里是纳什均衡——任何一方单方面改变策略都不会更好。GAN 训练用梯度下降找均衡,但两个网络交替更新相当于"两个玩家轮流走",不保证收敛(Monotone operator 理论)。这是 p26 non-convergence 的理论基础。
  • 另一种"收敛"的判定:看样本——如果连续多次 plot_samples 的结果不再变化,可以视为"实用收敛"。讲义 p35 每 10 轮画一次样本,就是让你用眼睛判断。
易错点 · 理解提示① "D 50%" 是准确率,不是"D 输出 0.5"——讲义说 "maybe always predict real",提醒你 50% 有多种实现方式。② "G 100%" 的准确率是在复合 GAN 中训练时测得的(即 D(G(z)) 接近 1),不是 G 自己"分类"的准确率。③ 收敛 ≠ 没问题:mode collapse 可以在收敛后发生。
p.26训练 GAN 的困难(非收敛 / 模式崩溃 / 梯度消失 / 损失无信息 / 超参敏感)★Review困难
Difficulties in training GANs  Non-convergence: the loss of the discriminator and generator may oscillate and not converge  Mode collapse: the generator finds and produces limited varieties of instances to fool the discriminator, and then collapses and stops finding other varieties  Vanishing gradients of generator: the discriminator is too good that the generator has vanishing gradients and does not learn at all  Uninformative loss of generator: the loss of the generator is measured using the current discriminator, which however keeps improving  Many and sensitive hyperparameters: the discriminator and generator have many hyperparameters which are difficult to tune
核心概念训练 GAN 的五大困难(必背):① 非收敛(non-convergence)——D 和 G 的损失震荡、不收敛;② 模式崩溃(mode collapse)——G 只生成有限几种样本骗 D,然后停止探索;③ 生成器梯度消失(vanishing gradients)——D 太强,G 的梯度消失、完全不学;④ 生成器损失无信息(uninformative loss)——G 的 loss 是用"当前的 D"测的,而 D 一直在变;⑤ 超参多且敏感——D 和 G 有很多难调的超参数。
详细讲解

五条可以按"症状 → 原因 → 本讲的证据"整理:

#困难症状原因本讲证据
1Non-convergence两条 loss 曲线震荡两个网络交替更新,没有保证收敛的优化目标p36 gen_loss ep2 峰 2.25 → ep8 谷 0.62 → ep40 回升 1.4
2Mode collapse样本只有少数几种G 发现"单一模式"即可骗 D,不再探索p35 样本只有 4/8/9,且形状雷同
3Vanishing gradients (G)G 的 loss 高但不降D 太强 → D(G(z)) ≈ 0 → −log(1−D) 饱和、梯度 ≈ 0p36 初期 dsc_loss 跌到 0.07,gen_loss 冲到 2.25
4Uninformative loss (G)gen_loss 低但样本差G 的 loss 相对"当前 D"——D 变弱时 G 的 loss 自动变低p35 gen_loss 从 ep40 的 1.39 "降"到 ep100 的 1.21,但样本没明显变好
5Sensitive hyperparameters换个学习率就崩D 和 G 要平衡,任一方的结构/学习率/训练次数都影响平衡p29 用 rmsprop 而非 adam、Dropout 0.5;p31 D 每批只训一次

第 3 条的推导(最可能出计算/解释题):原始 GAN 的 G 损失是 −log(1 − D(G(z)))。当 D 很强,D(G(z)) ≈ 0,1 − D(G(z)) ≈ 1,log(1) ≈ 0——函数值接近 0 且回平,对 G 的参数的导数 ≈ 0。梯度 ≈ 0 → G 不学。这就是"vanishing gradients"。本讲用 −log D(G(z))(标签 1),D(G(z)) ≈ 0 时 loss = 4.6、梯度大——缓解了这个问题,但没有根除(因为 D 仍在变强)。

第 4 条的深意:AE 的 loss 是"和固定目标(输入)的距离"——可以跨轮比较。GAN 的 G loss 是"和移动目标(当前的 D)的关系"——ep10 的 0.65 和 ep100 的 1.21 不可比,因为两个时期的 D 不同。所以 p35 的 gen_loss 不反映样本质量——看图比看数字可靠。这是 WGAN(p39)要解决的核心问题:"a meaningful loss metric that correlates with the generator's convergence and sample quality"。

第 1 和第 4 条的区别:non-convergence 是"曲线不动"(震荡),uninformative 是"曲线动了也没用"(不反映质量)。两者常同时发生。

第 5 条的体现:本讲选 rmsprop(不是 adam)——经验上 rmsprop 在 GAN 上更稳定;判别器加 Dropout(0.5)——削弱 D 防止太强;D 每批只训一次——限制 D 的进步;batch 512——大批次让梯度更稳。这些都是"调参"的结果,换一组可能就训不出来。

题目 · Review 关联
  • Review #4 必背五条,每条要能写一句定义 + 一句解释。考题形式:"State THREE difficulties in training GANs and explain each."
  • "Why is the generator's loss uninformative?"——Because it is measured against the current discriminator, which keeps changing; losses at different epochs are not comparable and do not reflect sample quality.
  • "How does a too-strong discriminator cause vanishing gradients?"——With the original loss −log(1−D(G(z))), D(G(z))≈0 makes the loss saturate near 0 with near-zero gradient, so the generator cannot learn.
  • "What is mode collapse? Give an example from the lecture."——The generator produces only a few varieties to fool D; e.g., the p35 samples contain only 4s, 8s and 9-like hybrids with similar shapes.
  • 和 WGAN(p39)的联系:WGAN 的两大改进正好对应第 4 条(meaningful loss)和第 1 条(stability)——考"how does WGAN address these difficulties"时按这个对应答。
必要扩展
  • 五条困难的相互关系:D 太强 → 第 3 条;G 太强(找到捷径)→ 第 2 条;两者拉锯 → 第 1 条;损失不可比 → 第 4 条;所有这些都靠调参缓解 → 第 5 条。它们不是独立的,而是"两个网络对抗"这一结构的连锁反应。
  • 实践对策(本讲用了的加 ✓):D 加 Dropout ✓、用 rmsprop ✓、D 每批只训一次 ✓、标签平滑 ✗、TTUR(D 和 G 不同学习率)✗、谱归一化 ✗、梯度惩罚(WGAN-GP,p42 提到)。
  • 更现代的视角:GAN 的很多问题源于"用分类器做分布比较"——扩散模型用"去噪得分匹配"绕过了对抗,2020 年后成为主流。但 GAN 的"对抗训练"思想在 RLHF、域适应等地方仍然活跃。
易错点 · 理解提示① 五条的名字要背英文原文(non-convergence / mode collapse / vanishing gradients / uninformative loss / sensitive hyperparameters),考题用英文提问。② 第 3 条是G 的梯度消失,不是 D 的——别写反。③ "Mode collapse" 不是"训练崩溃"(loss 爆炸)——它是"样本单一化",loss 可能看起来很正常。
p.27分节页:GAN code example分节
GAN code example
核心概念进入 GAN 代码段(p28–36,共 10 页):建生成器(p28)→ 建判别器和复合 GAN(p29)→ 生成输入/样本(p30)→ 训练 D 和 G(p31)→ 整个训练循环(p32)→ 更新历史(p33)→ 整合(p34)→ 结果(p35–36)。
详细讲解

这 10 页的结构是典型的"Keras 函数式工程代码":每个页一个或两个函数,最后 p34 用五行把它们串起来。和自编码器代码(一个 Sequential + fit)相比,GAN 必须手写训练循环——因为 fit 只能训练一个模型、一个损失,而 GAN 每批要交替训练 D 和 G 两个模型。

读代码的顺序建议:先看 p34(入口)→ 知道要调 create_generator、create_discriminator、create_gan、train_gan 四个函数 → 再看 p32(train_gan 的双层循环)→ 再看 p31(循环体里调的 train_discriminator / train_generator)→ 最后回头看 p28–30(三个 create 函数和两个 generate 函数)。

Course Review 把这段标为 #5 (optional)——意味着不要求默写,但要能读懂和修改。本讲义每页都给出"代码逐行 + 参数计算 + 可能的考题",文末"代码精读"卡再做一次总览。

题目 · Review 关联
  • Review #5 "GAN code example (optional)"——考法:"modify code"长题(如"把生成器的 BN 去掉""把 D 的优化器换成 adam""把 batch_size 改成 256 后每轮多少步")或"explain what line X does"。
  • Unit 8 的卷积参数公式 (k·k·din+1)·n 在 p28–29 要用 6 次;Unit 7 的 BN 参数 = 2×通道数 要用 5 次。
必要扩展
  • 为什么 GAN 不能用 fit?因为 fit 的假设是"一个模型、一个 (X, y) 对、每步一次梯度更新"。GAN 每步要:① 生成假图;② 训练 D(两次 train_on_batch);③ 冻结 D、训练 G(一次 train_on_batch)。这三步是不同模型、不同数据的交替——只能手写循环。train_on_batch 是 Keras 提供的"单批训练"原语。
易错点 · 理解提示optional 不等于"不考"——它意味着"不要求默写整段",但 p29 的 trainable = False、p31 的两次 train_on_batch、p32 的 n_batches 这些关键行仍然可能出现在"填空/改错/解释"题里。
p.28GAN 代码:创建生成器(Dense→Reshape→UpSampling×2→Conv2D×3)★Review代码·参数
GAN code example – creating generator
SZ_LATENT_GAN = 40

def create_generator():
    model = keras.Sequential([
        layers.Dense(7*7, activation=layers.LeakyReLU(0.2)),
        layers.BatchNormalization(),
        layers.Reshape(target_shape=(7, 7, 1)),
        layers.UpSampling2D(size=(2, 2)),
        layers.Conv2D(64, kernel_size=(5, 5), padding="same",
                      activation=layers.LeakyReLU(0.2)),
        layers.BatchNormalization(),
        layers.UpSampling2D(size=(2, 2)),
        layers.Conv2D(64, kernel_size=(5, 5), padding="same",
                      activation=layers.LeakyReLU(0.2)),
        layers.BatchNormalization(),
        layers.Conv2D(1, kernel_size=(5, 5), padding="same",
                      activation="sigmoid")
    ])
    return model
生成器:40 维噪声 → 7×7 → 14×14 → 28×28 Dense 49LReLU + BN98 Reshape7×7×1 UpSample→14×14 Conv2D 645×5 sameLReLU·BN UpSample→28×28 Conv2D 645×5 sameLReLU·BN Conv2D 15×5 samesigmoid 28×28×1 参数:2,009 + 98 + 1,664 + 128 + 102,464 + 128 + 1,601 = 108,092
图 12.P28 讲义 p28 生成器结构重绘:Dense(49) → Reshape(7,7,1) → [UpSampling → Conv2D(64) + BN] ×2 → Conv2D(1, sigmoid)。输入 40 维噪声,输出 28×28×1 图像。
核心概念create_generator():先全连接再卷积——Dense(7×7=49, LeakyReLU 0.2) → BN → Reshape(7,7,1) → UpSampling2D(×2) → Conv2D(64, 5×5, same, LReLU) → BN → UpSampling2D(×2) → Conv2D(64, 5×5, same, LReLU) → BN → Conv2D(1, 5×5, same, sigmoid)。空间 7→14→28,通道 1→64→64→1。总参数 108,092(第一个 BN 作用在 Dense 的 49 维输出上,98 个参数)。
详细讲解

设计思路:从"向量"到"图"。噪声是 40 维向量,没有空间结构;输出是 28×28 的图。怎么过渡?先生成一个 7×7 的"小图"(49 个数),再两次上采样放大到 28×28——这是 DCGAN 的标准做法(Radford 原版从 4×4 或 7×7 起步,放大到 64×64)。7×7 是因为 28/4 = 7。

逐层读:

  • Dense(7*7, LeakyReLU(0.2)):40 → 49。参数 40×49 + 49 = 2,009。LeakyReLU(0.2):x<0 时输出 0.2x(不是 0)——GAN 里用 LeakyReLU 而非 ReLU 是为了让负区也有梯度。
  • BatchNormalization():紧接在 Dense 之后、Reshape 之前,作用在 49 维向量的最后一维(Keras 默认 axis=−1)→ 可训练参数 γ+β = 2×49 = 98(另有 2 个不可训练的滑动均值/方差)。
  • Reshape((7, 7, 1)):49 → (7,7,1)。无参数。
  • UpSampling2D(size=(2,2)):7×7 → 14×14,每个像素复制成 2×2。无参数。
  • Conv2D(64, 5×5, same, LReLU):14×14×1 → 14×14×64。参数 (5×5×1 + 1)×64 = 26×64 = 1,664。
  • BatchNormalization():64 通道 → 2×64 = 128。
  • UpSampling2D(size=(2,2)):14×14 → 28×28。无参数。
  • Conv2D(64, 5×5, same, LReLU):28×28×64 → 28×28×64。参数 (5×5×64 + 1)×64 = 1,601×64 = 102,464。
  • BatchNormalization():128。
  • Conv2D(1, 5×5, same, sigmoid):28×28×64 → 28×28×1。参数 (5×5×64 + 1)×1 = 1,601。sigmoid 输出 [0,1] 匹配像素。

第一个 BN 的参数数要小心:它作用在 Dense 的 49 维输出上(不是 Reshape 之后的 1 通道),所以是 2×49 = 98,不是 2。这里最容易错——很多人一看"后面是 (7,7,1)"就以为 BN 只有 1 个通道。判断 BN 参数只看它直接接收的张量形状:Dense 输出 (n, 49) → 98;Conv 输出 (n, 14, 14, 64) → 128。

总参数:2,009 + 98 + 1,664 + 128 + 102,464 + 128 + 1,601 = 108,092。

层输出形状参数计算参数量
Dense(49, LReLU)(n, 49)40×49 + 492,009
BatchNormalization(n, 49)2×4998
Reshape(7,7,1)(n, 7, 7, 1)—0
UpSampling2D(n, 14, 14, 1)—0
Conv2D(64, 5×5, same)(n, 14, 14, 64)(5×5×1 + 1)×641,664
BatchNormalization(n, 14, 14, 64)2×64128
UpSampling2D(n, 28, 28, 64)—0
Conv2D(64, 5×5, same)(n, 28, 28, 64)(5×5×64 + 1)×64102,464
BatchNormalization(n, 28, 28, 64)2×64128
Conv2D(1, 5×5, same, sigmoid)(n, 28, 28, 1)(5×5×64 + 1)×11,601
总计40 → 28×28×1—108,092

为什么最后一层用 sigmoid 而不是 tanh:Radford 的 DCGAN 用 tanh(输出 [−1,1],配合归一化到 [−1,1] 的数据);本讲数据是 [0,1](p14 除以 255),所以用 sigmoid。两者都可行,只要数据范围和输出范围匹配。

和自编码器解码器的对比:AE 解码器是 Dense 堆叠(40→256→512→784),G 是 Dense + 卷积堆叠。卷积版的参数少得多(108,092 vs 544,272)——因为卷积核共享权重(Unit 8),而且先在 7×7 小图上运算,计算量也小。

题目 · Review 关联
  • 参数计算题:"Calculate the number of parameters in the generator"——按上表逐层算 → 108,092。易错点:第一个 BN 是 98(49 维),不是 2。
  • "What is the output shape of the generator?"——(None, 28, 28, 1)。
  • "Why LeakyReLU(0.2) instead of ReLU?"——LeakyReLU keeps a small gradient for negative inputs, which stabilizes GAN training (DCGAN guideline).
  • "Why Reshape((7,7,1))?"——To convert the 49-dim vector into a 7×7 spatial map so that upsampling and convolution can grow it to 28×28.
  • "Why UpSampling2D?"——To double the spatial size (7→14→28) without pooling; it has no parameters.
  • Unit 8 公式 (k·k·din+1)·n 用了三次:1,664 / 102,464 / 1,601;Unit 7 公式 BN = 2×通道 用了三次。
必要扩展
  • DCGAN 的生成器通常用 Conv2DTranspose(转置卷积)代替 UpSampling2D + Conv2D——前者一步完成上采样和卷积,有参数;后者先复制像素再卷积,无参数的上采样 + 有参数的卷积。本讲用后者,可能是为了减少参数和避免 checkerboard 伪影。
  • BN 在生成器中的作用: stabilize 训练——DCGAN 论文发现加 BN 后生成器不再"塌陷"到单一样本(mode collapse 的早期形式)。但 BN 也有问题:batch 内样本相互影响,生成结果会依赖于同批的其他噪声(这是 WGAN-GP 不用 BN 的原因之一,p42)。
  • 生成器的第一层 Dense(49) 不用 relu 而用 LeakyReLU——因为 BN 紧随其后,ReLU 的稀疏输出会让 BN 的均值/方差估计不稳定。
易错点 · 理解提示① 第一个 BN 的参数是 98(对 Dense 的 49 维输出),不是 2——BN 在 Reshape 之前。② UpSampling2D 无参数——别把它算进去。③ 7×7 来自 28/4(两次 ×2)——如果输出改成 32×32,第一层就是 Dense(8×8)。④ padding="same" 保持尺寸不变——尺寸变化全靠 UpSampling。
p.29GAN 代码:创建判别器与 GAN(Conv2D s2 ×3→Dropout→Dense(1) sigmoid)★Review代码·参数
GAN code example – creating discriminator & GAN
def create_discriminator():
    model = keras.Sequential([
        layers.Conv2D(64, kernel_size=(5, 5), strides=2,
                  padding="same", activation=layers.LeakyReLU(0.2)),
        layers.Dropout(0.5),
        layers.Conv2D(64, kernel_size=(5, 5), strides=2,
                  padding="same", activation=layers.LeakyReLU(0.2)),
        layers.Dropout(0.5),
        layers.Conv2D(64, kernel_size=(5, 5), strides=2,
                  padding="same", activation=layers.LeakyReLU(0.2)),
        layers.Dropout(0.5),
        layers.Flatten(),
        layers.Dense(1, activation="sigmoid")
    ])
    model.compile(loss="binary_crossentropy", optimizer="rmsprop")
    model.trainable = False
    return model

def create_gan(generator, discriminator):
    model = keras.Sequential([generator, discriminator])
    model.compile(loss="binary_crossentropy", optimizer="rmsprop")
    return model
核心概念create_discriminator():三个 strided Conv2D(64 个 5×5 核、stride 2、same、LeakyReLU 0.2)各接 Dropout(0.5),再 Flatten → Dense(1, sigmoid)。空间 28→14→7→4(stride-2 same 向上取整),Flatten 后 4×4×64 = 1,024 → 1。编译用 BCE + rmsprop,返回前 trainable = False。create_gan():Sequential([G, D]) 串成复合模型,同样 BCE + rmsprop。判别器参数 207,617,复合 GAN 315,709。
详细讲解

判别器 = 一个 CNN 二分类器。结构和 Unit 9 的 AlexNet-like、Unit 10 的 CNN_64 几乎一样:卷积提特征 → Flatten → Dense(1) 输出概率。区别在于下采样方式:Unit 8–9 用 MaxPooling,这里用 stride=2 的卷积(DCGAN 原则:"strided conv 替代池化")。

逐层读:

  • Conv2D(64, 5×5, strides=2, same, LReLU):28×28×1 → 14×14×64。参数 (5×5×1 + 1)×64 = 1,664。
  • Dropout(0.5):随机丢一半特征图。无参数。作用:防止 D 太强(p26 第 3 条)。
  • Conv2D(64, 5×5, strides=2, same, LReLU):14×14×64 → 7×7×64。参数 (5×5×64 + 1)×64 = 102,464。
  • Dropout(0.5)。
  • Conv2D(64, 5×5, strides=2, same, LReLU):7×7×64 → 4×4×64。参数 102,464。注意 7/2 = 3.5,same padding 向上取整 → 4。
  • Dropout(0.5)。
  • Flatten():4×4×64 = 1,024 维。无参数。
  • Dense(1, sigmoid):1,024 → 1。参数 1,024×1 + 1 = 1,025。

总参数:1,664 + 102,464 + 102,464 + 1,025 = 207,617。

stride-2 same 的尺寸公式:out = ⌈in / 2⌉。28 → 14 → 7 → 4(7/2 = 3.5 → 4)。如果用 Unit 8 的通用公式 ⌊(I + 2P − K)/S⌋ + 1,same padding 时 P = ⌊K/2⌋ = 2:(28 + 4 − 5)/2 + 1 = 13.5 → Keras 向上取整 = 14 ✓;(7 + 4 − 5)/2 + 1 = 4 ✓。记住 same + stride 2 = 向上取整除以 2。

model.trainable = False 在 create 时就设——这是讲义代码的一个特点。语义:判别器默认冻结;p31 的 train_discriminator 每次训练前显式设 trainable = True,训练完再设回 False。这样 create_gan 时 D 已经是冻结的,复合模型训练时梯度只流向 G——正好符合 p24 的要求。讲义 p24 说"set the discriminator to be non-trainable"是训练 G 时的操作,代码用"默认关闭 + 训练 D 时临时打开"实现同一效果。

为什么用 rmsprop 不用 adam:经验选择——DCGAN 论文用 Adam(β₁=0.5),但很多教程(包括 Keras 官方 DCGAN 例)用 rmsprop。rmsprop 对 GAN 的震荡更鲁棒(没有动量项),这是 p26 第 5 条"敏感超参"的一个体现。

create_gan 做了什么:Sequential([generator, discriminator])——数据从噪声进入 G,输出假图,再进入 D,输出概率。编译 BCE + rmsprop。训练这个复合模型(输入噪声、标签 1)时,由于 D 冻结,只有 G 更新——这就是 p24 "训练 G"的代码实现。

复合 GAN 的参数:G 108,092 + D 207,617 = 315,709。但训练 G 时可训练参数只有 108,092(D 冻结)。

题目 · Review 关联
  • 参数计算:"Parameters of the discriminator" = 207,617;"Parameters of the whole GAN" = 315,709;"Trainable parameters when training the generator" = 108,092。
  • 尺寸题:"What is the shape after the third Conv2D?"——(n, 4, 4, 64)(7/2 向上取整 = 4);"What is the Flatten output?"——1,024。
  • "Why trainable = False in create_discriminator?"——So that when the composite GAN is trained, the discriminator is frozen and only the generator updates (p24).
  • "Why Dropout in the discriminator?"——To prevent the discriminator from becoming too strong, which would cause vanishing gradients for the generator.
  • "Why strides=2 instead of MaxPooling?"——DCGAN guideline: strided convolutions replace pooling in the discriminator.
  • Review #5 若考"modify code: remove Dropout from the discriminator"——后果:D 更强、训练更不稳定、G 可能梯度消失。
必要扩展
  • Keras trainable 的作用域:对一个 Sequential 设 trainable=False 会递归设到所有子层;train_on_batch 和 fit 都尊重它。但注意:如果你在 compile() 之后改 trainable,需要重新 compile 才生效(Keras 2.x 的一个坑)。本讲代码在 compile 之后、return 之前设 trainable=False,但 D 在 p31 被 train_on_batch 前又设 True——Keras 2.x 在某些版本会在 train_on_batch 时动态检查 trainable,所以能工作;严格来说应该在切换后重新 compile。
  • Dropout 在判别器中的位置:每个 Conv 后一个——不是在 Flatten 后。这和 Unit 9 的 AlexNet-like(在 Dense 后 Dropout)不同;DCGAN 论文没有明确指导,但"在卷积层之间加 Dropout"是常见做法。
  • 判别器的感受野:三个 5×5 stride-2 卷积叠起来,输出每个值对应输入的 5 + 4×2 + 4×4 = 29 像素——比 28 还大,所以 Dense(1) 的每个输入都"看到"了整张图。
易错点 · 理解提示① 7×7 stride 2 → 4(向上取整),不是 3——same padding。② Dense(1) 的参数是 1,025 = 1,024 + 1,别忘 bias。③ trainable = False 不删参数——D 仍有 207,617 个参数,只是不更新;"复合 GAN 参数 315,709"和"训练 G 时可训练 108,092"是两个不同的数字。④ 编译器用 rmsprop——不是 Unit 7 Lab 常用的 adam。
p.30GAN 代码:生成输入与样本(正态噪声)代码
GAN code example – generating inputs & samples
def generate_sample_inputs(n_samples):
    inputs = np.random.normal(0, 1, size=(n_samples, SZ_LATENT_GAN))
    return inputs

def generate_samples(generator, n_samples):
    inputs = generate_sample_inputs(n_samples)
    samples = generator.predict(inputs, verbose=0)
    return samples
核心概念两个工具函数:generate_sample_inputs(n) 生成 n 个 40 维正态噪声 N(0,1)——生成器的输入;generate_samples(generator, n) = 采噪声 → generator.predict → 返回 n 张假图。后者在训练循环(p31 造假图、p33 画样本)和最终展示(p36)里被反复调用。
详细讲解

np.random.normal(0, 1, size=(n, 40)):均值 0、标准差 1 的正态分布,形状 (n, 40)。和 p19 AE 的 np.random.random(均匀 [0,1))对比:

AE(p19)GAN(p30)
函数np.random.random((10, 40))np.random.normal(0, 1, (n, 40))
分布均匀 U[0, 1)正态 N(0, 1)
范围[0, 1),全非负(−∞, +∞),约 68% 在 [−1,1]
为什么编码器潜层 sigmoid → (0,1)生成器第一层 Dense 无 sigmoid,LReLU 接受负值
喂给decoder.predictgenerator.predict

为什么 GAN 用正态:GAN 的潜空间完全由生成器自己定义——没有编码器把它"锚定"到某个范围。正态分布是最"自然"的选择(中心集中、四周稀疏、对称),是所有 GAN 的标准做法(StyleGAN 的 512 维 z 也是 N(0,1))。而 AE 的潜向量有 sigmoid 约束,必须用均匀分布才匹配。

generate_samples 的调用链:p31 train_discriminator 用它造 batch_size 张假图(训练 D);p31 train_generator 不用它——训练 G 时直接把噪声喂给复合 GAN(gan.train_on_batch(X, y)),假图在复合模型内部由 G 现场生成;p33 update_history 用它造 10 张样本画图;p36 用它造最终 10 张。

为什么分开两个函数:generate_sample_inputs 只管"采噪声"(不涉及模型),generate_samples 管"采噪声 + 过生成器"。这样 train_generator 可以只用前者(噪声直接喂 gan),而需要假图的地方用后者。职责分离是良好的工程习惯。

verbose=0:关掉 predict 的进度条——训练循环中每批都会调用,不关会刷屏。

题目 · Review 关联
  • "What is the shape of generate_sample_inputs(512)?"——(512, 40);"generate_samples(generator, 10)?"——(10, 28, 28, 1)。
  • "Why does the GAN use normal noise while the autoencoder uses uniform noise?"——GAN's generator has no sigmoid on its latent input; AE's latent layer is sigmoid-bounded to (0,1), so uniform noise matches.
  • Review #5 填空题:inputs = np.random.normal(____, ____, size=(n_samples, SZ_LATENT_GAN))——0, 1。
  • "Which function is used in train_generator?"——generate_sample_inputs(噪声直接喂 gan),不是 generate_samples。
必要扩展
  • SZ_LATENT_GAN = 40 和 SZ_LATENT_AE = 40 相同——但两个潜空间互不相通:AE 的潜空间是"编码器输出"的 40 维,G 的潜空间是"噪声输入"的 40 维,没有任何关系。相同数字只是讲义的选择。
  • 噪声维数的影响:太小(如 8)→ 潜空间不够表达多样性,容易 mode collapse;太大(如 512)→ 大部分维度用不上。40 对 MNIST 足够;StyleGAN 用 512 是因为 1024×1024 的人脸需要更多变化。
  • "Latent space interpolation"在 GAN 里比在 AE 里效果好——因为 GAN 的生成器是连续映射,噪声空间中相邻的点生成相似的图。两个噪声 z₁、z₂ 之间插值,会看到"一个人脸逐渐变成另一个人脸"。
易错点 · 理解提示① np.random.normal 的三个位置参数是 (loc, scale, size)——normal(0, 1, size):均值 0、标准差 1(不是方差 1)、形状 size。② generate_samples 返回的是假图(generator 的输出),不是噪声——别和 generate_sample_inputs 混。③ generate_samples 需要传 generator 参数(因为它是模块级函数,不持有模型引用)。
p.31GAN 代码:训练判别器与生成器(train_on_batch 交替)★Review代码·训练
GAN code example – training discriminator & generator
def train_discriminator(generator, discriminator, X_train_batch,
                        batch_size):
    X_real = X_train_batch
    y_real = np.ones(batch_size)
    X_fake = generate_samples(generator, batch_size)
    y_fake = np.zeros(batch_size)
    discriminator.trainable = True
    loss = discriminator.train_on_batch(X_real, y_real)
    loss += discriminator.train_on_batch(X_fake, y_fake)
    discriminator.trainable = False
    return loss / 2

def train_generator(generator, gan, batch_size):
    X = generate_sample_inputs(batch_size)
    y = np.ones(batch_size)
    loss = gan.train_on_batch(X, y)
    return loss
核心概念train_discriminator:真图 y=1、假图 y=0,打开 D 的 trainable → 两次 train_on_batch → 关闭 → 返回两次 loss 的平均。train_generator:噪声 X、标签全 1(假图标真),gan.train_on_batch——因 D 已冻结,只有 G 更新。这是 p23–24 两页原理的代码实现。
详细讲解

train_discriminator 逐行:

  • X_real = X_train_batch:一批真图(来自 p32 的切片),形状 (batch_size, 28, 28, 1)。
  • y_real = np.ones(batch_size):全 1 标签——"真"。
  • X_fake = generate_samples(generator, batch_size):用当前的 G 现场生成一批假图(p30)。
  • y_fake = np.zeros(batch_size):全 0——"假"。
  • discriminator.trainable = True:打开 D 的可训练开关(p29 在 create 时关了)。
  • loss = discriminator.train_on_batch(X_real, y_real):用真图训练 D 一步,返回这步的 BCE loss。
  • loss += discriminator.train_on_batch(X_fake, y_fake):再用假图训练 D 一步,loss 累加。
  • discriminator.trainable = False:关回去——这样后续训练 G 时 D 不会动。
  • return loss / 2:两次 loss 的平均值。

为什么分两次 train_on_batch 而不是拼接:也可以 np.concatenate([X_real, X_fake]) 一次训练 2×batch_size 张——数学上等价(BCE 对每个样本独立)。分两次的好处是代码清晰、不用拼接;缺点是两次更新而不是一次(梯度噪声略大)。讲义选了分两次。

loss / 2 的含义:真图那次的 loss 和假图那次的 loss 各是一个均值,再取平均——相当于"真图 BCE + 假图 BCE"的平均值。注意不是原始 GAN 目标函数里的 (log D(x) + log(1−D(G(z))))——这里是两个 BCE 的平均,量纲一样但数值不同。p35 的 dsc_loss 就是这个值:ep10 0.11、ep100 0.55。

train_generator 逐行:

  • X = generate_sample_inputs(batch_size):只采噪声,不生成假图——假图由复合模型内部的 G 现场生成。
  • y = np.ones(batch_size):全 1——"假图标真"(p24)。
  • loss = gan.train_on_batch(X, y):训练复合 GAN 一步。数据流:X → G → 假图 → D → 概率。因为 D 冻结,梯度只更新 G。
  • return loss:这步 G 的 BCE loss(p35 的 gen_loss)。

为什么 train_generator 不碰 trainable:因为它依赖 train_discriminator 已经把 D 关了(上一行 discriminator.trainable = False)。p32 的循环里先调 train_discriminator 再调 train_generator,顺序保证了 D 在训练 G 时是冻结的。如果单独调用 train_generator 而没先调 train_discriminator,D 可能仍然是 False(因为 p29 create 时就是 False)——所以实际上安全;但如果有人手动设过 True,就会出问题。

生成器参数 generator 在 train_generator 里没用到——这是讲义代码的一个小瑕疵:签名里有 generator 但函数体只用 gan(gan 内部包含 generator)。保留它可能是为了和 train_discriminator 的签名对称。

题目 · Review 关联
  • 填空题:y_real = np.____(batch_size) → ones;y_fake = np.____ → zeros;train_generator 里 y = np.____ → ones(假图标真,不是 zeros)。
  • "Why trainable = True before and False after?"——To update D only during its own training step and keep it frozen for the generator step (p24).
  • "Why loss / 2?"——Two train_on_batch calls (real, fake) each return a mean loss; averaging gives the discriminator loss per batch.
  • "What is the input to gan.train_on_batch?"——Noise vectors (not images), because the composite model starts with the generator.
  • "How many gradient updates per batch for D and G?"——D: 2 (real + fake); G: 1。所以 D 每批更新次数是 G 的 2 倍——这和 WGAN 的 3 倍(p47)形成对比。
必要扩展
  • train_on_batch 返回值:Keras 2.x 中 compile 只指定 loss 时返回标量 loss;若指定 metrics 则返回 [loss, ...metrics]。本讲只用 loss,所以返回标量,可以直接 +=。
  • Keras trainable 切换的坑:在 compile() 之后改 trainable,某些 Keras 版本需要重新 compile 才生效。本讲代码能工作是因为 train_on_batch 在每次调用时重新计算梯度(不像 fit 缓存了计算图)。更严谨的写法是在切换后重新 compile,或用 train_on_batch 前检查。
  • D 每批更新 2 次、G 1 次——这是让 D 比 G"学得快"的设计。但 GAN 的常见问题是 D 太强(p26 第 3 条),所以也有反过来(G 更新多次)的做法。WGAN 的 p47 用 for _ in range(3) 让 critic 更新 3 次——因为 WGAN 需要 critic 尽量强(p41 "no need to balance")。
易错点 · 理解提示① 训练 D 时假图标 0,训练 G 时假图标 1——同一张假图、两个标签。② train_generator 的输入是噪声不是假图。③ trainable 的 True/False 切换只在 train_discriminator 里——train_generator 依赖它留下的 False 状态。④ loss / 2 是两次 BCE 的平均,不是原始 GAN 目标函数的值。
p.32GAN 代码:训练整个 GAN(train_gan 双层循环)★Review代码·训练
GAN code example – training the whole GAN
import math, time

def train_gan(generator, discriminator, gan, X_train, epochs=100,
              batch_size=512):
    n_batches = math.ceil(len(X_train) / batch_size)
    history = {"gen_loss": [], "dsc_loss": [], "message": [],
               "samples": []}
    start_time = time.time()
    for i in range(epochs):
        gen_loss = dsc_loss = 0
        for j in range(n_batches):
            start = j * batch_size
            end = min((j+1) * batch_size, len(X_train))
            X_train_batch = X_train[start:end]
            dsc_loss += train_discriminator(
                generator, discriminator, X_train_batch, end-start)
            gen_loss += train_generator(generator, gan, end-start)
        update_history(history, start_time, i, epochs,
               gen_loss / n_batches, dsc_loss / n_batches, generator)
    return history
核心概念train_gan:双层循环——外层 100 轮,内层 n_batches = ⌈11693/512⌉ = 23 批。每批:切真图 → 训练 D(1 次,含两步)→ 训练 G(1 次)→ 累加 loss。每轮结束调 update_history 记录每批平均 loss。batch_size=512 是 GAN 的默认值(AE 是 256)。
详细讲解

为什么不用 fit:p27 扩展讲过——fit 只能训练一个模型。这里每批要交替训练 D 和 G,只能手写循环。这个函数就是 GAN 版的 fit:它做了 fit 做的所有事(分批、迭代、记录历史),只是循环体里是两个不同的训练步骤。

逐行读:

  • n_batches = math.ceil(len(X_train) / batch_size):⌈11693 / 512⌉ = 23(22 批 512 张 + 1 批 11693 − 22×512 = 429 张)。math.ceil 保证最后不足一批的也算一批。
  • history = {"gen_loss": [], "dsc_loss": [], "message": [], "samples": []}:四个列表,分别存每轮 G loss、D loss、每 10 轮的消息字符串、每 10 轮的样本图。
  • start_time = time.time():计时起点——p35 的 "time elapsed: 79.0s" 就是从这里算。
  • 外层 for i in range(epochs):i = 0 … 99。
  • gen_loss = dsc_loss = 0:每轮开始清零——Python 的链式赋值,两个变量都是 0。
  • 内层 for j in range(n_batches):j = 0 … 22。
  • start = j * batch_size; end = min((j+1) * batch_size, len(X_train)):切片范围。min 处理最后一批:j=22 时 (23)×512 = 11,776 > 11,693,所以 end = 11,693,这批只有 429 张。
  • X_train_batch = X_train[start:end]:取这批真图。没有 shuffle——每轮都是同样的顺序(Unit 7 的 fit(shuffle=True) 会打乱,这里手写循环没做)。
  • dsc_loss += train_discriminator(..., end-start):训练 D,end-start 是这批的真实大小(最后一批 429)。
  • gen_loss += train_generator(..., end-start):训练 G。
  • update_history(..., gen_loss / n_batches, dsc_loss / n_batches, generator):把累加的 loss 除以批数——得到每批平均 loss。

总步数:23 批/轮 × 100 轮 = 2,300 批;每批 D 更新 2 次 + G 更新 1 次 → D 共 4,600 步、G 共 2,300 步。p35 的 ep100 "462.8s" → 平均每批约 0.2 秒。

为什么 batch 512 比 AE 的 256 大:GAN 的梯度噪声大(两个网络对抗),大批次能平滑梯度;另外每批要生成 512 张假图 + 训练 3 次,批小了开销比例大。

和 AE 训练的对比:AE 用 fit(X, X, epochs=100, batch_size=256) → 46 步/轮 × 100 = 4,600 步,一次前向+反向;GAN 23 批/轮 × 100 = 2,300 批,每批 3 次前向+反向(D 两次 + G 一次)+ 一次生成——所以 GAN 的训练时间(7.7 分钟)远长于 AE(约 1–2 分钟)。

题目 · Review 关联
  • 计算题:"How many batches per epoch?"——⌈11693/512⌉ = 23;"How many images in the last batch?"——11693 − 22×512 = 429;"Total batches for 100 epochs?"——2,300。
  • "Why math.ceil?"——So the last partial batch (429 images) is still included.
  • "Why min((j+1)*batch_size, len(X_train))?"——To prevent the last slice from going past the end of the array.
  • "Why gen_loss / n_batches?"——gen_loss is a sum over 23 batches; dividing gives the mean per batch, which is comparable across epochs.
  • "Modify batch_size to 256"——n_batches = ⌈11693/256⌉ = 46,最后一批 173 张。
  • Review #4 的 non-convergence 在这里的体现:循环没有任何早停——100 轮跑满,不管 loss 是否收敛。
必要扩展
  • 没有 shuffle 的影响:每轮看到同样的 4 和 8 顺序,D 可能记住"这批真图长什么样"——加剧 D 过拟合。改进:idx = np.random.permutation(len(X_train)) 每轮打乱。
  • 没有验证集、没有早停——和 AE 一样(p17)。GAN 的"收敛"靠人眼(p33 每 10 轮画样本)。
  • epochs=100 和 batch_size=512 是默认参数,p34 调用时没传——所以用的是默认值。如果要跑 50 轮,写 train_gan(..., epochs=50)。
  • history 字典的设计:gen_loss/dsc_loss 每轮 append 一个值(100 个),message/samples 每 10 轮 append 一次(10 个)——p36 画曲线用前两个,p35 看样本用后两个。
易错点 · 理解提示① 23 批(不是 22)——ceil 把最后 429 张也算一批。② end - start 在最后一批是 429,不是 512——传给 train_discriminator/train_generator 的 batch_size 都是 429。③ 每轮记录的是平均 loss(除以 n_batches),不是总和。④ gen_loss = dsc_loss = 0 是两个变量同时赋 0——不是元组。
p.33GAN 代码:更新训练历史(NUM_REPORTS=10)代码
GAN code example – updating training history
NUM_REPORTS = 10  # message and samples

def update_history(history, start_time, i, epochs, gen_loss,
                   dsc_loss, generator):
    history["gen_loss"].append(gen_loss)
    history["dsc_loss"].append(dsc_loss)
    if (i + 1) % (epochs // NUM_REPORTS) == 0:
        elapsed = time.time() - start_time
        message = \
            f"Epoch {i+1}/{epochs}, time elapsed: {elapsed:.1f}s" + \
            f", gen_loss: {gen_loss:.2f}, dsc_loss: {dsc_loss:.2f}"
        print(message)
        samples = generate_samples(generator, 10)
        plot_samples(samples)
        history["message"].append(message)
        history["samples"].append(samples)
核心概念update_history:每轮都 append 两个 loss;每 10 轮((i+1) % (epochs // NUM_REPORTS) == 0,即 epochs//10 = 10)额外做四件事:算已用时间 → 拼消息字符串 → print → 生成 10 张样本并画图 → 把消息和样本存进 history。这就是 p35 那 10 条消息和 10 组样本的来源。
详细讲解

前两行:history["gen_loss"].append(gen_loss)——每轮一个值,100 轮后是长度 100 的列表。p36 的曲线就是画这两个列表。

条件 (i + 1) % (epochs // NUM_REPORTS) == 0:epochs = 100、NUM_REPORTS = 10 → epochs // NUM_REPORTS = 100 // 10 = 10。i 从 0 开始,所以 i + 1 是"第几轮"(1–100)。当 i+1 是 10 的倍数(10、20、…、100)时触发——10 次。这就是为什么 p35 有 10 条消息(ep10 到 ep100),而不是 ep1 或 ep5。

消息字符串:f"Epoch {i+1}/{epochs}, time elapsed: {elapsed:.1f}s, gen_loss: {gen_loss:.2f}, dsc_loss: {dsc_loss:.2f}"——格式:轮次 / 总轮数、已用秒数(1 位小数)、G loss(2 位小数)、D loss(2 位小数)。行尾的 \ 是 Python 的续行符,让两个 f-string 拼成一行。p35 的 "Epoch 10/100, time elapsed: 79.0s, gen_loss: 0.65, dsc_loss: 0.11" 就是这个格式的输出。

print(message):打印到标准输出——在 Jupyter 里显示在 cell 下方。

samples = generate_samples(generator, 10);plot_samples(samples):生成 10 张假图(p30)并画出来(p15)。每 10 轮弹一次图——这就是 p35 截图里那 10 组样本。注意每次都是新采的噪声(generate_sample_inputs 内部 np.random.normal),所以每组样本的"内容"不同——只能看"整体质量"变化,不能跟踪"同一张图"的演变。

history["message"].append(message);history["samples"].append(samples):存起来——p35 的消息表和样本图可以从 history 里重新取出。samples 是 (10, 28, 28, 1) 的数组,10 组 → (10, 10, 28, 28, 1)。

一个潜在的小问题:如果 epochs 不能被 NUM_REPORTS 整除(如 epochs=95),epochs // 10 = 9,触发轮次是 9、18、…、90——最后一轮 95 不触发,但也不会报错。如果 epochs < 10,epochs // NUM_REPORTS = 0,% 0 会抛 ZeroDivisionError——讲义的 100 轮没问题。

题目 · Review 关联
  • "How many messages are printed?"——10(每 10 轮一次:ep10, 20, …, 100)。
  • "Why i + 1 instead of i?"——i is 0-based; i+1 gives the human-readable epoch number (1–100), so the check fires at 10, 20, … rather than 9, 19, …。
  • "What is the shape of history["samples"] after training?"——A list of 10 arrays, each (10, 28, 28, 1)。
  • "Modify to report every 5 epochs"——NUM_REPORTS = 20(100 // 20 = 5)。
  • p35 的消息表是本函数的输出——考"interpret the training history"时,要能把 gen_loss / dsc_loss 的数值和 p36 的曲线、p26 的五大困难联系起来。
必要扩展
  • 更稳健的写法:if (i + 1) % max(1, epochs // NUM_REPORTS) == 0——防止 epochs < 10 时的除零错误。
  • Unit 6 的 History 对象(fit 返回的)有 epoch 和 history 两个属性;这里手写的 history 字典是它的简化版——只有需要的四个键。
  • 如果想在训练结束后回放"样本演变":把 history["samples"] 的 10 组图用 matplotlib 的 animation 或 GIF 拼起来——每组是一行 10 张,10 组叠成 10 行,就是 p35 的截图。
  • Keras 的 Callback(Unit 7 的 EarlyStopping 就是一个 Callback)可以在 fit 里做同样的事;但 GAN 用 train_on_batch,不触发 Callback,所以只能手写在循环里。
易错点 · 理解提示① 触发条件是 (i+1) % 10 == 0——ep10、ep20…,不是 ep9、ep19(因为 i 从 0 开始)。② 每次画的样本是新采的噪声——不是固定一组。③ epochs // NUM_REPORTS 是整除(//),不是 /——100 // 10 = 10(整数),100 / 10 = 10.0(浮点,% 10.0 也能用但不优雅)。④ loss 每轮都记录(100 个),消息/样本每 10 轮记录(10 个)——两个频率不同。
p.34GAN 代码:整合(putting it all together)代码
GAN code example – putting it all together
X_train = load_and_prep_mnist("48")
generator = create_generator()
discriminator = create_discriminator()
gan = create_gan(generator, discriminator)
history = train_gan(generator, discriminator, gan, X_train)
核心概念五行入口:加载数据 → 建 G → 建 D → 组复合 GAN → 训练。全部用默认参数(epochs=100、batch_size=512)。create_discriminator 返回的 D 已经是 trainable=False,所以 create_gan 时 D 自动冻结。
详细讲解

五行的依赖关系:第 1 行独立;第 2、3 行独立(G 和 D 可以并行建);第 4 行依赖 2、3;第 5 行依赖 1–4。所以如果要在 Notebook 里分 cell 运行,1–3 可以一个 cell,4 一个 cell(看 gan.summary()),5 一个 cell(耗时 7.7 分钟)。

第 3 行的副作用:create_discriminator() 内部 model.trainable = False——这意味着从这一行开始,D 就是冻结的。第 4 行 create_gan 把 G 和 D 串起来,D 仍然是冻结的。第 5 行训练时,train_discriminator 每批临时打开 D、训练、再关上——train_generator 看到 D 是关的。

变量命名:generator、discriminator、gan、history——和 Unit 4–11 的 model、history 风格一致。gan 是复合模型,不是 GAN 算法本身——"GAN" 在代码里只是个变量名。

和 AE 入口的对比(p17):

AE(p17)GAN(p34)
数据load_and_prep_mnist("48")同
建模型encoder、decoder(p16)+ Sequential([e, d])create_generator()、create_discriminator()、create_gan()
编译compile(mse, adam)在 create 函数内(BCE, rmsprop)
训练fit(X, X, 100, 256)train_gan(..., 100, 512)
历史history.history["loss"](100 个)history 字典(4 个键)
用时约 1–2 分钟462.8s ≈ 7.7 分钟

运行后:generator 和 discriminator 是训练好的模型对象——p36 直接用 generator 生成最终样本。注意 train_gan 不返回模型,只返回 history——模型是原地修改的(Keras 的 train_on_batch 直接改权重)。

题目 · Review 关联
  • "Write the code to build and train a GAN"(Review #5 optional)——这五行 + 前面 p28–33 的函数定义就是完整答案。考试若只要求"整合",写这五行即可。
  • "Which line freezes the discriminator?"——None here; it is frozen inside create_discriminator() (p29).
  • "What are the default epochs and batch_size?"——100 and 512 (defined in train_gan's signature, p32)。
  • Unit 4–11 的 history = model.fit(...) 模式在这里变成 history = train_gan(...)——返回类型从 Keras History 变成普通字典。
必要扩展
  • 保存模型:generator.save("gan_gen.keras")——因为 train_gan 不保存,训练 7.7 分钟的成果要手动存。复合 gan 也可以存,但通常只需要 G。
  • 重新训练:如果再跑一次第 5 行,G 和 D 会从当前权重继续训练(不是重新开始)——因为 train_on_batch 原地更新。要从头训练,重新跑第 2–4 行。
  • Unit 7 Lab 的 set_random_seed(42)(在 load_and_prep_mnist 里)让数据加载可复现,但 GAN 训练涉及 np.random.normal(p30)和 Dropout 的随机性——两次运行的 gen_loss 曲线不会完全一样(p35 的数值是某一次运行的结果)。
易错点 · 理解提示① 五行的顺序:先建 G、D 再建 gan——反过来会报错(参数未定义)。② history 是字典不是 Keras History——画曲线用 history["gen_loss"],不是 history.history["loss"]。③ 训练好的是 generator 变量——p36 用它生成样本,不是 gan(gan 的输出是概率,不是图)。
p.35GAN 代码:训练历史(10 条消息 + 样本)★Review原图数据
GAN code example – training history (讲义截图:10 条 update_history 消息 + 10 组样本,两列排版,左列 ep10–50、右列 ep60–100)
ep10(噪点) ep60(8 4 8 4 8 4 8 4 8 4) ep20(可辨 2 4 8 9 4) ep70(4 8 8 8 8 4 4 4 4 8) ep30 / ep40 / ep50(4 8 混合,含 9 形) ep80 / ep90 / ep100(8 与 4 交替,ep90 有黑块) ep100(讲义最终样本):8 9 8 4 9 4 8 4 4 4 —— 只出现 4、8、9 三种(训练集只有 4 和 8) 示意图:按讲义 p35 截图的 10 组样本重绘;ep10 为噪点,ep20 起可辨,ep50 后以 4 与 8 为主、偶有 9 形混合体
图 12.P35 讲义 p35 训练历史重绘:每 10 轮一组 10 张样本。ep10 噪点 → ep20–40 可辨但杂(含 2、9 形)→ ep50 之后基本只剩 4、8(和 9 形混合),ep90 有一张黑块。
核心概念训练历史的 10 条消息(ep10 → ep100):gen_loss 0.65 → 1.15 → 1.35 → 1.39(峰) → 1.38 → 1.34 → 1.30 → 1.27 → 1.24 → 1.21;dsc_loss 0.11 → 0.30 → 0.37 → 0.41 → 0.45 → 0.48 → 0.50 → 0.52 → 0.53 → 0.55(单调升);每 10 轮约 42.6 秒,总 462.8 秒 ≈ 7.7 分钟。样本:ep10 噪点,ep20 起可辨,后期以 4 和 8 为主。
详细讲解

先把 10 条消息列成表(讲义截图两列排版:左列 ep10–50,右列 ep60–100):

Epochtime elapsedgen_lossdsc_loss样本观察
1079.0 s0.650.11一片噪点,几乎看不出数字
20123.3 s1.150.30可辨:2、4、8、9 形混杂
30165.9 s1.350.374 与 8 为主,有 9 形
40207.9 s1.390.414 8 交替,笔画清晰
50250.4 s1.380.458 4 4 8 4 4 8 2 4 4——有 2
60292.9 s1.340.488 4 8 4 8 4 8 4 8 4——近乎交替
70336.3 s1.300.504 8 8 8 8 4 4 4 4 8
80378.6 s1.270.528 4 4 4 4 8 4 8 4 4
90420.6 s1.240.533 4 8 4 1 3 4 4 8 8——有一张黑块
100462.8 s1.210.554 8 4 8 4 4 4 4 4 4(p36 另一组:8 9 8 4 9 4 8 4 4 4)

时间列:相邻两条消息间隔 = 10 轮的时间:44.3、42.6、42.0、42.5、42.5、43.4、42.3、42.0、42.2 秒——非常稳定,约 42.6 秒/10 轮 → 4.26 秒/轮 → 每轮 23 批 → 每批约 0.19 秒。总 462.8 秒 ≈ 7.7 分钟。第一段(ep1–10)44.3 秒略长,含首次编译/图构建的开销。

dsc_loss 单调上升:0.11 → 0.55,10 条没有一次下降。按 p23,D 的 loss 是"真图判真 + 假图判假"的 BCE——loss 上升意味着 D 越来越判不出假图,即 G 越来越好。但 0.55 仍低于 0.693(ln 2,D 完全随机猜的值)——说明 D 仍比"瞎猜"强一点,G 还没完全骗过它。

gen_loss 先升后降:0.65 → 1.39(ep40)→ 1.21。ep10 的 0.65 很低——不是因为 G 好,而是因为 D 很弱(dsc_loss 0.11 看似 D 很强?不——见下一段的解释)。这正是 p26 第 4 条"uninformative loss"的实例:ep10 的 0.65 不能和 ep100 的 1.21 直接比较,因为两个时期的 D 不同。

ep10 的"矛盾":dsc 0.11 但 gen 0.65?dsc_loss 0.11 说明 D 在"真图判真 + 假图判假"上做得很好(BCE 低)。按 p24,G 的 loss = −log D(G(z)),如果 D 把假图判得很好(D(G(z)) ≈ 0),G 的 loss 应该很大(如 4.6)——但 ep10 的 gen_loss 只有 0.65,意味着 D(G(z)) ≈ 0.5。原因:dsc_loss 是两次 train_on_batch 的平均——第一次(真图)D 已经学会判真(loss ≈ 0.02),第二次(假图)是在第一次更新之后训练的,D 刚更新过、对假图的判断还不稳定;而 gen_loss 是在 D 训练完、又用新噪声测的。再加上 p36 的曲线显示 gen_loss 在 ep2 冲到 2.25、ep8 跌到 0.62——ep10 的 0.65 是在一个谷底附近。两个 loss 的测量时机不同,数值不能直接互相验证。

样本的演变:ep10 噪点 → ep20 可辨但混杂(2、4、8、9)→ ep30–40 以 4、8 为主 → ep50 后 8 和 4 几乎交替出现 → ep90 出现一张黑块(训练不稳定的瞬间)。训练集只有 4 和 8(p14),所以生成结果只应是 4 和 8——但 ep20 的 2、9 和 ep100 的 9 是"4 和 8 的混合体"(G 在潜空间里把两类的特征混在一起)。样本的种类在收窄(从混杂到只剩 4/8)——这是 mode collapse 的轻度表现(p25–26)。

和 p26 五大困难的对照:① non-convergence——gen_loss 在 p36 曲线上震荡(峰 2.25、谷 0.62);② mode collapse——样本只有 4/8/9;③ vanishing gradients——初期 D 太强(dsc 0.07)、gen 冲到 2.25;④ uninformative——ep10 的 0.65 不代表 G 好;⑤ sensitive hyperparams——rmsprop、Dropout 0.5、batch 512 都是调出来的。一张截图把五条全占了。

题目 · Review 关联
  • Review #4 若考 "interpret the training history"——给一张类似的表,问"what can you conclude?":dsc_loss 单调升(D 越来越难分辨)、gen_loss 后期缓降、样本从噪声变清晰——但 gen_loss 不反映质量(uninformative),样本种类少(mode collapse)。
  • "Why is dsc_loss increasing? Is that bad?"——No. It means the discriminator finds it harder to tell fakes from reals, i.e., the generator is improving. It is not comparable to a classifier's validation loss.
  • "At ep100, dsc_loss = 0.55 < ln 2 ≈ 0.693. What does this tell you?"——The discriminator is still slightly better than random guessing; the GAN has not reached the theoretical equilibrium (p25).
  • "Compute the average time per epoch."——462.8 / 100 = 4.63 s;"per batch?"——4.63 / 23 ≈ 0.20 s。
  • "Explain why gen_loss at ep10 (0.65) is lower than at ep100 (1.21) although samples are much better at ep100."——Generator loss is measured against the current discriminator (uninformative loss, p26); the discriminator at ep10 was weak/unstable, so a low generator loss then does not indicate good samples.
必要扩展
  • 这组数值是某一次运行的结果(随机种子 42 固定了数据,但 GAN 训练仍有 Dropout 和 normal 噪声的随机性)——你跑一次不会得到完全相同的数字,但趋势(dsc 升、gen 先升后降、样本从噪到清)是一样的。
  • 样本中出现的"9"——G 没见过 9(训练集只有 4、8)。它生成 9 是因为 9 = "4 的上半部分 + 8 的下圈"——潜空间里 4 和 8 的簇之间的点解码出来就像 9。这是 GAN "学到特征组合"的证据,也是 mode collapse 的伴生现象。
  • ep90 的黑块:一张 28×28 几乎全黑的图——G 在那一批训练中"崩溃"了一下(可能是 D 刚好特别强、G 的梯度爆炸)。下一组(ep100)恢复正常——说明 GAN 的训练是"震荡中前进",不是单调改善。
  • 改进方向:用 WGAN(p39–50)能得到"有意义的 loss"——p49 的 gen_loss 从 −2036 单调升到 −210,真的反映样本质量在提升。
易错点 · 理解提示① dsc_loss 上升不是坏事——在 GAN 里它意味着 G 在进步。② gen_loss 低不代表样本好(ep10 的 0.65 vs ep100 的 1.21)。③ 10 条消息是每 10 轮一次(p33 的 NUM_REPORTS=10),不是每轮。④ 时间列的单位是秒,总 462.8 s ≈ 7.7 分钟(不是小时)。
p.36GAN 代码:生成样本与训练曲线★Review原图数据
GAN code example – generated samples, plot of training history
samples = generate_samples(generator, 10)
plot_samples(samples)

plt.figure(figsize=(15, 5))
plt.plot(history["dsc_loss"], label="discriminative loss")
plt.plot(history["gen_loss"], label="generative loss")
plt.legend()
plt.show();
讲义 p36 样本(上)与训练曲线(下,重绘) 8 9 8 4 9 4 8 4 4 4 (generate_samples(generator, 10)) 020406080100 0.00.51.01.52.0 ep2 ≈ 2.2 ep8 ≈ 0.62 ep5 ≈ 0.07 ep40 ≈ 1.39 ep100 1.21 ep100 0.55 交叉 ≈ ep12 discriminative loss generative loss 横轴:epoch(0–100,df.index 从 0 起);纵轴:每批平均 loss(0–2.0)
图 12.P36 讲义 p36 重绘:上方为 generate_samples(generator, 10) 的 10 张样本(8 9 8 4 9 4 8 4 4 4);下方为 history["dsc_loss"](蓝)与 history["gen_loss"](橙)的 100 个点。关键点:gen 峰 ep2≈2.2、谷 ep8≈0.62、ep40≈1.39、ep100 1.21;dsc 从 0.42 跌到 ep5≈0.07 后单调升到 0.55;两线在 ep≈12 交叉。
核心概念两段代码:生成样本——generate_samples(generator, 10) + plot_samples;画曲线——plt.figure(figsize=(15,5)),先画 dsc_loss 再画 gen_loss,label 给图例。曲线读法:橙线(gen)从 1.6 冲到 2.2、跌到 0.6、回升到 1.4、缓降到 1.2;蓝线(dsc)从 0.4 跌到 0.07、单调升到 0.55;两线在 ep≈12 交叉,之后橙在上、蓝在下。
详细讲解

代码:第一段和 p19 的 AE 生成几乎一样——只是 decoder 换成 generator,噪声从 uniform 换成 normal(p30)。第二段画图:plt.figure(figsize=(15, 5)) 宽 15 英寸、高 5 英寸——比 p17 的 (15, 3) 高一些,因为纵轴范围 0–2.2 需要空间。plt.plot(history["dsc_loss"], label="discriminative loss")——x 轴自动用 0…99(history["dsc_loss"] 是普通列表,没有 df.index+1 那步,所以从 0 开始,和 p17 的 AE 曲线从 1 开始不同)。图例顺序 = plot 顺序:蓝(dsc)在前、橙(gen)在后。

橙线(gen_loss)的四个阶段:

  • ep1–2:冲顶。1.6 → 2.25。D 在最初几轮进步飞快(蓝线跌到 0.07),G 被打得措手不及——"D 太强,G 梯度大"(p26 第 3 条的反面:本讲用 −log D(G(z)),D 强时 loss 高、梯度大,所以 G 能学)。
  • ep2–8:跳水。2.25 → 0.62。G 快速学会"画出有笔画的东西",D 瞬间分辨不出——G 的 loss 暴跌。
  • ep8–40:回升。0.62 → 1.39。D 重新学会分辨"G 的早期套路",G 又被逼着进步——loss 回升。这一段是"G 和 D 拉锯"。
  • ep40–100:缓降。1.39 → 1.21。双方都进步缓慢,趋于动态平衡。

蓝线(dsc_loss)的两个阶段:ep1–5 从 0.42 跌到 0.07(D 学会分辨噪声和数字——容易);ep5–100 从 0.07 单调升到 0.55(G 越来越好,D 越来越难分辨)。蓝线没有一次下降(ep5 之后)——这是"D 越来越难"的单调证据。

交叉点 ep≈12:之前蓝在下(D 的 loss 低 = D 强)、橙在上(G 的 loss 高 = G 弱);之后橙在下(G 的 loss 低)、蓝在上(D 的 loss 高)。但不要把它读成"G 赢了"——按 p24 的分析,G 的 loss 低只说明 D(G(z)) 大,而 D 的 loss 高说明 D 判不出假图——两者是同一件事的两个侧面。交叉点只是"两条线的数值相等"的位置,没有特别含义。

这张图是 p26 五大困难的可视化:non-convergence——橙线的三个转折(冲顶、跳水、回升)就是"震荡";uninformative——橙线在 ep8 的 0.62(最低)对应的是"早期套路",不是最好的样本,而 ep100 的 1.21(较高)对应的样本反而最好。橙线越低 ≠ 样本越好。

和 p17 AE 曲线的对比:AE 的 loss 从 0.06 单调降到 0.02——一条平滑的下降曲线,因为目标是固定的。GAN 的两条线都不单调——因为目标(对方)在动。这就是"合作"(AE)vs"对抗"(GAN)的区别在图上的表现。

题目 · Review 关联
  • "Sketch the training curves of a GAN and explain the shape."——画两条:D loss 先降后升、G loss 先升后降再缓降,两线交叉;解释:初期 D 学得快、G 梯度大;中期拉锯;后期动态平衡。
  • "Why does the generator loss peak at epoch 2?"——The discriminator learns fast in the first few epochs, so D(G(z)) drops and −log D(G(z)) spikes; the generator then quickly learns to produce structured images.
  • "Why is the generator loss at ep8 lower than at ep100 although samples at ep100 are better?"——Uninformative loss (p26): the generator loss is relative to the current discriminator, which is much stronger at ep100.
  • "What is the x-axis range?"——0 to 99 (list index), since history["gen_loss"] is a plain list; p17's AE plot used df.index + 1 so it starts at 1.
  • "Which line is plotted first / which colour?"——dsc_loss first (default colour 1 = blue in matplotlib's tab10); gen_loss second (orange).
必要扩展
  • matplotlib 默认颜色循环 tab10:第 1 条蓝 #1f77b4、第 2 条橙 #ff7f0e——和讲义截图一致(蓝 dsc、橙 gen)。如果先画 gen 再画 dsc,颜色会反过来。
  • p35 的 10 条消息和 p36 的曲线是同一次训练的两个视图:p35 的 ep40 gen 1.39 = 曲线上 x=39 的橙点;ep100 的 1.21 = x=99 的橙点。可以互相验证。
  • 更精细的诊断图:除了 loss,还可以每 10 轮算一次"D 在真图上的准确率"和"D 在假图上的准确率"——理想均衡是两者都 50%。本讲只画 loss,但 p25 的"50%"理论就是这两个准确率。
  • WGAN(p50)的曲线形状完全不同——两条线都在负值区、单调趋 0、没有交叉震荡——这是 Wasserstein 距离"有意义"的直观证据。
易错点 · 理解提示① 蓝线是 dsc(先画)、橙线是 gen(后画)——别记反。② x 轴从 0 开始(不是 1)——因为没用 df.index + 1。③ 橙线最低点(ep8)不是样本最好的时候——G 的 loss 不反映质量。④ 两线交叉(ep≈12)没有特殊含义——别把它当作"收敛点"。
p.37The end(正文结束,附录 WGAN 在后)结尾
The end
核心概念"The end" 标记正文结束——生成建模(p3–8)、自编码器(p9–19)、GAN(p20–36)三部分讲完。后面 p38–50 是附录:Wasserstein GAN 的原理和代码。
详细讲解

这页的意思是"考试范围到这里"——Course Review p10 的五个考点(生成/判别定义、AE 原理、GAN 原理、GAN 困难、GAN 代码 optional)全部在 p1–37 内。附录 WGAN(p38–50)不在 Review 里。

但建议仍然读附录:① 它是理解 p26 第 4 条"uninformative loss"的最佳对照——WGAN 的 loss 是"有意义的";② 它的代码和 p28–36 几乎一样,只有五处改动(p40)——读一遍等于复习了 GAN 代码;③ 如果考试出"modify code to improve GAN training","改用 Wasserstein loss" 是一个高分答案。

到这里回顾一下正文的三段结构:AE(p9–19)——一个网络、一个损失、fit 训练、用 MSE 学重建;GAN(p20–36)——两个网络、两个损失、手写循环、用对抗学生成。两者都是"向量 → 图"的解码器/生成器,但学习信号完全不同。

题目 · Review 关联
  • Review p10 的五个考点覆盖 p1–37;p11 的答题说明(短题 state/determine/name,长题 modify code/describe/explain/justify)——"The end" 之后的内容不会以"必答题"出现。
  • 试卷答案(2026 Autumn release)中没有 Unit 12 的题目——本讲是首次进入考核范围,Review 列表就是范围。
必要扩展
  • Unit 12 是本课程最后一次讲新内容——之后是 Project 截止(12/4)和期末考。生成模型这一讲和前面 11 讲的关系:它复用了 Dense/Conv2D/BN/Dropout(Unit 4、7、8)、MNIST 加载(Unit 5)、训练曲线(Unit 6)、CNN 结构(Unit 9),只是把"目标"从判别换成了生成。
易错点 · 理解提示"The end" 不等于"后面不用看"——附录的 WGAN 代码(p44–48)和正文 GAN 代码(p28–34)的差异只有五处,对照阅读是复习 GAN 代码的高效方法。
p.38附录分节页:Wasserstein GANs分节附录
Appendix: Wasserstein GANs
核心概念进入附录:Wasserstein GAN(WGAN)——对 GAN 做五处小改动,换来有意义的损失和更稳定的训练。原理 p39–42(4 页)+ 代码 p43–50(8 页)。
详细讲解

附录和正文的对应关系:p39(WGAN 简介)↔ p21(GAN 定义);p40(五改动)↔ p23–24(训练 D/G);p41(Wasserstein 损失)↔ p24(BCE);p42(WGAN-GP)↔ p26(困难的进一步解决)。代码部分 p44–48 和 p28–34 逐页对应——差异只有 p40 列的五处。

读附录的正确心态:它不是新模型,而是对 GAN 的"打补丁"。补丁的动机来自 p26 的第 1、4 条困难(non-convergence、uninformative loss)——WGAN 的论文标题就是 "Wasserstein GAN: Toward Principled Methods for Training Generative Adversarial Networks"(走向有原则的方法)。

Course Review 不包含附录——但如果考"propose an improvement to the GAN in the lecture",WGAN 的五改动(p40)就是最好的答案。

题目 · Review 关联
  • Review p10 没有 WGAN——期末考不会直接考附录;但 p26 "Difficulties" 的延伸题("How can these difficulties be addressed?")可以答 WGAN。
  • 试卷答案中没有 WGAN 相关题目。
必要扩展
  • WGAN 2017 年 1 月放上 arXiv,到 2017 年 12 月 WGAN-GP 出现——不到一年就有了改进版。这是 GAN 研究的典型节奏:2014 原始 GAN → 2015 DCGAN → 2017 WGAN / WGAN-GP / ProgGAN → 2018 SAGAN / BigGAN → 2019 StyleGAN → 2020 后扩散模型接棒。
易错点 · 理解提示"Appendix" 在讲义里意味着"讲师不打算在课上讲"——但讲义把 8 页代码都给了,说明希望你课后能读懂。期末复习优先级:p40 五改动 > p41 Wasserstein 损失 > p42 WGAN-GP > 代码细节。
p.39WGAN 简介(Arjovsky 2017 / critic / 两大改进)附录
Wasserstein GANs Arjovsky et al, 2017, https://arxiv.org/abs/1701.07875v3  The Wasserstein GAN, or WGAN, makes a few changes to GANs to stabilize training  Two improvements of training reported ➢ A meaningful loss metric that correlates with the generator's convergence and sample quality ➢ Improved stability of the optimization process  The discriminator in WGAN is called the critic
核心概念WGAN(Arjovsky 2017)对 GAN 做少量改动以稳定训练。报告了两大改进:① 有意义的损失——与生成器的收敛程度和样本质量相关;② 优化过程更稳定。WGAN 里的判别器叫 critic(评论者)。
详细讲解

"A few changes":p40 列了五条——换损失函数、标签 ±1、去 sigmoid、裁剪权重、critic 多训几次。没有改网络结构(生成器完全一样,判别器只去掉一个 sigmoid)。这是 WGAN 最漂亮的地方:理论上的大改动(从 JS 散度换成 Wasserstein 距离),工程上只是几行代码。

"A meaningful loss metric"——针对 p26 第 4 条。GAN 的 gen_loss 是"相对当前 D"的,不可跨轮比较;WGAN 的 loss 是 Wasserstein 距离的(负)估计——它衡量的是生成分布和真实分布的距离,与 D 无关。loss 越低 = 分布越近 = 样本越好。p49 的 gen_loss 从 −2036 单调升到 −210,确实和样本质量同步改善——这就是"correlates with sample quality"的证据。

"Improved stability"——针对 p26 第 1、3 条。理论原因:当两个分布没有重叠(训练初期,G 输出噪声、和真实数据完全不重叠)时,JS 散度(GAN 的隐含距离)是常数 log 2、梯度为零;Wasserstein 距离在这种情况下仍然平滑变化、梯度非零。所以 WGAN 在初期也能给 G 提供有效的学习信号——p50 的曲线没有 p36 那种冲顶跳水的震荡。

"Critic" 这个名字:判别器(discriminator)判"真/假"——一个二分类;critic 给一个分数(score)——一个实数(−∞, +∞),表示"有多真"。它不输出概率,所以不叫"判别",叫"评论"。这个改名对应 p41 的"去掉 sigmoid"。

和 GAN 的术语对照:

GANWGAN
判别器名字discriminatorcritic
判别器输出D(x) ∈ (0, 1),概率critic(x) ∈ (−∞, +∞),分数
标签真 1 / 假 0真 +1 / 假 −1
损失binary cross-entropyWasserstein(−mean(y·p))
权重约束无裁剪到 [−c, c]
每批 D 更新次数1(两次 train_on_batch)3(p47)
loss 含义相对当前对手,不可比分布距离的估计,可比
题目 · Review 关联
  • Review 不直接考,但 "State TWO improvements of WGAN over GAN"——"a meaningful loss metric correlating with convergence/sample quality" 和 "improved stability"。两条照背。
  • "What is the discriminator called in a WGAN?"——The critic。
  • Review #4 的延伸:"How can the uninformative generator loss be addressed?"——Use the Wasserstein loss (WGAN), which estimates the distance between distributions and correlates with sample quality.
必要扩展
  • Wasserstein 距离也叫 Earth Mover's distance(推土机距离)——直觉:把分布 pg 的"土"搬成 pdata 的形状,最少要搬多远。两个不重叠的分布之间,EM 距离是它们之间的间隔——平滑、非零;JS 散度则是常数 log 2——零梯度。这是 WGAN 论文的核心论证。
  • 论文里的实验:在两个不重叠的高斯分布之间,JS 散度的梯度处处为零,而 EM 距离的梯度处处非零且指向正确方向——这张图是 WGAN 最著名的插图。
  • "Critic" 的另一个含义:在 RL 里 critic 是价值函数(评估状态好坏)——同样是"打分不分类"的意思。
易错点 · 理解提示① WGAN 没有改生成器——只改了判别器(去 sigmoid)和训练方式。② "A few changes" = p40 的五条,不是"一个小改动"。③ 两大改进对应 p26 的第 4 条(meaningful loss)和第 1 条(stability)——不是五条全解决(mode collapse 仍可能发生)。
p.40WGAN 对 GAN 的改动(Wasserstein 损失 / ±1 标签 / 去 sigmoid / 裁剪 / 多训 critic)附录五改动
WGAN changes to GAN  Use the Wasserstein loss  Perform training using labels of 1 for real images and -1 for fake images (instead of 1 and 0)  Remove the sigmoid activation in the output layer of the critic  Clip the weights of the critic after each update in training  Train the critic multiple times for each update of the generator
核心概念WGAN 的五个改动(必背顺序):① 用 Wasserstein 损失;② 标签改为真 +1 / 假 −1(原来是 1 / 0);③ 去掉 critic 输出层的 sigmoid;④ 每次更新后裁剪 critic 的权重;⑤ 每更新一次生成器,critic 训练多次。
详细讲解

五条改动不是独立的,而是一条因果链:换损失(①)→ 需要新标签(②)→ 需要去 sigmoid(③)→ Wasserstein 距离需要 Lipschitz 约束(④)→ critic 可以放心多训(⑤)。逐条看:

#改动GAN(p28–31)WGAN(p44–47)为什么
①损失函数binary_crossentropywasserstein = mean(y·p)让 loss 成为分布距离的估计(p39)
②标签真 1、假 0真 +1、假 −1配合 ①:loss = mean(real) − mean(fake) 需要正负对称
③critic 输出Dense(1, sigmoid)Dense(1),无激活分数需要 (−∞, +∞),sigmoid 把它压到 (0,1) 就不是分数了
④权重裁剪无np.clip(w, −c, c),c = 0.05强制 Lipschitz 约束(p41)
⑤critic 训练次数每批 1 次每批 3 次critic 越强、估计越准;GAN 里 D 太强会梯度消失,WGAN 不会

① → ② 的推导(p41 详述):Wasserstein 损失 = −(1/n)Σ yi·pi。对真图 y=+1:loss = −mean(p);对假图 y=−1:loss = +mean(p)。Keras 最小化 loss → 真图的分数被推高、假图的分数被压低 → mean(real) − mean(fake) 变大 → 这正是 Wasserstein 距离的 Kantorovich-Rubinstein 对偶形式。如果标签仍是 1/0,假图的 loss 恒为 0——没有训练信号。所以 −1 是 Wasserstein 损失的必然要求。

② → ③ 的推导:如果保留 sigmoid,p ∈ (0,1),mean(real) − mean(fake) 最大只能是 1——critic 的"分数"被限制在一个小区间,无法表达"分布距离有多大"。去掉 sigmoid 后 p 可以是任意实数(p49 的 −2036 到 −28),才能当距离用。

③ → ④ 的推导:Kantorovich-Rubinstein 对偶要求 critic 是 K-Lipschitz 的(输入变化 1,输出变化不超过 K)——否则 mean(real) − mean(fake) 可以被推到无穷大,不再是"距离"。裁剪权重到 [−c, c] 是最简单的强制 Lipschitz 的方法(权重有界 → 每层的变化率有界 → 整体 Lipschitz)。

④ → ⑤ 的推导:在 GAN 里 D 太强会导致 G 梯度消失(p26 第 3 条),所以 D 只能训练一次;在 WGAN 里 loss 是线性的 mean(y·p)——critic 再强,G 的梯度也不消失(不是 sigmoid 的饱和区)。所以 critic 可以多训(3 次)以得到更准的距离估计——"no need to balance the training of the critic and generator"(p41)。

本讲代码里的五个数字:标签 −1(p46)、clip_max = 0.05(p46)、critic ×3(p47)、无 sigmoid(p45)、wasserstein 损失(p44)。注意 p41 文字说裁剪 [−0.01, 0.01],但 p46 代码用 0.05——讲义内部不一致,考试时以题目给的为准。

题目 · Review 关联
  • "State the changes WGAN makes to GAN"——五条照背,最好带上"为什么"(上表的最后一列)。
  • "Why are labels −1 instead of 0 for fake images in WGAN?"——With the Wasserstein loss −mean(y·p), a label of 0 would give zero loss for fakes (no training signal); −1 makes the loss push fake scores down, so mean(real) − mean(fake) is maximized.
  • "Why remove the sigmoid?"——The critic must output an unbounded score so the loss can measure distribution distance; sigmoid caps it at 1.
  • "Why clip the critic's weights?"——To enforce the Lipschitz constraint required by the Kantorovich-Rubinstein duality.
  • "Why can the critic be trained more times than the generator?"——The Wasserstein loss is linear in the critic output, so a stronger critic gives a better distance estimate without vanishing gradients for the generator.
  • Review #5 的 "modify code" 若出 "convert the GAN code to a WGAN"——五处改动各一行:loss=wasserstein、y_fake=−np.ones、Dense(1) 无激活、clip 循环、for _ in range(3)。
必要扩展
  • 五条改动的"最小集":其实 ①②③④ 是必需的(缺一个 Wasserstein 距离就不成立),⑤ 是"可以这么做"而不是"必须"。WGAN 论文的实验用 critic ×5(小的数据集)或 ×100(大的);本讲用 3。
  • 裁剪的副作用:权重被压到 [−0.05, 0.05] 后,critic 的容量下降(相当于权重很小、网络"变弱");而且裁剪是一个硬截断,梯度在边界处不连续。这就是 WGAN-GP(p42)用梯度惩罚代替裁剪的动机。
  • p46 的 clip_max=0.05 是函数默认参数——如果想试 [−0.01, 0.01](p41 的文字值),调用时传 clip_max=0.01。
易错点 · 理解提示① 五条改动的顺序:损失 → 标签 → sigmoid → 裁剪 → 多训——按因果链记,不易漏。② 标签是 +1 / −1,不是 1 / 0 也不是 +1 / 0。③ 裁剪的是 critic 的权重(每一层的核和偏置都裁),不是生成器的、不是梯度的。④ "多训 critic" 是每批 3 次(本讲),不是"多训几轮"。
p.41Wasserstein 损失(−mean(y·p) / Lipschitz 约束 / 裁剪 [−0.01, 0.01])附录公式
Wasserstein loss  The Wasserstein loss function is defined as −(1/n) Σi=1n yi × pi ➢ Require the labels yi to use values of 1 and -1 ➢ Require to enforce the Lipschitz constraint, e.g. by clipping the critic's weights within [−0.01, 0.01]  Removing the sigmoid activation in the output layer produces the output range (−∞, ∞), thus the name critic  No need to balance the training of the critic and generator, so the critic can be trained multiple times to supply accurate measurement in generator training
核心概念Wasserstein 损失 = −(1/n) Σi yi·pi(代码:backend.mean(y_true * y_pred))。两个要求:① 标签 y 取 +1 / −1;② 强制 Lipschitz 约束——例如把 critic 的权重裁剪到 [−0.01, 0.01](p46 代码用 0.05)。去掉 sigmoid 后输出范围 (−∞, ∞)——所以叫 critic。critic 和生成器不需要平衡,critic 可以多训以提供准确的度量。
详细讲解

公式逐项:yi 是标签(+1 真 / −1 假),pi 是 critic 对第 i 个样本的输出(分数),n 是样本数。backend.mean(y_true * y_pred) 就是这个公式——Keras 的损失函数签名固定是 (y_true, y_pred),返回一个标量,Keras 会最小化它。

为什么是"负号":Keras 最小化 loss。我们希望 critic 最大化 mean(real) − mean(fake)(让真图分数高、假图分数低)。加负号后,"最小化 −[mean(real) − mean(fake)]" = "最大化 mean(real) − mean(fake)"。

代入标签验证:

样本yloss 贡献 = −y·p最小化 loss 的方向
真图+1−pp → 大(分数被推高)
假图−1+pp → 小(分数被压低)

所以 critic 训练后,mean(real) 高、mean(fake) 低,两者之差 = Wasserstein 距离的估计。这就是 Kantorovich-Rubinstein 对偶:W(pdata, pg) = sup‖f‖L≤1 [Ex~data f(x) − Ez f(G(z))]——在所有 1-Lipschitz 函数 f 中,找让"真图期望 − 假图期望"最大的那个,最大值就是 Wasserstein 距离。critic 就是在学这个 f。

对生成器的影响:训练 G 时,复合模型 Sequential([G, critic]) 的输入是噪声、标签 +1(p46 的 train_wgan_generator 直接调用 train_generator,y = ones)。loss = −mean(critic(G(z))),最小化它 → critic(G(z)) 被推高 → 假图的分数接近真图的分数 → Wasserstein 距离缩小。G 的 loss 就是 −(假图分数的均值)——这就是 p49 的 gen_loss(−2036 → −210)。它越接近 0,假图分布越接近真图分布——有意义的 loss。

为什么需要 Lipschitz 约束:如果没有约束,critic 可以把真图分数推到 +∞、假图分数推到 −∞——loss 变成 −∞,但那不是"距离",而是无意义的发散。Lipschitz 约束(‖f‖L ≤ K)让 f 不能"太陡"——两个分布之间的分数差被限制在一个和"实际距离"成正比的范围内。裁剪权重是最简单的实现:每层权重 ‖W‖ ≤ c → 每层的 Lipschitz 常数有界 → 复合后有界。

裁剪范围 [−0.01, 0.01] vs 0.05:讲义 p41 的文字是 [−0.01, 0.01],p46 的代码 clip_max=0.05——5 倍差异。WGAN 论文用的是 0.01(c=0.01);讲义代码可能调过。两个值都能工作,但裁剪越大、critic 容量越大、Lipschitz 约束越松。考试时按题目给的值。

"No need to balance":GAN 里 D 太强 → G 梯度消失,所以 D 只能训一次;WGAN 里 G 的 loss 是 线性的(−mean(critic(G(z))),没有 sigmoid/log 的饱和),critic 再强,G 的梯度 ‖∂critic/∂G‖ 仍然非零(只是被 Lipschitz 常数限制上界)。所以 critic 可以多训(本讲 3 次)来得到更准的距离估计—— critic 越准,G 的梯度方向越可靠。

"Thus the name critic":sigmoid 把输出限制在 (0,1)——可以解释为"概率",所以叫"判别器";去掉后输出是实数——不能解释为概率,只能解释为"分数",所以改叫"评论者"。

题目 · Review 关联
  • "Write the Wasserstein loss function."——L = −(1/n) Σ yi·pi,or def wasserstein(y_true, y_pred): return backend.mean(y_true * y_pred)(p44)。
  • "Given y_true = [1, 1, −1, −1] and y_pred = [5, 3, −2, 1], compute the loss."——−(1/4)(1·5 + 1·3 + (−1)(−2) + (−1)(1)) = −(1/4)(5+3+2−1) = −9/4 = −2.25。
  • "Why must the labels be ±1?"——With y=0 for fakes, the fake loss term is zero (no signal); with −1, minimizing the loss pushes fake scores down, maximizing mean(real) − mean(fake).
  • "Why is clipping needed?"——To enforce the Lipschitz constraint required by the Kantorovich-Rubinstein duality; otherwise the critic could push scores to ±∞.
  • "Why can the critic be trained more without hurting the generator?"——The loss is linear (no sigmoid saturation), so the generator's gradient does not vanish.
  • 注意讲义内部差异:p41 文字 [−0.01, 0.01],p46 代码 clip_max=0.05——若题目问"what clip value is used in the lecture code",答 0.05。
必要扩展
  • Wasserstein 距离的直觉:两个土堆 pdata 和 pg,把 pg 搬成 pdata 的最少"搬运量 × 距离"。当 pg 是一团噪声(离 pdata 很远),W 很大;当 pg ≈ pdata,W ≈ 0。critic 的 mean(real) − mean(fake) 就是这个 W 的下界估计。
  • 为什么 GAN 的 JS 散度在分布不重叠时梯度为零:JS 散度 = (1/2)KL(p‖m) + (1/2)KL(q‖m),当 p、q 不重叠时最优 D 处处 0 或 1,JS = log 2 是常数——梯度为零。这是 Arjovsky 2017 论文的理论核心,解释了 GAN 训练初期(G 输出噪声、和真实数据不重叠)为什么 G 学不动。
  • Lipschitz 约束的其他实现:WGAN-GP(梯度惩罚,p42)、谱归一化(Miyato 2018,每层除以最大奇异值)、Weight normalization(Salimans 2016)。
  • 本讲 p49 的 dsc_loss 是 −2036(critic loss)——这个大数值来自"无 sigmoid + 权重裁剪 0.05":critic 输出的分数范围可以是几千。换成 0.01 裁剪,分数范围会小 5 倍左右。
易错点 · 理解提示① 公式的负号:loss = −mean(y·p),不是 +mean(y·p)——Keras 最小化,所以要负号。② 标签 −1 是对假图的——别写成真图 −1。③ 裁剪范围:文字 0.01、代码 0.05——两个都记住,考试看题目问的是哪个。④ "Lipschitz" 约束是对 critic 的,不是对生成器的。
p.42带梯度惩罚的 WGAN(WGAN-GP,Gulrajani 2017)附录
WGAN with gradient penalty  Gulrajani et al, 2017, https://arxiv.org/abs/1704.00028v3  WGAN with gradient penalty, or WGAN-GP, enhances WGAN to apply a gradient norm penalty to enforce the Lipschitz constraint ➢ Instead of clipping the weights  Changes to the WGAN ➢ Add a gradient penalty term in the critic loss function ➢ Do not clip the weights of the critic ➢ Do not use batch normalization in the critic
核心概念WGAN-GP(Gulrajani 2017):用梯度范数惩罚(gradient penalty)代替权重裁剪来强制 Lipschitz 约束。对 WGAN 的三处改动:① 在 critic 损失里加一个梯度惩罚项;② 不再裁剪权重;③ critic 里不用 BatchNormalization。
详细讲解

为什么要改:WGAN 的权重裁剪(p41 ④)有两个问题——① 它是硬截断:权重撞到边界 ±c 后,梯度要么被截掉、要么把权重推回,优化路径不光滑;② 它让 critic 容量下降:所有权重被压到很小(±0.01 或 ±0.05),网络"表达力"被人为削弱,论文称之为 "underfitting"(即便在 MNIST 上)。WGAN-GP 的思路:不限制权重本身,而是限制梯度——Lipschitz 约束的本意就是"梯度范数 ≤ K",直接惩罚梯度更贴近本意。

梯度惩罚的公式:在 critic loss 里加 λ·E[(‖∇x̂ critic(x̂)‖2 − 1)²],其中 x̂ 是真图和假图的随机插值(x̂ = εx + (1−ε)G(z),ε~U[0,1]),λ 通常取 10。直觉:在真假分布"之间"的点上,要求 critic 的梯度范数接近 1(1-Lipschitz 的最优情况)。这样既不需要裁剪,又比裁剪更准确地约束了 Lipschitz 常数。

三处改动:

WGAN(p44–47)WGAN-GP
Lipschitz 约束裁剪权重到 [−c, c]梯度惩罚 λ(‖∇critic‖−1)²
critic loss−mean(y·p)−mean(y·p) + λ(‖∇critic‖−1)²
裁剪每次更新后 clip不裁
critic 的 BN本讲 critic 没有 BN(只有 Dropout)不用 BN

"Do not use batch normalization"的原因:梯度惩罚是逐样本计算的(对每个 x̂ 算 ∇critic(x̂)),但 BN 的统计量是跨 batch的——同一个样本在不同 batch 里的输出不同,梯度就不是"这个样本的梯度"了。所以 WGAN-GP 的 critic 不能有 BN;替代方案是 Layer Normalization。本讲的 critic(p45)本来就没有 BN(只有 Conv + Dropout),所以这一条对本讲代码没有实际影响——但如果 critic 用了 BN(很多 DCGAN 判别器有),就必须去掉。

讲义对 WGAN-GP 的定位:只此一页——不要求代码。考场上若问"how to improve WGAN",答:"Replace weight clipping with a gradient penalty on random interpolations between real and fake samples (WGAN-GP); do not clip weights; do not use batch normalization in the critic."

题目 · Review 关联
  • "What is WGAN-GP and why was it proposed?"——WGAN with gradient penalty: it enforces the Lipschitz constraint via a gradient norm penalty instead of weight clipping, avoiding the capacity loss and optimization difficulties caused by clipping.
  • "State the changes WGAN-GP makes to WGAN."——(1) add a gradient penalty term to the critic loss; (2) do not clip the critic's weights; (3) do not use batch normalization in the critic.
  • "Why no batch normalization in WGAN-GP's critic?"——BN couples samples within a batch, but the gradient penalty is computed per sample on interpolated points, which would be inconsistent.
  • Review 不考 WGAN-GP;它只是 p26 第 5 条"敏感超参"的又一层解决思路。
必要扩展
  • WGAN-GP 之后:2017–2018 年 SAGAN(自注意力)、BigGAN(大 batch + 正交正则)、StyleGAN(风格调制 + PGGAN 多尺度)——它们都在 WGAN-GP 或谱归一化的基础上做改进。GAN 的"训练稳定性"问题到 2019 年基本被工程手段压住,但 mode collapse 仍是隐患。
  • 梯度惩罚的"插值点"为什么要随机:真实分布和生成分布之间的"空间"是 critic 最容易违反 Lipschitz 的地方(因为它在训练数据之外),所以惩罚要覆盖那里——随机插值就是采样这个区域。
  • 本讲 p45 的 critic 有 Dropout(0.5) 但没有 BN——所以"WGAN-GP 不用 BN"对讲义代码是 no-op。但如果有人按 p28 生成器的样子给 critic 加 BN(Conv→BN→LReLU),就必须知道这个约束。
易错点 · 理解提示① WGAN-GP 的三改动:加梯度惩罚、不裁剪、不用 BN(critic)——注意两个"不"字。② 梯度惩罚是对 critic 输出对输入的梯度(∇x̂ critic),不是对权重的梯度。③ WGAN-GP 和 WGAN 是两个东西——WGAN 用裁剪(本讲代码),WGAN-GP 用梯度惩罚(讲义只提概念)。
p.43附录分节页:WGAN code example分节附录
Appendix: WGAN code example
核心概念进入 WGAN 代码段(p44–50,8 页):Wasserstein 损失 + 生成器(p44)→ critic + WGAN(p45)→ 训练 critic 和 G(p46)→ 整个训练循环(p47)→ 整合(p48)→ 结果(p49–50)。
详细讲解

和 GAN 代码(p28–36)比,WGAN 代码少了三页——因为 load_and_prep_mnist、plot_samples(p14–15)、generate_sample_inputs、generate_samples(p30)、update_history(p33)全部复用,不用重写。需要重写的只有:损失函数(新增 1 个)、生成器(直接 return create_generator())、critic(去 sigmoid + 换损失)、训练 critic(−1 标签 + 裁剪)、训练循环(critic ×3)。

阅读方法:把 p44–48 和 p28–34 并排打开,逐行找差异——差异正好就是 p40 的五条改动。这是复习"五改动"最高效的方法。

题目 · Review 关联
  • Review 不考 WGAN 代码;但 Review #5 的 "modify code" 若出 "convert the GAN to a WGAN",p44–47 就是标准答案。
必要扩展
  • 工程上的好习惯:讲义把可复用的工具函数(数据、画图、采样、历史)只写一次,模型和训练函数按变体各写一套——这是"组合优于复制"的体现。你的 Project 如果要比较多个模型,也应这样组织代码。
易错点 · 理解提示分节页不考;但注意 p44 的 create_wgan_generator() 只有 return create_generator() 一行——生成器完全没变。
p.44WGAN 代码:Wasserstein 损失与生成器代码
WGAN code example – Wasserstein loss, creating generator
from tensorflow.keras import backend

def wasserstein(y_true, y_pred):
    return backend.mean(y_true * y_pred)

def create_wgan_generator():
    return create_generator()
核心概念wasserstein(y_true, y_pred) = backend.mean(y_true * y_pred)——p41 公式 −(1/n)Σyipi 的负号被省掉了(Keras 最小化,所以等价于最大化 mean(y·p),再等价于最小化 −mean(y·p))。create_wgan_generator() 直接返回 create_generator()——生成器完全不变。
详细讲解

from tensorflow.keras import backend:Keras 的后端模块(TensorFlow 后端),提供张量运算——backend.mean 相当于 tf.reduce_mean。用 backend 而不是直接用 tf 是为了后端无关(历史上 Keras 支持 Theano / CNTK)。

自定义损失函数的签名:Keras 要求 loss(y_true, y_pred) 返回一个标量张量(batch 内已平均)。y_true 形状 (n, 1)、y_pred 形状 (n, 1)(Dense(1) 的输出),逐元素相乘后求均值——标量。

负号去哪了:p41 的公式是 −(1/n)Σy·p;代码是 +(1/n)Σy·p。为什么都对?因为 Keras 最小化 loss:

  • 按 p41 公式:min −mean(y·p) → max mean(y·p) → 真图(y=+1)p 推高、假图(y=−1)p 压低。✓
  • 按代码:min +mean(y·p) → 真图(y=+1)p 压低、假图(y=−1)p 推高。✗ 方向反了!

等等——代码里没有负号,训练方向是反的?不是。请看 p46:y_real = np.ones(batch_size)、y_fake = -np.ones(batch_size)——和 p41 一致。那 min mean(y·p) 就是"压低真图分数、推高假图分数"——这正是 GAN 判别器的反方向。但 critic 的"分数"本身没有"必须是正的"这个约定——它的绝对方向是任意的!只要 critic 和 G 的训练一致即可。看 p46 的 train_wgan_generator → 调用 train_generator(p31)→ y = np.ones → gan.train_on_batch(X, y),gan 用 wasserstein 损失 → min mean(+1 · critic(G(z))) → 把假图分数压低。而 critic 训练时把真图分数压低、假图分数推高——两者方向相反:critic 要"真低假高",G 要"假低"(向真靠拢)。所以整体是"critic 学一个函数 f 让 mean(f(real)) < mean(f(fake)),G 让 f(fake) 变小"——令 f' = −f,就是标准形式"真高假低、G 让假变高"。整个系统差一个全局符号,数学上等价。这就是为什么代码省掉负号也能工作:p49 的 loss 都是负数(−2036 → −210),对应 f' = −f 下"真高假低"的正距离 2036 → 210。

更简洁的理解:把代码里的 critic 输出读作"负分数"——critic 训练让真图的负分数更负(低)、假图的负分数更不负(高);G 训练让假图的负分数更负(向真图靠拢)。负分数的差 = −W 距离。p49 的 gen_loss = −2036 意味着 W ≈ 2036(很大),−210 意味着 W ≈ 210(缩小了 10 倍)——分布靠近了。

考场上怎么写:如果题目要求"write the Wasserstein loss"——写 return backend.mean(y_true * y_pred)(讲义原文);如果题目问"why is there no minus sign"——答"Keras minimizes; with labels +1/−1 the overall sign convention of the critic's score is arbitrary and consistent between critic and generator, so the loss is equivalent to the negative Wasserstein estimate up to sign"。

create_wgan_generator:一行 return create_generator()——p28 的生成器(Dense→Reshape→UpSampling→Conv2D×3,参数 108,092)。WGAN 不改生成器,所以直接复用。写成一个独立函数(而不是直接 generator = create_generator())是为了和 GAN 代码的调用形式对称(p48:create_wgan_generator()、create_wgan_discriminator()、create_wgan())。

题目 · Review 关联
  • "Write a Keras custom loss for the Wasserstein distance."——def wasserstein(y_true, y_pred): return backend.mean(y_true * y_pred)。
  • "Is the generator changed in WGAN?"——No; create_wgan_generator() simply returns create_generator() (108,092 params)。
  • "What is the role of backend.mean?"——It averages over the batch so the loss is a scalar tensor.
  • Review #5 的 "modify code" 若出 "change the loss function to Wasserstein"——三行:import backend、def wasserstein、compile(loss=wasserstein)。
必要扩展
  • 自定义损失的注册:如果要把模型保存为 .h5 并用 load_model 加载,需要 @keras.saving.register_keras_serializable()(Keras 3)或传 custom_objects={"wasserstein": wasserstein}——本讲没保存模型,不涉及。
  • Keras 3(TF 2.16+)里 tensorflow.keras 已改为 Keras 3 包,backend.mean 仍然存在(keras.backend.mean),但 set_random_seed 的位置变了(keras.utils.set_random_seed 仍在)。讲义代码在 TF 2.x 下运行。
  • 关于"负号"的更深层:WGAN 原论文的算法 1 写的是 gw ← optimizer(critic loss = −mean(f(real)) + mean(f(fake))),而本讲代码的 critic 训练等价于优化 +mean(f(real)) − mean(f(fake))——符号相反,但"critic 和 G 对着干"的结构相同。只要 G 的损失是 critic 损失的"反方向"(这里是 train_generator 用 y=+1),对抗就成立。
易错点 · 理解提示① wasserstein 的返回值没有负号——和 p41 的公式差一个符号,但训练等价(critic 的分数方向是约定)。② 生成器不变——WGAN 只改 critic 和训练方式。③ y_true * y_pred 是逐元素乘(形状相同),不是矩阵乘。
p.45WGAN 代码:创建判别器(无 sigmoid)与 WGAN代码
WGAN code example – creating discriminator & WGAN
def create_wgan_discriminator():
    model = keras.Sequential([
        layers.Conv2D(64, kernel_size=(5, 5), strides=2,
                  padding="same", activation=layers.LeakyReLU(0.2)),
        layers.Dropout(0.5),
        layers.Conv2D(64, kernel_size=(5, 5), strides=2,
                  padding="same", activation=layers.LeakyReLU(0.2)),
        layers.Dropout(0.5),
        layers.Conv2D(64, kernel_size=(5, 5), strides=2,
                  padding="same", activation=layers.LeakyReLU(0.2)),
        layers.Dropout(0.5),
        layers.Flatten(),
        layers.Dense(1)  # no sigmoid
    ])
    model.compile(loss=wasserstein, optimizer="rmsprop")
    model.trainable = False
    return model

def create_wgan(generator, discriminator):
    model = keras.Sequential([generator, discriminator])
    model.compile(loss=wasserstein, optimizer="rmsprop")
    return model
核心概念create_wgan_discriminator:和 p29 的 GAN 判别器只差两处——① 最后一层 Dense(1) 没有 sigmoid(注释 "# no sigmoid");② compile(loss=wasserstein, ...)(不是 BCE)。结构、Dropout、trainable = False、优化器 rmsprop 全部相同。参数仍是 207,617(去激活不改参数数)。create_wgan:同 create_gan,只是 loss 换成 wasserstein。
详细讲解

逐行对比 p29:

行GAN(p29)WGAN(p45)差异
Conv2D ×3 + Dropout ×3相同相同无
Flatten相同相同无
输出层Dense(1, activation="sigmoid")Dense(1)去 sigmoid
compile loss"binary_crossentropy"wasserstein换损失
compile optimizer"rmsprop""rmsprop"无
trainableFalseFalse无
参数量207,617207,617无(激活无参数)

为什么去掉 sigmoid 不改参数数:sigmoid 是逐元素函数 y = 1/(1+e−x),没有权重;Dense(1) 的 1,025 个参数(1,024 权重 + 1 偏置)完全不变。所以 critic 的 summary 和判别器的 summary 在 "Param #" 列完全相同——只是输出范围从 (0,1) 变成 (−∞, +∞)。

输出范围变化的后果:critic 的输出可以是任意实数——p49 的 dsc_loss 是 −2036、gen_loss 是 −2037(ep10),说明 critic 的分数在 ±2000 的量级。这个量级由权重裁剪的范围(0.05)和网络深度决定。如果裁剪到 0.01,分数范围会小一些。

create_wgan:Sequential([generator, discriminator])——复合模型和 p29 一样;compile(loss=wasserstein, optimizer="rmsprop")。训练它(输入噪声、标签 +1)时,loss = mean(+1 · critic(G(z))) = mean(critic(G(z))),最小化 → 假图的 critic 分数被压低。结合 critic 训练时"真图分数压低、假图分数推高"(p44 的分析),整体是:critic 让 f(real) < f(fake),G 让 f(fake) 变小——两者对抗,f(fake) 被拉向 f(real)。令 g = −f,就是"真高假低、G 让假变高"的标准图像。

函数名仍然叫 create_wgan_discriminator——虽然 p39 说 WGAN 里改叫 critic,但代码里的函数名和参数名仍是 discriminator。这是讲义代码的一个不一致——考场上用 "critic" 这个术语,写代码时照讲义的名字。

题目 · Review 关联
  • "Modify the GAN discriminator to a WGAN critic."——两行:layers.Dense(1)(去掉 sigmoid)和 model.compile(loss=wasserstein, optimizer="rmsprop")。
  • "Does removing sigmoid change the parameter count?"——No; activations have no parameters. Still 207,617。
  • "What is the output range of the critic?"——(−∞, +∞) (unbounded score)。
  • "What optimizer is used in the WGAN code?"——rmsprop, same as GAN。
  • "Why does create_wgan also use the Wasserstein loss?"——Because the composite model's loss is what drives the generator: loss = mean(critic(G(z))) with label +1 pushes fake scores toward real scores.
必要扩展
  • 去 sigmoid 后的数值稳定性:critic 的输出无界,极端情况下可能变成很大的数(几千),Keras 的 rmsprop 对大梯度做了归一化(除以梯度平方的滑动均值),所以仍然稳定——这也是讲义选 rmsprop 的一个可能原因。
  • 复合 WGAN 的参数:G 108,092 + critic 207,617 = 315,709(和 GAN 相同,因为结构只去了一个激活)。训练 G 时可训练参数 108,092(critic 冻结)。
  • Dropout 在 critic 里的角色:和 GAN 一样是"削弱 critic 防止太强"——但 p41 说 WGAN "no need to balance",理论上不需要 Dropout。讲义保留了它——可能是为了复用 p29 的结构、减少改动。
易错点 · 理解提示① 去掉 sigmoid 不改参数数——207,617 不变。② 代码里的函数名仍叫 create_wgan_discriminator,但术语上它是 critic。③ create_wgan 和 create_gan 的唯一区别是 loss——结构完全一样。
p.46WGAN 代码:训练判别器与生成器(−1 标签 / 裁剪 0.05)代码·训练
WGAN code example – training discriminator & generator
def train_wgan_discriminator(generator, discriminator, X_train_batch,
                             batch_size, clip_max=0.05):
    X_real = X_train_batch
    y_real = np.ones(batch_size)
    X_fake = generate_samples(generator, batch_size)
    y_fake = -np.ones(batch_size)  # -1
    discriminator.trainable = True
    loss = discriminator.train_on_batch(X_real, y_real)
    loss += discriminator.train_on_batch(X_fake, y_fake)
    for layer in discriminator.layers:
        weights = layer.get_weights()
        weights = [np.clip(w, -clip_max, clip_max) for w in weights]
        layer.set_weights(weights)
    discriminator.trainable = False
    return loss / 2

def train_wgan_generator(generator, gan, batch_size):
    return train_generator(generator, gan, batch_size)
核心概念train_wgan_discriminator:和 p31 的 train_discriminator 只差两处——① y_fake = -np.ones(batch_size)(假图 −1,不是 0);② 两次 train_on_batch 之后、关 trainable 之前,遍历 critic 每一层、把所有权重裁剪到 [−clip_max, clip_max](默认 0.05)。train_wgan_generator:直接 return train_generator(...)——G 的训练方式完全不变(噪声 + 标签 +1 + gan.train_on_batch)。
详细讲解

逐行对比 p31:

行GAN(p31)WGAN(p46)差异
y_realnp.onesnp.ones无
y_fakenp.zeros-np.ones0 → −1
train_on_batch ×2相同相同无(但 loss 函数不同)
裁剪循环无for layer in ...: clip新增
trainable 开关True → FalseTrue → False无
returnloss / 2loss / 2无

裁剪循环逐行:

  • for layer in discriminator.layers:遍历 critic 的 8 层(Conv、Dropout、Conv、Dropout、Conv、Dropout、Flatten、Dense)。
  • weights = layer.get_weights():返回该层的权重列表——Conv2D 是 [kernel (5,5,d,64), bias (64,)],Dense 是 [kernel (1024,1), bias (1,)],Dropout/Flatten 是 [](空列表)。
  • weights = [np.clip(w, -clip_max, clip_max) for w in weights]:对每个权重数组,把所有元素裁剪到 [−0.05, 0.05]——np.clip 逐元素:小于 −0.05 的变 −0.05、大于 0.05 的变 0.05、中间的不变。kernel 和 bias 都裁。
  • layer.set_weights(weights):把裁剪后的权重写回。Dropout/Flatten 的空列表 set_weights([]) 不会报错。

裁剪的位置:在两次 train_on_batch 之后——即"更新一次 critic,裁一次"。这符合 p40 的 "Clip the weights of the critic after each update in training"。注意是"每批裁一次"(两次 train_on_batch 之间不裁),而不是"每次 train_on_batch 后裁"——细节差异,影响不大。

裁剪的范围 0.05 vs 0.01:clip_max=0.05 是函数默认参数;p41 文字说 [−0.01, 0.01]。WGAN 论文用 0.01。讲义代码的 0.05 是 5 倍——可能是为了 MNIST 上训练更快(critic 容量更大)。考试若问"what value is used in the lecture code"→ 0.05;"what does the lecture text say"→ 0.01。

裁剪了多少参数:critic 的 207,617 个参数全部被裁剪(Conv 的 kernel + bias、Dense 的 kernel + bias)。训练后期,很多权重会撞到边界 ±0.05——这就是 p42 说的"容量下降"。

loss 的数值:critic 用 wasserstein 损失 = mean(y·p)。真图 y=+1 → mean(preal);假图 y=−1 → −mean(pfake)。两次 train_on_batch 返回的 loss 分别是这两个值,相加除以 2。p49 的 dsc_loss(ep10)= −286——即 mean(preal) − mean(pfake) ≈ −572(乘以 2),critic 学到的方向是"真图分数低、假图分数高"(p44 分析过的符号约定)。

train_wgan_generator:一行 return train_generator(generator, gan, batch_size)——复用 p31。G 的训练输入噪声、标签 +1、复合模型 gan(这里传入的是 create_wgan 返回的复合模型,用的是 wasserstein 损失)。loss = mean(+1 · critic(G(z))) = mean(critic(G(z))),最小化 → 假图分数压低 → 向真图分数靠拢。G 的训练逻辑完全没变,只是 gan 的 loss 换了。

题目 · Review 关联
  • "Modify train_discriminator for WGAN."——两处:y_fake = -np.ones(batch_size);加裁剪循环(4 行)。
  • "What is the default clip value in the lecture code?"——0.05(clip_max=0.05);"What does p41 say?"——[−0.01, 0.01]。
  • "Which weights are clipped?"——All weights of every layer in the critic (kernels and biases); Dropout/Flatten have none.
  • "Is the generator training function changed?"——No; train_wgan_generator just calls train_generator。
  • "When are the weights clipped?"——After both train_on_batch calls (after each critic update), before setting trainable = False。
  • 可能的计算题:"After clipping, what is the maximum absolute value of any critic weight?"——0.05。"Maximum output magnitude of a Dense(1) with 1,024 inputs all at ±1 and weights ±0.05?"——|Σw·x + b| ≤ 1,024×0.05 + 0.05 = 51.25(单层上界;多层复合后可以更大)。
必要扩展
  • np.clip(w, a, b) 等价于 np.minimum(np.maximum(w, a), b)——对浮点数组逐元素操作,不改变形状和 dtype。
  • get_weights() / set_weights() 是 Keras 层级别的权重读写——返回/接收 NumPy 数组列表,顺序与 layer.weights 一致(kernel 在前、bias 在后)。BN 层还会返回 moving mean / variance(本讲 critic 没有 BN)。
  • 裁剪对优化器状态的影响:rmsprop 为每个参数维护累积量 r;裁剪改了参数但没改 r——下一轮更新时 r 可能"过大",导致有效步长变小。这是裁剪的另一个隐性问题,WGAN-GP 没有这个问题(不裁)。
  • 如果想试 p41 的 0.01:调用 train_wgan_discriminator(..., clip_max=0.01)——但 p47 的循环里调用时没传 clip_max,所以要用 0.01 得改 p47。
易错点 · 理解提示① 假图标签是 −1(-np.ones),不是 0——这是和 p31 最醒目的差异。② 裁剪的是权重(get_weights),不是梯度、不是输出。③ 裁剪范围:代码 0.05、文字 0.01——两个都记。④ 裁剪循环在 trainable = False 之前、两次 train_on_batch 之后——顺序错了(比如在 train_on_batch 之前裁)就不是"更新后裁剪"了。
p.47WGAN 代码:训练整个 WGAN(critic ×3)代码·训练
WGAN code example – training the whole WGAN
def train_wgan(generator, discriminator, gan, X_train, epochs=100,
               batch_size=512):
    n_batches = math.ceil(len(X_train) / batch_size)
    history = {"gen_loss": [], "dsc_loss": [], "message": [],
               "samples": []}
    start_time = time.time()
    for i in range(epochs):
        gen_loss = dsc_loss = 0
        for j in range(n_batches):
            start = j * batch_size
            end = min((j+1) * batch_size, len(X_train))
            X_train_batch = X_train[start:end]
            for _ in range(3):
                dsc_loss += train_wgan_discriminator(generator,
                        discriminator, X_train_batch, end-start)
            gen_loss += train_wgan_generator(
                        generator, gan, end-start)
        update_history(history, start_time, i, epochs,
            gen_loss / n_batches, dsc_loss / n_batches / 3, generator)
    return history
核心概念train_wgan 和 p32 的 train_gan 只差两处:① 内层 for _ in range(3)——每批训练 critic 3 次、G 1 次;② 记录 dsc_loss 时除以 3(dsc_loss / n_batches / 3),因为累加了 3 次。其余(23 批、100 轮、batch 512、update_history)完全相同。
详细讲解

逐行对比 p32:

行GAN(p32)WGAN(p47)差异
函数名train_gantrain_wgan命名
n_batches / history / start_time相同相同无
双层循环 / 切片相同相同无
训练 criticdsc_loss += train_discriminator(...)(1 次)for _ in range(3): dsc_loss += train_wgan_discriminator(...)×3
训练 Ggen_loss += train_generator(...)gen_loss += train_wgan_generator(...)函数名(内容相同)
update_historygen_loss / n_batches, dsc_loss / n_batchesgen_loss / n_batches, dsc_loss / n_batches / 3dsc 除以 3

for _ in range(3):下划线 _ 是 Python 惯例——"这个循环变量我不需要"。循环体是把同一批真图 X_train_batch 喂给 train_wgan_discriminator 三次——每次它都用新采的噪声生成假图(generate_samples 内部调 generate_sample_inputs),所以三次训练的假图不同,但真图相同。三次之后 critic 用这批真图"看过三遍"。

为什么 critic 多训 3 次:p41 "no need to balance the training of the critic and generator"——WGAN 的 loss 是线性的,critic 再强也不会让 G 梯度消失;而 critic 越强,它估计的 Wasserstein 距离越准,G 的梯度方向越可靠。GAN 里 D 只训 1 次(p32)是因为 D 太强会让 G 梯度消失(p26 第 3 条)——这是 WGAN 和 GAN 训练策略上的核心差异。

为什么 dsc_loss 要除以 3:dsc_loss 累加了 3 × n_batches = 69 个值(每批 3 次),而 gen_loss 只累加了 n_batches = 23 个。为了让两者都是"每批平均",dsc 要多除一个 3——否则 dsc_loss 会是实际值的 3 倍。p49 的 dsc_loss(−286 等)就是除以 3 之后的值。

步数统计:23 批/轮 × 100 轮 = 2,300 批;每批 critic 3 次(各含两次 train_on_batch → 6 步)+ G 1 步 → critic 共 2,300 × 6 = 13,800 步、G 共 2,300 步。critic 的更新次数是 G 的 6 倍(GAN 里是 2 倍)。这解释了 WGAN 的训练时间更长:p49 总 1145 秒(19 分钟)vs p35 的 463 秒(7.7 分钟)——约 2.6 倍。

时间估算:每批 GAN 约 0.2 秒(D 2 步 + G 1 步 + 生成 1 次);WGAN 每批 critic 6 步 + G 1 步 + 生成 3 次——约 0.45 秒 → 每轮 23 × 0.45 ≈ 10.4 秒 → 100 轮 ≈ 1,040 秒 ≈ 17 分钟。p49 的 1,145 秒(含 ep90 的异常 911 秒)与此一致。

update_history 的最后一个参数 generator:每 10 轮用它生成样本——和 p33 一样。

题目 · Review 关联
  • "Modify train_gan to train the critic 3 times per generator update."——两处:for _ in range(3): dsc_loss += train_wgan_discriminator(...) 和 dsc_loss / n_batches / 3。
  • "Why divide dsc_loss by 3?"——Because it accumulates 3 critic updates per batch; dividing gives the mean per critic update, comparable to gen_loss.
  • "How many critic updates per generator update?"——3(本讲);"per epoch?"——23 × 3 = 69 critic updates, 23 generator updates。
  • "Why can the critic be trained more often in WGAN?"——The Wasserstein loss is linear, so a stronger critic improves the distance estimate without vanishing gradients for the generator (p41).
  • "Is the fake data the same across the 3 critic updates?"——No; generate_samples draws new noise each call, so each critic update uses fresh fakes; reals are the same batch。
  • 计算:"Total critic train_on_batch calls for 100 epochs?"——23 × 3 × 2 × 100 = 13,800;"generator?"——23 × 100 = 2,300。
必要扩展
  • critic ×3 是 WGAN 论文的建议值之一(论文用 5 或 100,取决于任务);本讲 3 是速度和准确度的折中。critic 次数越多、训练越慢、距离估计越准。
  • 一个常见的 WGAN-GP 实现细节:G 和 critic 用不同的学习率(TTUR)——本讲都用 rmsprop 默认 lr=0.001。
  • 没有 shuffle、没有早停——和 GAN 一样(p32 扩展)。WGAN 的 "meaningful loss" 理论上可以用来早停(loss 趋于 0 时停),但本讲仍跑满 100 轮。
易错点 · 理解提示① for _ in range(3) 包的是 critic 训练,不是 G——G 每批只训 1 次。② dsc_loss / n_batches / 3——两个除号,顺序无所谓但都别漏。③ 三次 critic 训练用的真图相同、假图不同(噪声重采)。④ WGAN 的训练时间约是 GAN 的 2.5 倍(p49 1145 s vs p35 463 s)——不是 3 倍,因为 G 的训练时间不变。
p.48WGAN 代码:整合代码
WGAN code example – putting it all together
X_train = load_and_prep_mnist("48")
generator = create_wgan_generator()
discriminator = create_wgan_discriminator()
wgan = create_wgan(generator, discriminator)
history = train_wgan(generator, discriminator, wgan, X_train)
核心概念五行入口,和 p34 只差函数名:create_wgan_generator、create_wgan_discriminator、create_wgan、train_wgan;复合模型变量叫 wgan(p34 叫 gan)。数据、默认参数(100 轮、batch 512)完全相同。
详细讲解

逐行:

  • X_train = load_and_prep_mnist("48")——同 p34,11,693 张 4 和 8。
  • generator = create_wgan_generator()——p44,等价于 create_generator(),108,092 参数。
  • discriminator = create_wgan_discriminator()——p45,critic:无 sigmoid、wasserstein 损失、trainable=False,207,617 参数。
  • wgan = create_wgan(generator, discriminator)——p45,复合模型,wasserstein 损失。
  • history = train_wgan(generator, discriminator, wgan, X_train)——p47,critic ×3,约 19 分钟(p49)。

变量名 wgan:复合模型叫 wgan 而不是 gan——只是为了和 GAN 代码区分(两者在同一个 notebook 里可能都要跑)。train_wgan 的第三个参数名仍然是 gan(p47 签名 def train_wgan(generator, discriminator, gan, ...))——传 wgan 进去即可。

GAN vs WGAN 入口对比:

GAN(p34)WGAN(p48)
生成器create_generator()create_wgan_generator()(相同)
判别器create_discriminator()create_wgan_discriminator()(无 sigmoid)
复合create_gan()(BCE)create_wgan()(wasserstein)
训练train_gan()(D ×1)train_wgan()(critic ×3)
用时462.8 s1,145.0 s
gen_loss 范围0.62 – 2.25−3000 – +1300
loss 可比性不可跨轮比较可比(W 距离估计)
题目 · Review 关联
  • "Write the code to build and train a WGAN."——五行 + p44–47 的函数。和 GAN 的区别全在函数名里——考场上容易得分。
  • "What are the parameter counts of the three models?"——generator 108,092; critic 207,617; composite wgan 315,709(trainable when training G: 108,092)。
必要扩展
  • 如果要在同一 notebook 里跑 GAN 和 WGAN 并比较:注意 keras.utils.set_random_seed(42) 在 load_and_prep_mnist 里被调用两次(p34、p48 各一次)——第二次重置了随机种子,所以 WGAN 的初始化和 GAN 相同(G 和 critic 的初始权重一样)。这让两者的比较更公平,但也意味着 generate_sample_inputs 的噪声序列会重复。
  • 保存:generator.save("wgan_gen.keras")——同样需要手动保存。
易错点 · 理解提示① 第三个模型变量叫 wgan(不是 gan),但 train_wgan 的形参仍叫 gan。② create_wgan_generator() 和 create_generator() 返回结构完全相同的模型——只是函数名不同。③ 默认参数(100 轮、512)和 GAN 一样——但 WGAN 每批多训 2 次 critic,所以慢 2.6 倍。
p.49WGAN 代码:训练历史(10 条消息 + 样本)原图数据
WGAN code example – training history (讲义截图:10 条消息 + 10 组样本,左列 ep10–50、右列 ep60–100)
ep10(混杂、扭曲) ep60(4 4 4 4 4 8 4 4 4 4) ep20(4 8 混杂) ep70(9 8 4 4 8 4 4 8 8) ep30 / ep40 / ep50(4 为主,笔画变粗) ep80 / ep90 / ep100(8 4 交替,4 占多) ep100(讲义最终样本):4 4 8 8 4 4 8 8 4 4 —— 只出现 4 和 8,比 GAN 更干净 示意图:按讲义 p49 截图的 10 组样本重绘;ep10–30 混杂扭曲,ep40 后以 4 为主、笔画粗,ep100 只剩 4 和 8
图 12.P49 讲义 p49 训练历史重绘:每 10 轮一组 10 张样本。ep10–30 混杂 → ep40 后以 4 为主、笔画变粗 → ep80–100 为 4 和 8 交替(ep100:4 4 8 8 4 4 8 8 4 4)。
核心概念WGAN 训练历史 10 条消息:gen_loss −2036.83 → −1066.78 → −706.60 → −528.03 → −421.49 → −350.06 → −300.18 → −262.39 → −233.04 → −209.59;dsc_loss −286.33 → −141.58 → −93.87 → −70.32 → −56.22 → −46.83 → −40.13 → −35.11 → −31.21 → −28.09。两者都单调趋 0(W 距离缩小),gen/dsc 比 ≈ 7.1–7.5。每 10 轮约 112 秒,ep90 异常 1833.3 s(疑机器休眠),总 1145.0 s。
详细讲解

10 条消息列表(讲义截图两列:左 ep10–50、右 ep60–100):

Epochtime elapsedgen_lossdsc_lossgen / dsc样本观察
10135.1 s−2036.83−286.337.11混杂、扭曲,像 4 又像 8
20246.3 s−1066.78−141.587.534 与 8 混杂
30357.5 s−706.60−93.877.534 为主
40471.8 s−528.03−70.327.514 为主,笔画粗
50587.9 s−421.49−56.227.504 为主
60698.6 s−350.06−46.837.484 4 4 4 4 8 4 4 4 4
70819.2 s−300.18−40.137.489 8 4 4 8 4 4 8 8
80921.7 s−262.39−35.117.478 4 交替,4 占多
901833.3 s ⚠−233.04−31.217.474 4 8 4 4 4 9 8 4 8
1001145.0 s−209.59−28.097.464 4 8 8 4 4 8 8 4 4

和 p35 对比:loss 的符号和意义。GAN 的 loss 是 BCE(0.07–2.25,正值,不可跨轮比较);WGAN 的 loss 是 Wasserstein 估计(负值,可以跨轮比较)。gen_loss 从 −2037 升到 −210——即 |loss| 缩小了 10 倍——W 距离从约 2037 缩到约 210,生成分布向真实分布靠近了 10 倍。这就是 p39 "meaningful loss" 的证据。

为什么是负数、这么大:p44 分析过——代码里 critic 的分数方向是"真图负、假图正"(省掉了公式里的负号),所以 W 距离的估计是负数。数值大小(±2000)来自无 sigmoid 的 critic + 裁剪 0.05——分数范围可以是几千。

gen/dsc 比值 ≈ 7.5:10 条消息里 gen_loss / dsc_loss 稳定在 7.46–7.53。原因:dsc_loss 是 critic 两次 train_on_batch 的平均(真图 loss 和假图 loss 各一次,再除以 2、再除以 3),而 gen_loss 是复合模型一次 train_on_batch 的 loss(只含假图)。如果 critic 的真图分数 ≈ −a、假图分数 ≈ +b,那么 dsc_loss ≈ (−a + b)/2 ≈ −(a−b)/2,gen_loss ≈ +b(G 的 loss 是 mean(critic(G(z))),假图分数为 +b 时 ≈ +b——但 p49 的 gen_loss 是负数,所以假图分数也是负的、只是比真图"更不负")。更精确地说:dsc ≈ (f(real) − f(fake))/2(按 p46 的符号),gen ≈ f(fake)。若 f(real) ≈ −2400、f(fake) ≈ −2037,则 dsc ≈ (−2400 − (−2037))/2 ≈ −182(接近 −286 量级),gen ≈ −2037 ✓。比值 7.5 反映了 "f(real) 和 f(fake) 的差距 ≈ f(fake) 的 1/4"——这是 critic 在裁剪约束下能达到的分数分离程度。

单调性:gen_loss 10 条严格单调上升(−2037 → −210),dsc_loss 严格单调上升(−286 → −28)。没有任何回落——这是 WGAN 稳定性的直接体现(p39 "improved stability")。对比 p35:GAN 的 gen_loss 先升后降(0.65 → 1.39 → 1.21),dsc_loss 单调升但意义不同。

时间列的异常:ep10→20 用 111.2 s、ep20→30 111.2 s、ep30→40 114.3 s、ep40→50 116.1 s、ep50→60 110.7 s、ep60→70 120.6 s、ep70→80 102.5 s——都约 112 s。但 ep80→90 用了 911.6 s(1833.3 − 921.7)——是正常值的 8 倍。然后 ep90→100 只用 −688.3 s(1145.0 − 1833.3)——负数!这在物理上不可能。解释:ep90 那一行的时间戳是错的——很可能是机器休眠或终端卡顿导致 time.time() 跳了一下,或者截图时手误(1833.3 可能是 833.3 的笔误?833.3 − 921.7 仍是负数……更可能是 1033.3:1033.3 − 921.7 = 111.6 ✓,1145.0 − 1033.3 = 111.7 ✓)。所以 ep90 的真实时间约为 1033.3 s,讲义的 "1833.3" 是笔误(1 和 0 之差)。无论哪种解释,总时间 1145 s(约 19 分钟)是可信的,每 10 轮约 112 s 也可信。

样本的演变:ep10–30 混杂扭曲(像 4 又像 8,笔画细、断裂)→ ep40–50 以 4 为主、笔画变粗 → ep60 后 4 和 8 清晰交替 → ep100 "4 4 8 8 4 4 8 8 4 4"。和 GAN(p35)比:GAN 后期有 9 形混合体和黑块,WGAN 后期只有 4 和 8、更干净——但 WGAN 的样本笔画更粗、更"重"(裁剪让 critic 对细节不敏感,G 不需要画细节就能骗过)。两者的 mode collapse 程度相似(都只有 4 和 8)。

题目 · Review 关联
  • 对比题(最可能):"Compare the training histories of the GAN (p35) and WGAN (p49)."——GAN: BCE losses in [0.07, 2.25], generator loss non-monotonic (peaks at ep40 then falls), not comparable across epochs; WGAN: Wasserstein estimates in [−3000, +1300], both losses strictly monotonic toward 0, comparable across epochs (meaningful loss), samples cleaner (only 4 and 8), training 2.6× slower。
  • "What does it mean that gen_loss rises from −2037 to −210?"——The Wasserstein distance estimate shrank ~10×; the generator distribution moved closer to the data distribution.
  • "Why are the losses negative?"——The code's wasserstein loss omits the minus sign (mean(y·p)); the critic's score direction is a convention, so the estimate is negative of the distance.
  • "Explain the time anomaly at epoch 90."——1833.3 s is inconsistent (the next segment would be negative); it is a recording error / machine sleep; the true value is likely ≈1033.3 s (consistent with ~112 s per 10 epochs)。
  • 计算:"Average seconds per 10 epochs."——(1145.0 − 135.1) / 9 ≈ 112.2 s;"per epoch?"——≈11.2 s;"ratio to GAN?"——112.2 / 42.6 ≈ 2.6×。
必要扩展
  • "Meaningful loss" 的实用价值:可以用 gen_loss 做早停(连续 N 轮不升就停)或模型选择(保存 gen_loss 最高——即最接近 0——的那一轮)。GAN 的 loss 做不到这一点。本讲虽然没做,但这是 WGAN 在工程上的真正好处。
  • gen/dsc 比值 7.5 的来源是本讲代码的"符号约定 + 两次平均"——如果用标准形式(带负号),比值会是负的,但绝对值关系类似。不要把这个比值当成 WGAN 的通用性质——换一个裁剪范围或 critic 结构,比值会变。
  • 样本"笔画粗"的原因:critic 被裁剪后,对细粒度细节(细笔画)的分数不敏感——G 发现"画粗一点"就能获得高分数,于是倾向于粗笔画。这是权重裁剪的副作用之一(p42),WGAN-GP 的样本通常更锐利。
易错点 · 理解提示① WGAN 的 loss 是负数、范围 ±2000——别和 GAN 的 0–2 混淆。② gen_loss 上升(−2037 → −210)是好事——W 距离在缩小;别读成"loss 在变大"。③ ep90 的 1833.3 s 是异常值——不是 WGAN 变慢了;总时间 1145 s 和每 10 轮 112 s 是可信的。④ dsc_loss 是除以 3 之后的值(p47)——别以为是 critic 单次 train_on_batch 的原始值。
p.50WGAN 代码:生成样本与训练曲线原图数据
WGAN code example – generated samples, plot of training history
samples = generate_samples(generator, 10)
plot_samples(samples)

plt.figure(figsize=(15, 5))
plt.plot(history["dsc_loss"], label="discriminative loss")
plt.plot(history["gen_loss"], label="generative loss")
plt.legend()
plt.show();
讲义 p50 样本(上)与训练曲线(下,重绘) 4 4 8 8 4 4 8 8 4 4 (generate_samples(generator, 10)) 020406080100 −3000−2000−100001000 ep1 ≈ +1300 ep5 ≈ −3000 ep100 −210 ep100 −28 discriminative loss generative loss 横轴:epoch(0–100);纵轴:每批平均 Wasserstein loss(−3000 … 1000)。两条曲线单调趋 0,无震荡。
图 12.P50 讲义 p50 重绘:上方为 10 张样本(4 4 8 8 4 4 8 8 4 4);下方为 history["dsc_loss"](蓝)与 history["gen_loss"](橙)。橙线从 ep1≈+1300 跌到 ep5≈−3000,然后单调升到 ep100 −210;蓝线从 ep1≈−700 跌到 ep10≈−280,然后缓慢趋 −28。两条线不交叉、不震荡。
核心概念代码和 p36 完全相同(只是 history 来自 train_wgan)。曲线形状完全不同:橙线(gen)ep1 ≈ +1300 → ep5 谷 ≈ −3000 → 单调升 → ep100 −210;蓝线(dsc)ep1 ≈ −700 → ep10 ≈ −280 → 缓慢趋 −28。两条线都单调趋 0,没有 p36 的冲顶跳水震荡,也不交叉。样本 "4 4 8 8 4 4 8 8 4 4"——只有 4 和 8。
详细讲解

橙线的三个阶段:

  • ep1–5:俯冲。+1300 → −3000。第一轮 critic 还很弱(随机初始化),G 的 loss 是正的(critic 给假图正分);几轮内 critic 迅速学会"真图负分、假图正分"的分离(在裁剪约束下),G 的 loss(= 假图分数)跌到 −3000——意味着假图和真图的分数差达到约 3000,即 W 距离估计 ≈ 3000。注意这个"跌"不是 G 变差——是 critic 变强了(能区分了),把距离"量"出来了。
  • ep5–50:快速回升。−3000 → −420。G 快速学习,假图分数向真图分数靠拢,W 距离估计缩小 7 倍。
  • ep50–100:缓慢回升。−420 → −210。趋于平稳,但仍在改善。

蓝线(critic loss):ep1 ≈ −700 → ep10 ≈ −280 → ep100 ≈ −28。它的绝对值 = (真图分数 − 假图分数)/2 的估计——也是 W 距离的(一半)估计。蓝线趋 0 和橙线趋 0 是同一件事:W 距离在缩小。蓝线比橙线更早"变平"(ep10 后就接近 −280 → −28 的缓坡)——因为 critic 每批训练 3 次、收敛快。

为什么橙线在蓝线下方:橙线 ≈ f(fake),蓝线 ≈ (f(real) − f(fake))/2。f(real) ≈ −2400、f(fake) ≈ −2037 时,橙 ≈ −2037、蓝 ≈ −182——橙更负。这个关系在整个训练过程中保持(gen/dsc ≈ 7.5)。

和 p36 的 GAN 曲线逐项对比:

GAN(p36)WGAN(p50)
gen 范围0.62 – 2.25−3000 – +1300
dsc 范围0.07 – 0.55−700 – −28
gen 形状冲顶 → 跳水 → 回升 → 缓降(震荡)俯冲 → 单调升(无震荡)
dsc 形状跌 → 单调升跌 → 单调升(趋 0)
两线交叉ep≈12 交叉不交叉(橙一直在下)
loss 可比性不可跨轮比较可比(W 距离估计)
样本4/8/9 混合,有黑块只有 4 和 8,干净但笔画粗
总时间463 s1,145 s(2.6×)

这张图是 p39 "两大改进" 的证据:① meaningful loss——橙线从 −3000 升到 −210,和样本从混杂变清晰同步;② stability——两条线都单调,没有 p36 的"冲顶跳水"。

但 mode collapse 仍在:样本只有 4 和 8——训练集本来就只有这两类,所以这不算严重的 mode collapse;但 p49 ep100 的样本 10 张里 4 占 6 张、8 占 4 张,而且形状雷同——"多样性"仍然有限。WGAN 没有解决 mode collapse(p26 第 2 条)。

题目 · Review 关联
  • "Sketch and compare the loss curves of GAN and WGAN."——GAN: two positive curves, generator curve non-monotonic with a spike and a dip, curves cross; WGAN: two negative curves, both monotonic toward zero, no crossing, generator below critic.
  • "Why does the generator loss drop to −3000 at epoch 5 and then rise? Is the generator getting worse then better?"——The initial drop reflects the critic learning to separate real from fake (measuring a large distance), not the generator getting worse; the subsequent rise is the generator improving (distance shrinking).
  • "What does the final generator loss (−210) tell you?"—The estimated Wasserstein distance between generated and real distributions is about 210 (in the critic's score units), much smaller than the initial ~3000.
  • "Why do both curves tend to zero?"—Both are estimates of the Wasserstein distance (up to scale); as the generator improves, the distance shrinks to zero.
  • "Which training is more stable? Justify."—WGAN: both losses are monotonic; GAN's generator loss oscillates (2.25 → 0.62 → 1.39)。
必要扩展
  • 橙线 ep1 的正值 +1300:第一轮 critic 是随机初始化、还没学会"真负假正"的分离,假图分数碰巧为正。ep2 之后变负——critic 已学到分离方向。这个"正→负"的翻转是 critic 符号约定确定的瞬间,不是 G 的变化。
  • 曲线的"平滑":100 个点、每点是一轮 23 批的平均——WGAN 每批 critic 训 3 次,相当于每轮 69 次 critic 更新,平均后曲线很平滑。GAN 每轮只有 23 次 D 更新,曲线略粗糙(p36 的橙线在 ep40 后有小波动)。
  • WGAN-GP 的曲线会与此类似(也单调趋 0),但 loss 的数值范围不同(没有裁剪、分数范围由梯度惩罚决定)。本讲没有 WGAN-GP 的训练结果。
  • 两张图(p36、p50)的代码完全相同——代码不变、结果天差地别,这正是"损失函数的选择比网络结构更重要"的一个经典例子。
易错点 · 理解提示① 橙线在 ep5 的 −3000 是谷底,之后"上升"是好事——W 距离在缩小;别读成"loss 在变大"。② 蓝线(dsc)是 critic 的 loss、橙线是 gen 的——和 p36 一样的颜色约定(先画 dsc 蓝、后画 gen 橙)。③ 两条线不交叉——橙一直在下。④ 纵轴范围 −3000 到 +1000——不是 0 到 2。

🔍 代码精读:三段代码当 Lab(无 t12 notebook)——AE(p14–19)· GAN(p28–36)· WGAN(p44–48)

Unit 12 没有配套 tutorial / lab notebook(tutorial 只到 t11),但讲义本身给了三段完整、可运行的 Keras 代码:自编码器(7 页)、GAN(10 页)、WGAN(8 页)。Course Review p10 把 "GAN code example" 标为 #5 (optional),p11 的答题说明又说长题会出 "modify code"——所以这三段代码就是本讲的"Lab":不要求默写,但要能读懂每一行、算出每个参数、预测改动后的后果。下面按"数据流 → 参数 → 训练配置 → 输出 → 改动练习"五步,把三段代码各做一次完整 walkthrough;三张卡共用 p14–15 的工具函数(load_and_prep_mnist、plot_samples)和 p30 / p33 的辅助函数(generate_sample_inputs、generate_samples、update_history)——它们只在 AE 卡里讲一次。

Lab·A自编码器代码全解(p14–p19):11,693 张 · 1,087,800 参数 · 46 步/轮 · 100 轮代码精读参数
load_and_prep_mnist("48") → encoder / decoder(Sequential) → Sequential([encoder, decoder]) → compile(mse, adam) → fit(X, X, 100, 256) → 对比重建 → decoder.predict(np.random.random((10, 40)))
核心概念AE 代码是"最小生成模型":两个独立 Sequential(为了 p19 能单独调 decoder)+ 一个复合模型 + fit(X, X)。关键数字:数据 (11693, 28, 28, 1);编码器 784→512→256→40(543,528 参数);解码器 40→256→512→784(544,272);总 1,087,800;Adam 优化器 2×+2 = 2,175,602;每轮 ⌈11693/256⌉ = 46 步,100 轮 4,600 步;压缩比 784/40 = 19.6。
详细讲解

第 1 步 · 数据流(p14):(X_train, y_train), _ = mnist.load_data() 丢弃测试集 → np.isin(y_train, [4, 8]) 筛出 5,842 + 5,851 = 11,693 张 → astype(float) / 255 → reshape(-1, 28, 28, 1)。返回只有一个数组——没有标签。p15 的 plot_samples 用 subplot(1, n, i+1)(1-based)、cmap="gray_r"(白底黑字)、reshape(28, 28)(去通道维)。

第 2 步 · 模型与参数(p16):

层形状公式参数
Flatten(28,28,1) → 784—0
Dense 512 relu784 → 512(784+1)×512401,920
Dense 256 relu512 → 256(512+1)×256131,328
Dense 40 sigmoid256 → 40(256+1)×4010,280
Dense 256 relu40 → 256(40+1)×25610,496
Dense 512 relu256 → 512(256+1)×512131,584
Dense 784 sigmoid512 → 784(512+1)×784402,192
Reshape784 → (28,28,1)—0
总计784 → 40 → 784enc 543,528 + dec 544,2721,087,800

两个易错点:① Dense 的 bias 别漏(784×512 = 401,408 是错的,+512 = 401,920 才对);② 潜层用 sigmoid(不是 relu)——为了把潜向量限制在 (0,1),匹配 p19 的均匀噪声。

第 3 步 · 训练配置(p17):Sequential([encoder, decoder])(Keras 允许模型嵌套)→ compile(loss="mse", optimizer="adam") → fit(X_train, X_train, epochs=100, batch_size=256, verbose=0)。输入 = 目标是自编码器的标志。46 步/轮(最后一批 173 张)。df.index = df.index + 1 让曲线横轴从 1 开始。

第 4 步 · 输出(p18–19):autoencoder.predict(X_train[:10]) 看重建——形状正确、笔画略粗略模糊;decoder.predict(np.random.random((10, 40))) 生成——10 张 4/8 的变体,偶有"四不像"(潜空间空洞)。

与 Unit 4 的关系:这就是一个"输入 = 输出"的 Unit 4 全连接网络。Unit 4 的 Dense 参数公式 (nin+1)·nout 用了六次;Unit 6 的 history.history["loss"] + df.plot 画曲线;Unit 7 的 verbose=0 和 Adam。

题目 · Review 关联
  • Review #2 "Autoencoders" 的代码证据全在这 7 页:编码器压缩(p16 前四层)、潜向量(Dense(40))、解码器重建(后四层)、瓶颈(40 ≪ 784)、随机潜向量生成(p19)。
  • Review p11 "modify code" 可能出法:① "Change the latent size to 2" → SZ_LATENT_AE = 2,重建更模糊;② "Use binary_crossentropy instead of mse" → compile(loss="binary_crossentropy", ...);③ "Train on all digits" → load_and_prep_mnist();④ "Add a denoising objective" → autoencoder.fit(X_noisy, X_train, ...)(p12 去噪);⑤ "Generate 100 samples" → np.random.random((100, 40))。
  • Review p11 "determine" 可能出法:① "Number of trainable parameters" → 1,087,800;② "Steps per epoch" → 46;③ "Shape of the latent vector for a batch of 10" → (10, 40);④ "Output shape of the decoder" → (None, 28, 28, 1)。
必要扩展
  • Optimizer = 2 × Trainable + 2(Unit 8 总结的通用公式,Adam):本讲 AE = 2 × 1,087,800 + 2 = 2,175,602。Keras 的 model.optimizer.variables() 会返回这个数的张量元素总数(m、v 各一份 + iterations + iterations 的幂)。
  • 训练时间估算:4,600 步 × 1.09M 参数,CPU 约 1–2 分钟、GPU 约 10–20 秒——比 GAN(7.7 分钟)快 5 倍以上,因为 AE 每步只做一次前向+反向。
  • 如果你想在 Project 里用 AE 做异常检测(p12):训练后 recon = autoencoder.predict(X)、err = ((X − recon)**2).mean(axis=(1,2,3))、对 err 设阈值(如 mean + 2σ)。
  • 与 Unit 9 迁移学习的接口:把 encoder 当特征提取器,enc.trainable = False,后面接 Dense 做分类——这是"无监督预训练"的最小实现。
易错点 · 理解提示① fit(X_train, X_train) 不是笔误。② 1,087,800 = 543,528 + 544,272——编码器和解码器不共享权重。③ p18 用 autoencoder.predict(输入图),p19 用 decoder.predict(输入噪声)——两个不同的模型入口。④ np.random.random((10, 40)) 是 [0,1) 均匀分布——和 GAN 的 N(0,1) 不同。
Lab·BGAN 代码全解(p28–36):G 108,092 · D 207,617 · 23 批/轮 · 100 轮 · 462.8 s代码精读参数
create_generator() / create_discriminator() / create_gan(G, D) → generate_sample_inputs / generate_samples → train_discriminator / train_generator → train_gan(双层循环)→ update_history → generate_samples(generator, 10) + plot
核心概念GAN 代码 = 三个 create 函数 + 两个 generate 函数 + 两个 train 函数 + 一个循环 + 一个 history。关键数字:G 108,092(Dense 2,009 + BN 98 + Conv 1,664 + BN 128 + Conv 102,464 + BN 128 + Conv 1,601);D 207,617(Conv 1,664 + 102,464 + 102,464 + Dense 1,025);复合 315,709;batch 512 → ⌈11693/512⌉ = 23 批/轮(最后一批 429);每批 D 更新 2 步 + G 1 步;100 轮 462.8 s。
详细讲解

第 1 步 · 生成器(p28):Dense(49, LReLU) → BN → Reshape(7,7,1) → UpSampling → Conv2D(64, 5×5, same, LReLU) → BN → UpSampling → Conv2D(64, 5×5, same, LReLU) → BN → Conv2D(1, 5×5, same, sigmoid)。空间 7→14→28。第一个 BN 在 Dense(49) 之后、Reshape 之前 → 98 个参数(不是 2)。

第 2 步 · 判别器(p29):Conv2D(64, 5×5, s2, same, LReLU) ×3 各接 Dropout(0.5) → Flatten → Dense(1, sigmoid)。空间 28→14→7→4(same + stride 2 = 向上取整除 2);Flatten 1,024。compile(BCE, rmsprop)。返回前 trainable = False。

第 3 步 · 复合 GAN(p29):Sequential([G, D]),compile(BCE, rmsprop)。训练它时 D 冻结 → 只有 G 更新。

第 4 步 · 噪声与样本(p30):np.random.normal(0, 1, (n, 40));generate_samples(generator, n) = 采噪声 + generator.predict。

第 5 步 · 训练两步(p31):

train_discriminatortrain_generator
输入真图 X_train_batch + 假图 generate_samples(·, batch_size)噪声 generate_sample_inputs(batch_size)
标签真 1、假 0全 1(假图标真)
trainableTrue → 训练 → False不动(依赖上一步留下的 False)
train_on_batch2 次(真、假)1 次(gan)
返回loss / 2loss

第 6 步 · 循环(p32–33):n_batches = ceil(11693/512) = 23;每批切真图(最后一批 429 张)→ train_discriminator → train_generator → 累加;每轮 update_history(..., gen_loss/23, dsc_loss/23, generator);每 10 轮((i+1) % 10 == 0)打印消息 + 画 10 张样本。

第 7 步 · 入口与输出(p34–36):五行入口;p35 的 10 条消息(gen 0.65→1.39→1.21,dsc 0.11→0.55 单调升);p36 的曲线(gen 峰 ep2≈2.2、谷 ep8≈0.62;dsc 谷 ep5≈0.07;交叉 ep≈12);样本 "8 9 8 4 9 4 8 4 4 4"。

与前面单元的关系:Unit 8 的 Conv2D 参数 (k²·din+1)·n 用了 6 次;Unit 7 的 BN = 2×通道 用了 3 次、Dropout 用了 3 次;Unit 5 的 BCE + Dense(1, sigmoid) 是 D 的输出层;Unit 7 的 rmsprop(不是 adam)。

题目 · Review 关联
  • Review #5(optional)"GAN code example"——考法就是 p11 的 "modify code":① "Remove BatchNormalization from the generator" → 删三个 BN,G 参数变 107,738(108,092 − 354),训练可能更不稳定(BN 缓解 mode collapse);② "Replace rmsprop with adam" → 两处 optimizer="rmsprop" 改 "adam";③ "Change batch_size to 256" → n_batches = 46;④ "Train the discriminator twice per generator update" → 把 train_discriminator 那行包进 for _ in range(2),dsc_loss 除以 2;⑤ "Remove Dropout from D" → D 更强、G 更容易梯度消失;⑥ "Use SZ_LATENT_GAN = 100" → Dense(100→49) = 4,949 参数,其余不变。
  • Review p11 "explain/justify" 可能出法:① "Why is the discriminator set non-trainable?"(p24);② "Why are fake images labelled 1 when training the generator?"(p24);③ "Why does the discriminator loss increase over training?"(p35);④ "Why is the generator loss not a good indicator of sample quality?"(p26 第 4 条)。
  • Review p11 "determine":G 108,092 / D 207,617 / GAN 315,709 / trainable-when-training-G 108,092 / 23 batches / 429 last batch / 2,300 total batches。
必要扩展
  • Optimizer 参数:rmsprop 为每个参数维护一个累积量 r(不像 Adam 的两个),所以 rmsprop 的变量数 = Trainable + 1(iterations)——G 108,093、D 207,618。如果换成 Adam 就是 2×+2。
  • 训练时间分解:462.8 s / 2,300 批 ≈ 0.20 s/批 = 生成 512 张假图(G 前向)+ D 两次 train_on_batch + G 一次 train_on_batch(含 G 前向 + D 前向 + 反向到 G)。
  • Keras 的 trainable 切换坑(p29 扩展):在 compile 之后改 trainable,某些版本要重新 compile。更稳健的写法是在 train_discriminator 里 True 之后 discriminator.compile(...)、False 之后也 compile——讲义代码依赖 train_on_batch 每次重算梯度,在 TF 2.x 下能工作。
  • 如果你想复现 p35 的数值:keras.utils.set_random_seed(42) 固定了数据顺序和初始权重,但 Dropout 和 np.random.normal 仍有随机性——不同机器/版本的数值会略有差异,趋势一致。
易错点 · 理解提示① 第一个 BN = 98(49 维),不是 2。② D 的第三次 stride-2:7 → 4(向上取整)。③ 训练 D 时假图标签 0、训练 G 时 1。④ train_generator 的输入是噪声不是假图。⑤ 优化器是 rmsprop。⑥ 复合 GAN 315,709 ≠ 训练 G 时的可训练参数 108,092。
Lab·CWGAN 代码全解(p44–50):五改动 · critic 207,617 · ×3 · 1,145 s代码精读附录
wasserstein(y_true, y_pred) → create_wgan_generator()(= create_generator)→ create_wgan_discriminator()(Dense(1) 无 sigmoid,loss=wasserstein)→ create_wgan → train_wgan_discriminator(−1 标签 + clip 0.05)/ train_wgan_generator(= train_generator)→ train_wgan(critic ×3)→ 五行入口 → 10 条消息 + 曲线
核心概念WGAN 代码 = GAN 代码 + 五处改动(p40)。参数完全相同(G 108,092、critic 207,617、复合 315,709——去 sigmoid 不改参数数)。训练差异:critic 每批 3 次(各含两次 train_on_batch → 6 步)+ G 1 步;dsc_loss 除以 3;时间 1,145 s(约 GAN 的 2.6 倍)。结果差异:loss 为负值、单调趋 0(gen −2037 → −210,dsc −286 → −28)。
详细讲解

改动 ① · 损失(p44):def wasserstein(y_true, y_pred): return backend.mean(y_true * y_pred)——p41 公式 −(1/n)Σy·p 的无负号版本(Keras 最小化;critic 分数方向是约定)。

改动 ②③ · 生成器与 critic(p44–45):create_wgan_generator() 一行 return create_generator();create_wgan_discriminator() 和 p29 只差 Dense(1)(无 sigmoid)和 loss=wasserstein;create_wgan 和 create_gan 只差 loss。

改动 ④⑤ · 训练(p46–47):

GAN(p31–32)WGAN(p46–47)
y_fakenp.zeros-np.ones
裁剪无for layer in critic.layers: clip(w, −0.05, 0.05)
critic 次数/批1for _ in range(3)
记录dsc_loss / n_batchesdsc_loss / n_batches / 3
G 训练train_generatortrain_wgan_generator(= train_generator)

第 4 步 · 入口与输出(p48–50):五行入口(函数名加 wgan);p49 的 10 条消息(gen −2036.83 → −209.59 单调升、dsc −286.33 → −28.09 单调升、gen/dsc ≈ 7.5、ep90 时间 1833.3 s 异常);p50 曲线(gen ep1 ≈ +1300 → ep5 ≈ −3000 → −210;dsc −700 → −28;不交叉);样本 "4 4 8 8 4 4 8 8 4 4"。

读 WGAN 代码的正确方法:把 p44–47 和 p28–32 并排,逐行找差异——差异就是 p40 的五条。找不到差异的地方(如 Dropout、rmsprop、batch 512)说明 WGAN 没有改它们。

题目 · Review 关联
  • Review 不考 WGAN;但 Review #4 "Difficulties" 的延伸 "propose an improvement" → "Convert the GAN to a WGAN: use the Wasserstein loss −mean(y·p), label fakes −1, remove the critic's sigmoid, clip critic weights, train the critic multiple times"——五条照写。
  • Review #5 的 "modify code" 若出 "Convert the GAN code to a WGAN"——答案就是上面那张表的五行。
  • 可能的 "determine":① "Parameter count of the critic" → 207,617(same as D);② "Critic updates per epoch" → 23 × 3 = 69;③ "Clip range in the lecture code" → 0.05(p41 文字 0.01);④ "Label for fake images" → −1。
必要扩展
  • 从 WGAN 到 WGAN-GP(p42)的代码改动(讲义未给):① 去掉 p46 的裁剪循环;② 在 critic loss 里加 λ * mean((grad_norm − 1)²),其中 grad 是 critic 对"真图和假图的随机插值"的梯度(需要 tf.GradientTape,不能用 train_on_batch);③ critic 里不用 BN(本讲 critic 本来就没有)。这是一个中等工作量的 Project 题目。
  • WGAN 的训练时间是 GAN 的 2.6 倍(1,145 vs 463 s)——每批 7 步 vs 3 步,再加 3 次生成假图。如果 Project 要跑多次实验,WGAN 的成本要算进去。
  • critic ×3 是本讲的选择;WGAN 论文用 5 或 100。critic 次数越多、距离估计越准、训练越慢。可以用 dsc_loss 的稳定性判断 critic 是否训够——如果 dsc_loss 在一轮内波动很大,说明 critic 还没收敛。
易错点 · 理解提示① 五改动里没有"改生成器"——create_wgan_generator 原样返回 G。② 去掉 sigmoid 不改参数数。③ wasserstein 没有负号——critic 的分数方向是约定,别和 p41 的公式混淆。④ 裁剪范围代码 0.05、文字 0.01。⑤ dsc_loss 除以 3——别漏。

📋 Course Review 对照:Unit 12 对应 p10 五考点 #1–#5(#5 optional · WGAN 附录不在 Review)

Course Review p10 的 "Unit 12" 共五条,四条必考 + 一条 optional:#1 生成/判别建模定义 · #2 自编码器原理 · #3 GAN 原理 · #4 训练 GAN 的问题 · #5 GAN 代码(optional)。附录 WGAN(p38–50)不在 Review 里——意味着期末考大概率不直接考 WGAN 细节,但它是回答 #4 延伸题("how to address these problems")的最佳素材。p11 的答题说明:短题(state / determine / name / 数字 / 表达式)+ 长题(modify code / describe / explain / justify);可带计算器——所以 参数计算(AE 1,087,800、G 108,092、D 207,617、批次数 23/46)几乎肯定会以 "determine" 出现。2026 Autumn 的试卷答案中没有 Unit 12 题目——本讲是首次进入考核,Review 列表就是范围。

#Course Review 考点(原文)可考的小问本讲对应代码 / 讲义证据自检:能否……
1The definition of generative and discriminative modeling① 判别建模定义(四要点)p4:predicting labels (numbers or categories) from features = supervised learning with labelled examples;数学 Prob(label | features)Unit 4–11 全部模型;p4 图 "Labelled examples → Discriminative model → Predicted value 0.8"用两句英文写出定义并点出 "labelled" 和 "Prob(label | features)"
② 生成建模定义(四要点)p5:generating new data with specific characteristics;usually unsupervised with unlabelled examples;数学 Prob(features) or Prob(features, label)p6 人脸、p7 风格迁移、p8 ChatGPT / MuseGAN / World models 三个例子写出定义并举两个不同模态的例子
③ 两者对比p5 表:目标(预测标签 vs 生成数据)/ 范式(监督 vs 通常无监督)/ 数学目标 / 输出(值 vs 样本)—给出一个任务判断属于哪类并说明理由(如 "情感分析 → 判别,因为学 Prob(label | features)")
④ 辨析题p1 / p4 易错点:生成模型 ≠ GAN(AE 也是);判别建模 ≠ GAN 的判别器;生成建模 ≠ 一定无标签("usually")ChatGPT 是自回归生成模型,不是 GAN(p8)说出 "discriminative modelling" 和 "discriminator" 的区别
2How Autoencoders work① 结构:编码器 / 潜向量 / 解码器p10:encoder compresses input → latent code / latent vector(lower-dimensional);decoder reconstructs original datap16:Flatten → Dense(512) → Dense(256) → Dense(40, sigmoid);Dense(256) → Dense(512) → Dense(784, sigmoid) → Reshape画出沙漏图并标出三个部分的维度 784 → 40 → 784
② 瓶颈与潜空间p11:低维形成 bottleneck,迫使网络学 efficient representations(捕捉重要特征);压缩后的空间叫 latent space压缩比 784/40 = 19.6解释"没有瓶颈网络会学成恒等映射"
③ 训练方式p17:无标签,fit(X_train, X_train),mse + adam,100 轮、batch 256(46 步/轮)1,087,800 参数;Adam 2,175,602解释为什么输入 = 目标、为什么用 mse
④ 用解码器生成p11 / p19:feed a latent vector of random numbers (noise) to the decoder;np.random.random((10, 40))(均匀 [0,1),匹配 sigmoid 潜层)p19 三行:X = np.random.random(...) → decoder.predict(X) → plot_samples写出 p19 三行并说明为什么是 decoder 不是 autoencoder、为什么是 uniform
⑤ 五个应用p12:image generation (decoder) / image denoising / data compression (latent vectors) / anomaly detection (reconstruction errors) / dimensionality reduction & feature extraction去噪 = 输入加噪、目标原图;异常检测 = 重建误差大 → 异常任选两个应用并各说一句"怎么做"
3How Generative Adversarial Networks (GAN) work① 定义:复合模型 + 对抗对p21:composite model containing an adversarial pair of two models;generator generates instances (examples / samples / observations) appearing as if from the training dataset;discriminator predicts whether an instance is real or fakep21 图:噪声 → G → 假图 → D → Real(1)/Fake(0);真图也进 D写出定义并指出 "generator never sees real data"
② 骗过聪明判别器 / DCGANp22:"If a generator can fool a smart discriminator, the generated instances are as good as real ones!";today a GAN ≈ DCGAN(deep convolutional GAN;原始论文用 DNN)p28 生成器全是 Conv2D + BN + UpSampling;p29 判别器 strided Conv说出 DCGAN 相对原始 GAN 的变化(DNN → CNN)
③ 训练 Dp23:usual supervised binary classification;真图标 1、假图标 0;训练数据一半来自 G、一半来自训练集;G 不更新p31:y_real = np.ones、y_fake = np.zeros、trainable = True → 两次 train_on_batch → False解释"标签从哪来"(来源决定,非人工)
④ 训练 Gp24:目标 fool D;set D non-trainable(否则 D "learns to become foolish");label fakes as real(y=1);loss = −log D(G(z))p31 train_generator:噪声 + np.ones + gan.train_on_batch;数值:D(G(z)) = 0.1 → 2.30,0.9 → 0.11推导"为什么冻结 D""为什么标 1",并算两个 BCE 值
⑤ 收敛p25:equilibrium;理论上 G 100%(在复合 GAN 中测)、D 50%(random guessing,maybe always "real");收敛后仍可能 mode collapsep36 曲线:ep100 gen 1.21 / dsc 0.55(< ln 2),未到理论均衡解释 50% 和 100% 为什么是同一件事
⑥ 与 AE 的对比都是 composite model;AE 合作(重建)、GAN 对抗;AE 的 decoder ≈ GAN 的 G;AE 用 mse、G 用 D 的反馈p18 重建模糊 vs p36 GAN 样本锐利但有噪声列一张三行对比表
4Potential problems when training GAN① Non-convergencep26:D 和 G 的 loss oscillate and do not convergep36 橙线冲顶 2.25 → 跳水 0.62 → 回升 1.39英文一句话定义 + 指出曲线上对应的段
② Mode collapsep26:G finds and produces limited varieties to fool D, then collapses and stops finding othersp35 样本只有 4/8/9,形状雷同;p49 样本只有 4/8定义并举讲义例子
③ Vanishing gradients (G)p26:D too good → G has vanishing gradients and does not learn at all;推导:−log(1−D(G(z))) 在 D(G(z))≈0 时饱和p36 初期 dsc 跌到 0.07、gen 冲到 2.25用原始 GAN 损失推导梯度为何消失;说明本讲用 −log D(G(z)) 的缓解
④ Uninformative loss (G)p26:G 的 loss 用 current discriminator 测,而 D keeps improving → 不可跨轮比较、不反映质量p35:ep10 gen 0.65(样本噪点)vs ep100 gen 1.21(样本清晰)——loss 反而更高用 p35 的两个数字解释"低 loss ≠ 好样本"
⑤ Many & sensitive hyperparametersp26:D 和 G 有 many hyperparameters which are difficult to tunep29 rmsprop(非 adam)、Dropout 0.5;p31 D 每批 1 次;p32 batch 512列出讲义里三个"调出来的"选择
⑥ 延伸:如何缓解→ WGAN(p39–41):meaningful loss(W 距离)+ stability;WGAN-GP(p42)p49 / p50:loss 单调趋 0、样本更干净把五条困难和 WGAN 的两大改进对应起来(④→meaningful、①③→stability)
5
optional
GAN code example (optional)① 结构代码p28 G:Dense(49) → BN → Reshape → UpSampling → Conv(64) → BN → UpSampling → Conv(64) → BN → Conv(1, sigmoid),108,092;p29 D:Conv(64, s2) ×3 + Dropout → Dense(1, sigmoid),207,617第一个 BN = 98(49 维);D 的空间 28→14→7→4给一段代码数参数(Conv 用 (k²·d+1)·n,BN 用 2×通道)
② 训练代码p31 两函数(ones / zeros / trainable 开关 / loss/2;ones / gan.train_on_batch);p32 循环(23 批、429 最后一批);p33 NUM_REPORTS=10复合 315,709;训练 G 时可训练 108,092填空:y_fake = np.____;y = np.____(train_generator)
③ modify code去 BN(−354 → 107,738)/ adam 换 rmsprop / batch 256(46 批)/ D ×2 / SZ_LATENT_GAN = 100(Dense 4,949)见 Lab·B 卡预测每个改动对参数量和训练的影响
④ 读训练历史p35 十条消息(gen 0.65→1.39→1.21;dsc 0.11→0.55 单调升;42.6 s/10 轮);p36 曲线形状交叉 ep≈12;峰 ep2、谷 ep8给一张类似的表回答 "what can you conclude"
⑤ 转 WGAN五改动:wasserstein loss / y_fake = −1 / Dense(1) 无 sigmoid / clip 0.05 / critic ×3p44–47把 GAN 代码改成 WGAN(五处)

英文答题模板(考场直接写)

题型模板
定义 · 判别建模"Discriminative modelling learns a model for predicting labels (numbers or categories) from features. It equals supervised learning using labelled examples, and mathematically estimates Prob(label | features)."
定义 · 生成建模"Generative modelling learns a model for generating new data with specific characteristics. It is usually unsupervised learning using unlabelled examples, and mathematically estimates Prob(features) or Prob(features, label)."
AE 原理"An autoencoder consists of an encoder and a decoder. The encoder compresses the input into a lower-dimensional latent vector (a bottleneck that forces the network to learn efficient representations); the decoder reconstructs the input from the latent vector. It is trained with no labels by minimizing the reconstruction error between the input and the output. To generate, a random latent vector is fed to the decoder."
GAN 原理"A GAN is a composite model of an adversarial pair: a generator that produces instances looking as if they come from the training data, and a discriminator that predicts whether an instance is real or fake. The discriminator is trained as a binary classifier (real=1, fake=0). The generator is trained with the discriminator frozen and fake images labelled real, so that D(G(z)) → 1. They reach equilibrium when D is only 50% accurate and G fools it 100%."
训练 G 的两个操作"Set the discriminator non-trainable; otherwise it would 'learn to become foolish' and the generator's improvement would be illusory. Label fake images as real because the generator's objective is to make D(G(z)) close to 1; BCE with y=1 gives −log D(G(z))."
五大困难"(1) Non-convergence: the losses oscillate. (2) Mode collapse: the generator produces only a few varieties. (3) Vanishing gradients: a too-strong discriminator saturates the generator's loss. (4) Uninformative loss: the generator's loss is measured against the current discriminator, which keeps changing. (5) Many sensitive hyperparameters."
GAN 收敛"The GAN converges when generator and discriminator reach equilibrium: the generator fools the discriminator 100% of the time (measured when trained via the whole GAN), and the discriminator is only 50% accurate, i.e., guessing randomly — possibly predicting 'real' for everything. Mode collapse may still occur."
WGAN(延伸)"WGAN uses the Wasserstein loss −mean(y·p) with labels +1/−1, removes the critic's sigmoid, clips the critic's weights, and trains the critic multiple times. This gives a meaningful loss that correlates with sample quality and improves stability."
参数计算Dense: (nin+1)·nout;Conv2D: (k·k·din+1)·n;BN: 2×channels;UpSampling/Reshape/Flatten/Dropout: 0。AE 1,087,800;G 108,092;D 207,617;GAN 315,709。
复习优先级(按 Review 权重):① p4 + p5 定义(4 句,必背)→ ② p26 五大困难(5 条,必背)→ ③ p21 / p23 / p24 / p25 GAN 原理(定义 + 两步训练 + 收敛)→ ④ p10 / p11 / p12 / p19 AE 原理(结构 + 瓶颈 + 生成三行)→ ⑤ 参数计算(AE 六层 + G 七层 + D 四层,用 dl_u12_verify.py 的数)→ ⑥ p35 / p36 训练历史的解读 → ⑦ p40 五改动(延伸)。WGAN-GP(p42)和 WGAN 代码细节(p44–48)优先级最低。

📘 第十二讲总结:Generative Deep Learning(生成建模 · 自编码器 · GAN · WGAN 附录)

对应讲义 Unit 12 全 50 页;无 Lab / Tutorial notebook,以讲义三段代码(AE p14–19 / GAN p28–36 / WGAN p44–48)当 Lab。本讲回答一个问题:没有标签,网络怎么学会"创造"?路径分四步:① 定义——判别学 Prob(label | features),生成学 Prob(features)(p4–5);② 自编码器——编码器压到 40 维瓶颈、解码器重建、fit(X, X) + mse,1,087,800 参数,随机噪声喂解码器即可生成(p9–19);③ GAN——生成器造假、判别器打假,D 当二分类器训(真 1 假 0),G 在 D 冻结时用"假图标真"训,均衡时 D 50% / G 100%;但训练有五大困难(非收敛、模式崩溃、梯度消失、损失无信息、超参敏感);DCGAN 代码 G 108,092 / D 207,617,23 批/轮,100 轮 462.8 s(p20–36);④ WGAN(附录)——五改动换来"有意义的损失"和"更稳定的训练":wasserstein = mean(y·p)、标签 ±1、去 sigmoid、裁剪 0.05、critic ×3;loss 从 −2037 单调升到 −210,样本只剩干净的 4 和 8(p38–50)。Course Review p10 五考点全部在 p1–37;WGAN 不在 Review 但是 #4 延伸题的最佳答案。

1. 概念地图(50 页)

生成深度学习:没有标签,学会创造 —— AE · GAN · WGAN 判别 Prob(label|features) vs 生成 Prob(features) · MNIST 4+8 · 潜向量 40 两个范式 p4–8:判别(监督·有标签)↔ 生成(通常无监督·无标签)· 应用:人脸 / 风格迁移 / ChatGPT / 音乐 / 世界模型 B · 自编码器 p9–19(合作) C · GAN p20–36(对抗) F · WGAN 附录 p38–50 结构 p10–11 Encoder 784→512→256→40(sigmoid) Latent vector 40 = bottleneck(19.6:1) Decoder 40→256→512→784(sigmoid) 瓶颈迫使学 efficient representation 训练 p17(无标签) Sequential([encoder, decoder]) fit(X, X) · loss=mse · adam 100 轮 · batch 256 · 46 步/轮 · 4,600 步 参数 p16(Dense (in+1)·out) enc 401,920+131,328+10,280 = 543,528 dec 10,496+131,584+402,192 = 544,272 总 1,087,800 · Adam 2,175,602 结果 p18–19 重建:形状对、笔画粗、略模糊(有损) 生成:np.random.random((10,40))→decoder 均匀 [0,1) 匹配 sigmoid 潜层;偶有空洞 应用 p12 生成 / 去噪 / 压缩 / 异常检测 / 降维 一句话:AE = 学"压缩"的解码器 靠重建误差间接学;没有"好坏"标准 → 这正是 GAN 要补的东西:一个判别器 定义 p21–22(Goodfellow 2014) composite model · adversarial pair G:噪声 → 假图(从不看真数据) D:图 → 真(1)/假(0) 概率 骗过聪明 D = 样本好 · 今天 GAN = DCGAN 训练 p23–24(交替) 训 D:真 1 假 0 · BCE · G 不动 训 G:冻结 D · 假图标 1 · −log D(G(z)) D(G(z))=.1→2.30 · .9→.11 · .5→.693 收敛 p25 · 困难 p26(必背) 均衡:G 100%(复合中测)/ D 50%(乱猜) ① 非收敛 ② 模式崩溃 ③ G 梯度消失 ④ 损失无信息(D 一直在变)⑤ 超参敏感 代码 p28–34(Review #5 optional) G: Dense49→BN→7×7→Up→Conv64→BN →Up→Conv64→BN→Conv1 = 108,092 D: Conv64 s2 ×3 + Dropout→Dense1 = 207,617 复合 315,709 · rmsprop · batch 512 23 批/轮(末批 429)· D 2 步 + G 1 步/批 结果 p35–36 gen .65→1.39(ep40)→1.21 · dsc .11→.55↑ 曲线:橙峰 ep2≈2.2 谷 ep8≈.62 · 蓝谷 .07 462.8 s · 样本 4/8/9 · 交叉 ep≈12 简介 p39(Arjovsky 2017) a few changes → stabilize training ① meaningful loss(与质量相关) ② improved stability · D 改名 critic 五改动 p40(因果链) ① Wasserstein loss ② 标签 +1/−1 ③ 去 sigmoid(输出 −∞,+∞) ④ 裁剪 critic 权重(Lipschitz) ⑤ critic 多训(×3)· G 不变 损失 p41 · GP p42 −(1/n)Σy_i·p_i = mean(y·p),代码无负号 真 +1 → −p 推高 · 假 −1 → +p 压低 裁剪 .01(文字)/ .05(代码) WGAN-GP:梯度惩罚代替裁剪 · 无 BN 代码 p44–48 · 结果 p49–50 critic 207,617(同 D)· wgan 315,709 critic 6 步 + G 1 步/批 · dsc÷3 · 1145 s gen −2037→−210↑ · dsc −286→−28↑ 单调 不交叉 · ep90 时间 1833.3 s 异常 样本 p50 4 4 8 8 4 4 8 8 4 4(只有 4/8,干净但粗) 一句话:WGAN = 让 loss 变成"距离"
图 12.S1 Unit 12 概念地图:顶部两范式对比(p4–8)→ 三个模型(AE 合作 / GAN 对抗 / WGAN 附录),每列从"结构 → 训练 → 参数 → 结果 → 一句话"。

2. 参数速查(Course Review "determine" 必算 · 用 Dense (in+1)·out / Conv2D (k²·d+1)·n / BN 2×通道)

模型层(形状变化)公式参数小计 / 备注
AE encoder
p16
Flatten (28,28,1)→784—0543,528
输入 784
输出 40(sigmoid)
Dense 512 relu(784→512)(784+1)×512401,920
Dense 256 relu(512→256)(512+1)×256131,328
Dense 40 sigmoid(256→40)(256+1)×4010,280
(解码器见下)
压缩比 784/40 = 19.6
潜层 sigmoid → 配合 p19 均匀噪声
AE decoder
p16
Dense 256 relu(40→256)(40+1)×25610,496544,272
AE 总 1,087,800
Adam 2,175,602
Dense 512 relu(256→512)(256+1)×512131,584
Dense 784 sigmoid(512→784)(512+1)×784402,192
Reshape 784→(28,28,1)—0
两端占 73.9%,瓶颈层只占 0.9%
GAN generator
p28
Dense 49 LReLU(40→49)(40+1)×492,009108,092
输入 40(N(0,1))
输出 28×28×1(sigmoid)
第一个 BN = 98(49 维,在 Reshape 之前)
BatchNormalization(49)2×4998
Reshape →(7,7,1)—0
UpSampling2D →14×14—0
Conv2D 64 5×5 same LReLU(1→64)(25·1+1)×641,664
BatchNormalization(64)2×64128
UpSampling2D →28×28—0
Conv2D 64 5×5 same LReLU(64→64)(25·64+1)×64102,464
BatchNormalization(64)2×64128
Conv2D 1 5×5 same sigmoid(64→1)(25·64+1)×11,601
GAN discriminator
p29
Conv2D 64 5×5 s2 same LReLU(28→14)(25·1+1)×641,664207,617
输入 28×28×1
输出 1(sigmoid)
Dropout ×3 = 0 参数
Conv2D 64 5×5 s2 same LReLU(14→7)(25·64+1)×64102,464
Conv2D 64 5×5 s2 same LReLU(7→4)(25·64+1)×64102,464
Flatten(4×4×64 = 1,024)—0
Dense 1 sigmoid(1,024→1)(1,024+1)×11,025
复合 GAN
p29
Sequential([G, D]) 总参数315,709(= 108,092 + 207,617)
训练 G 时可训练参数(D 冻结)108,092
WGAN
p45
critic = D 去 sigmoid(激活无参数)207,617(不变)
复合 wgan315,709(不变)

3. 三模型结构对照(AE / GAN / WGAN)

自编码器 AE(p9–19)GAN(p20–36)WGAN(p38–50,附录)
子模型encoder + decoder(合作)generator + discriminator(对抗)generator + critic(对抗)
"向量 → 图"的那一半decoder:Dense 40→256→512→784generator:Dense 49 → 上采样 + Conv ×3同 GAN(create_wgan_generator 原样返回)
另一半encoder:Dense 784→512→256→40discriminator:strided Conv ×3 → Dense(1, sigmoid)critic:同 D 但 Dense(1) 无 sigmoid
噪声np.random.random((10,40)) 均匀 [0,1)np.random.normal(0,1,(n,40))同 GAN
损失mse(重建)BCE(D:真 1 假 0;G:假图标 1)wasserstein = mean(y·p)(真 +1 假 −1)
优化器adamrmsproprmsprop
训练 APIfit(X, X, 100, 256) → 46 步/轮手写循环 · train_on_batch · D 2 步 + G 1 步/批 · 23 批/轮同 GAN 但 critic ×3(6 步)+ G 1 步/批
特殊操作无trainable 开关+ 裁剪 critic 权重 [−0.05, 0.05] + dsc_loss ÷ 3
参数1,087,800G 108,092 · D 207,617 · 复合 315,709同 GAN
训练时间约 1–2 分钟462.8 s(7.7 分钟)1,145 s(19 分钟,约 2.6×)
loss 范围 / 可比性0.06 → 0.02,单调降,可比gen 0.62–2.25、dsc 0.07–0.55,不可跨轮比gen −3000→−210、dsc −700→−28,可比(W 距离估计)
最终样本重建模糊;随机生成 4/8 变体8 9 8 4 9 4 8 4 4 4(有 9 混合体)4 4 8 8 4 4 8 8 4 4(干净但笔画粗)
主要问题潜空间空洞、生成模糊五大困难(p26)裁剪致容量下降(→ WGAN-GP);mode collapse 仍在

4. 训练历史速查(p35 GAN · p49 WGAN · 讲义原数)

EpochGAN timeGAN genGAN dscEpochWGAN timeWGAN genWGAN dscWGAN gen/dsc
1079.0 s0.650.1110135.1 s−2036.83−286.337.11
20123.3 s1.150.3020246.3 s−1066.78−141.587.53
30165.9 s1.350.3730357.5 s−706.60−93.877.53
40207.9 s1.390.4140471.8 s−528.03−70.327.51
50250.4 s1.380.4550587.9 s−421.49−56.227.50
60292.9 s1.340.4860698.6 s−350.06−46.837.48
70336.3 s1.300.5070819.2 s−300.18−40.137.48
80378.6 s1.270.5280921.7 s−262.39−35.117.47
90420.6 s1.240.53901833.3 s ⚠−233.04−31.217.47
100462.8 s1.210.551001145.0 s−209.59−28.097.46
每 10 轮 ≈ 42.6 s · 总 7.7 分钟 · dsc 单调升 · gen 先升后降 · 样本 4/8/9每 10 轮 ≈ 112 s(ep90 异常,疑 1033.3 之误)· 总 19 分钟 · 两 loss 单调趋 0 · 样本 4/8

曲线要点(p36 / p50):GAN 橙线(gen)峰 ep2 ≈ 2.2、谷 ep8 ≈ 0.62、ep40 ≈ 1.39、ep100 1.21;蓝线(dsc)谷 ep5 ≈ 0.07 后单调升到 0.55;两线交叉 ep ≈ 12。WGAN 橙线 ep1 ≈ +1300 → ep5 ≈ −3000 → 单调升到 −210;蓝线 −700 → ep10 ≈ −280 → −28;不交叉。

5. 公式与数值速查

项目公式 / 数值出处
数据量MNIST 训练集 4 → 5,842、8 → 5,851,共 11,693;load_and_prep_mnist("48") 返回 (11693, 28, 28, 1),值域 [0, 1]p14
批次数AE:⌈11693/256⌉ = 46(末批 173);GAN/WGAN:⌈11693/512⌉ = 23(末批 429)p17 / p32
Dense 参数(nin + 1) × noutUnit 4
Conv2D 参数(k · k · din + 1) × n(bias=True)Unit 8
BatchNormalization 参数2 × 特征数(γ, β;另有 2 个非训练的滑动统计量)——看 BN 直接接收的张量形状Unit 7 / p28
Optimizer 参数(Adam)2 × Trainable + 2;rmsprop:Trainable + 1Unit 8 / p17
stride-2 same 尺寸out = ⌈in / 2⌉:28 → 14 → 7 → 4p29
BCE−[y log p + (1−y) log(1−p)];D=0.5 → ln2 = 0.693;G loss = −log D(G(z)):D(G(z)) = 0.9 → 0.105、0.5 → 0.693、0.1 → 2.303、0.01 → 4.605p23–24
LeakyReLU(0.2)x < 0 时输出 0.2x;LeakyReLU(0.2)(−1) = −0.2p28
Wasserstein 损失−(1/n) Σ yi·pi(讲义 p41);代码 backend.mean(y_true * y_pred)(无负号,等价);y ∈ {+1, −1};例:y=[1,1,−1,−1]、p=[5,3,−2,1] → −2.25p41 / p44
Kantorovich-RubinsteinW(pdata, pg) = sup‖f‖L≤1 [E f(real) − E f(fake)];f = criticp41 扩展
Lipschitz 裁剪w ← clip(w, −c, c);c = 0.01(p41 文字)/ 0.05(p46 代码)p41 / p46
压缩比784 / 40 = 19.6p16
GAN 均衡pg = pdata 时 D(x) = pdata(x) / (pdata(x) + pg(x)) = 0.5p25
原始 GAN 目标minG maxD Ex[log D(x)] + Ez[log(1 − D(G(z)))]p21 扩展
步数AE 46×100 = 4,600;GAN 23×100 = 2,300 批(D 4,600 步 / G 2,300 步);WGAN 2,300 批(critic 13,800 步 / G 2,300 步)p17 / p32 / p47

6. 英文术语表(考试作答用原词)

术语含义出处
discriminative modellingpredicting labels from features; supervised; Prob(label | features)p4
generative modellinggenerating new data with specific characteristics; usually unsupervised; Prob(features) or Prob(features, label)p5
autoencoder / encoder / decodercompress to latent code → reconstructp10
latent code / latent vector / latent space / bottleneck低维表示 / 它所在的空间 / 网络中的窄通道p10–11
efficient representationbottleneck 迫使网络捕捉 important featuresp11
composite model / adversarial pairGAN = 两个模型装在一起、互相对抗p21
generator / discriminator / critic造假 / 判真假(概率)/ WGAN 的打分者(实数)p21 / p39
DCGANdeep convolutional GAN;今天 GAN 的默认形态p22
non-trainabletrainable = False;训练 G 时冻结 Dp24 / p29
"learns to become foolish"不冻结 D 时 D 会配合错误标签而变笨p24
equilibrium / 50% accuracy / guessing randomlyGAN 收敛的描述p25
non-convergence / mode collapse / vanishing gradients / uninformative loss / sensitive hyperparameters五大困难p26
Wasserstein loss / Earth Mover's distance−mean(y·p);分布间"搬运"距离p41
Lipschitz constraint / clippingcritic 不能太陡;裁剪权重是实现方法p41
gradient penalty (WGAN-GP)用梯度范数惩罚代替裁剪p42
UpSampling2D / strided convolution生成器上采样 / 判别器下采样(代替池化)p28–29
train_on_batch单批训练原语;GAN 交替训练的基础p31

7. 易错点 Top 12

#易错正确出处
1生成模型 = GANAE、VAE、扩散模型、自回归 LM 都是生成模型;GAN 只是其中一种p1 / p8
2判别建模 = GAN 的判别器前者是范式(p4),后者是 GAN 里的一个子网络(p21);GAN 的 D 是判别建模思想的一个应用p4
3自编码器 fit(X, y)fit(X_train, X_train)——输入 = 目标;无标签;loss = mse(回归)p17
4p19 用 autoencoder.predict 生成decoder.predict(np.random.random((10, 40)))——跳过编码器;均匀 [0,1) 匹配 sigmoid 潜层p19
5生成器第一个 BN 有 2 个参数BN 在 Dense(49) 之后、Reshape 之前 → 2×49 = 98;G 总 108,092(不是 107,996)p28
6判别器第三次 stride-2 后是 7→3same + stride 2 = ⌈7/2⌉ = 4;Flatten 1,024;Dense(1) 1,025p29
7训练 G 时假图标签 0训 D 时假图 0、训 G 时假图 1(假图标真);同一张图、两个标签,取决于训练谁p23–24 / p31
8训练 G 时 G 也要冻结 / 输入是假图冻结的是 D;train_generator 的输入是噪声(复合模型从 G 开始)p24 / p31
9dsc_loss 上升 = 训练变差GAN 里 dsc_loss 升 = D 越来越判不出假图 = G 在进步;gen_loss 低 ≠ 样本好(uninformative)p35–36
10WGAN 假图标签 0 / 损失带负号 / 裁剪 0.01标签 −1;代码 mean(y·p) 无负号(分数方向是约定);裁剪代码 0.05(p41 文字才是 0.01);去掉 sigmoid 不改参数数p41 / p44–46
11WGAN loss 从 −3000 升到 −210 是"变差"是变好:|loss| = W 距离估计,缩小 10 倍 = 分布靠近 10 倍;ep90 的 1833.3 s 是记录异常p49–50
1223 批 / 22 批;末批 512⌈11693/512⌉ = 23;末批 11693 − 22×512 = 429;AE:46 批、末批 173p32

8. 自测 12 题(先答再翻页码)

#题目答案出处
1用一句英文区分 discriminative 和 generative modelling(含数学记号)Discriminative estimates Prob(label | features) from labelled data; generative estimates Prob(features) or Prob(features, label), usually from unlabelled data.p4–5
2Why is a bottleneck necessary in an autoencoder?Without it the network can learn the identity function; the bottleneck forces it to capture only important features (efficient representation).p11
3写出用 AE 生成 10 张样本的三行代码X = np.random.random((10, SZ_LATENT_AE)); samples = decoder.predict(X, verbose=0); plot_samples(samples)p19
4AE 的总参数?压缩比?每轮几步?1,087,800;784/40 = 19.6;⌈11693/256⌉ = 46p16–17
5Generator and discriminator: which one sees real data? Which one is a classifier?Discriminator sees both real and fake and is a binary classifier (real=1, fake=0); generator never sees real data.p21 / p23
6Training the generator: two key operations and whySet D non-trainable (else D "learns to become foolish"); label fakes as real (so loss = −log D(G(z)) is small when G succeeds).p24
7If D(G(z)) = 0.1, what is the generator's loss? And 0.9?−ln 0.1 = 2.30;−ln 0.9 = 0.11p24
8State the five difficulties in training GANsNon-convergence; mode collapse; vanishing gradients of G; uninformative loss of G; many and sensitive hyperparameters.p26
9GAN generator / discriminator / composite parameter counts108,092 / 207,617 / 315,709(trainable when training G: 108,092)p28–29
10How many batches per epoch (batch 512)? Last batch size? Total critic updates in WGAN for 100 epochs?23;429;23 × 3 × 100 = 6,900 critic training calls (13,800 train_on_batch steps)p32 / p47
11Five changes WGAN makes to GANWasserstein loss; labels +1/−1; remove critic's sigmoid; clip critic weights after each update; train critic multiple times per generator update.p40
12Why can the critic be trained more often than the generator in WGAN, unlike the discriminator in GAN?The Wasserstein loss is linear in the critic output (no sigmoid/log saturation), so a stronger critic gives a better distance estimate without vanishing gradients for the generator.p41

9. 与前后讲的联系

单元在本讲中的复用 / 对照本讲页
Unit 1–2(ML 概念 / 神经网络基础)判别 vs 生成的范式之分;"没有标签能不能学"是本讲的出发点p4–5
Unit 4(全连接网络与回归)Dense 参数 (nin+1)·nout 用了 10 次(AE 六层 + G/D 各一层);AE 的 mse 是 Unit 4 的回归损失p16–17 / p28–29
Unit 5(分类与反向传播)MNIST 加载的改造版(只要训练集、只要 4 和 8、不要标签);Dense(1, sigmoid) + BCE 二分类是 D 的输出层p14 / p29
Unit 6(评估·泛化·正则化)history.history["loss"] + df.plot 画曲线;无验证集 / 无早停——生成模型"靠眼睛评估"p17 / p36 / p50
Unit 7(Dropout·BN·初始化·优化器)BN = 2×通道(3 次)、Dropout(0.5) 削弱 D、Adam(AE)vs rmsprop(GAN)p28–29
Unit 8(卷积原理)Conv2D 参数 (k²·d+1)·n 用了 6 次;same + stride 2 = ⌈n/2⌉;UpSampling2D 是"反向下采样"p28–29
Unit 9(CNN 架构与迁移学习)DCGAN 的卷积结构;自编码器的"编码器当特征提取器"= 无监督预训练p22 / p28–29 / p12
Unit 10–11(文本)ChatGPT = Unit 11 文本生成的放大版(自回归,不是 GAN);"生成模型 ≠ GAN"的例子p8
Project / 期末Project 的"图像分类 + 文本分析"是判别任务——本讲的 AE 异常检测、GAN 数据增强可作为加分项;期末 Review p10 五考点全在 p1–37Review
一句话收尾:自编码器教会网络"压缩"(解码器 = 向量 → 图),GAN 教会网络"造假"(用判别器代替 mse 当老师),WGAN 教会网络"量距离"(用 Wasserstein 损失代替 BCE 让 loss 有意义)。三者共用同一个解码器 / 生成器的骨架——变的只是"老师":mse → 判别器 → critic。

🧪 交互:生成模型实验台(AE / GAN 参数计算器 · GAN 训练模拟器 · BCE vs Wasserstein 梯度对比)

Course Review p10 的五个考点里有三个是"算参数 / 说原理 / 说问题"——所以这个实验台为手算与直觉服务:① 参数计算器把 p16 / p28 / p29 / p45 的四张参数表变成可改的数——AE 改 h1 / h2 / latent,立刻得到逐层 Dense 参数、enc / dec 小计、压缩比与 Adam 变量数;GAN 改 latent / dropout,立刻得到 G / D / 复合模型的参数,并自动判断"第一个 BN 的参数为什么是 2×49 而不是 2";② GAN 训练模拟器按 p23 / p24 的两步交替(D 走 2 步、G 走 1 步)在 SVG 上实时画出 D(x)、D(G(z)) 与两条 loss 曲线,并可切换 "健康 / 模式崩溃 / 震荡" 三种剧本看 p26 五困难的形状;③ BCE vs Wasserstein把 p41 的公式摆到滑块上:拖 D(G(z)) 从 0.01 到 1,看 BCE 的梯度如何在两端饱和(假图已经骗过 D 时 G 学不动)而 Wasserstein 的梯度恒为 ±1——这正是 p40 改动①的动机。改任何控件,数字和图立刻更新。

A · AE 与 GAN 参数计算器(p16 · p28 · p29 · p45 · Review #5)
提示:AE 的 h1 / h2 / L 只对 AE 有效;对 GAN / 判别器 / critic 模型,latent 改的是 Dense 的输入维度(讲义 100),batch 决定"每轮批次数"(512 → 23 批,末批 429;256 → 46 批,末批 173)。切到 "GAN 生成器" 时注意第一个 BN 作用在 Dense 输出的 49 维向量上(Reshape 之前),所以参数是 2×49 = 98,不是 2×1。
B · GAN 训练模拟器(p23 训练 D · p24 训练 G · p25 收敛 · p26 五困难)
D 的输出:D(x)(真图)与 D(G(z))(假图),虚线 = 0.5
损失:gen(非饱和 BCE)与 dsc(BCE 平均)
G 的样本(10 个 z → 10 张图 → 判成的数字)
怎么读:点 "步进 1 轮" 看 p23 / p24 的一次交替——D 先更新(dsc 下降、D(G(z)) 被压低),G 再更新(D(G(z)) 被抬高一点,gen 下降)。"健康" 剧本在 40 轮左右达到 p35 表里的 gen 1.39 / dsc 0.41,100 轮到 1.21 / 0.55;"模式崩溃" 剧本里多样性指标会一路掉到 1 种数字,而 dsc/gen 看起来仍然"正常"——这就是 p26 第 3 条说的"loss 正常但样本单一"。
C · BCE vs Wasserstein:为什么 G 在两端学不动(p24 非饱和损失 · p41 Wasserstein 损失 · p42 梯度惩罚)
G 的损失随 D(G(z)) 的变化( BCE 非饱和 −log(D(G(z))) vs Wasserstein −p )
怎么读:拖滑块到 0.99——BCE 的曲线已经贴地,斜率 ≈ 1/0.99 ≈ 1.01,G 几乎没有梯度可学(p24 "D(G(z)) → 1 时 G 学不到东西");拖到 0.01——斜率 1/0.01 = 100,梯度爆炸。Wasserstein 的损失是一条直线,斜率永远是 −1,所以 p40 说 "no need to balance G and D"。