第 15 章 · 生成对抗网络
Understanding Deep Learning — Generative adversarial networks
A generative adversarial network or GAN is an unsupervised model that aims to generate new samples that are indistinguishable from a set of training examples. GANs are just mechanisms to create new samples; they do not build a probability distribution over the modeled data and hence cannot evaluate the probability that a new data point belongs to the same distribution.
In a GAN, the main generator network creates samples by mapping random noise to the output data space. If a second discriminator network cannot distinguish between the generated samples and the real examples, the samples must be plausible. If this network can tell the difference, this provides a training signal that can be fed back to improve the quality of the samples. This idea is simple, but training GANs is difficult: the learning algorithm can be unstable, and although GANs may learn to generate realistic samples, this does not imply that they learn to generate all possible samples.
GANs have been applied to many types of data, including audio, 3D models, text, video, and graphs. However, they have found the most success in the image domain, where they can produce samples that are almost indistinguishable from real pictures. Accordingly, the examples in this chapter focus on synthesizing images.
一个生成对抗网络或 GAN 是一种无监督模型,旨在生成与一组训练样本无法区分的新样本。 GAN 只是创建新样本的机制;它们不会为建模数据构建概率分布,因此无法评估新数据点属于同一分布的概率。
在 GAN 中,主要的生成器网络通过将随机噪声映射到输出数据空间来创建样本。如果第二个判别器网络无法区分生成的样本和真实示例,那么这些样本必定是合理的。如果这个网络能够区分差异,这就提供了一个训练信号,可以反馈回去以提高样本质量。这个想法很简单,但训练 GAN 很困难:学习算法可能不稳定,而且尽管 GAN 可能学会生成逼真的样本,这并不意味着它们学会生成所有可能的样本。
GAN 已被应用于许多类型的数据,包括音频、三维模型、文本、视频和图。然而,它们在图像领域取得了最大的成功,在该领域中,它们可以生成几乎无法与真实图片区分的样本。因此,本章中的示例侧重于图像合成。
We aim to generate new samples{ x ∗ j} that are drawn from the same distribution as a set of real training data{ x i}. A single new sample x ∗ j is generated by (i) choosing a latentvariable z j from a simple base distribution (e.g., a standard normal) and then (ii) passing this data through a network x ∗ j= g[ z j, θ] with parameters θ. This network is known as the generator. During the learning process, the goal is to find parameters θ so that the samples{ x ∗
j} look “similar” to the real data{ x i} (see figure 14.2a).
Similarity can be defined in many ways, but the GAN uses the principle that the samples should be statistically indistinguishable from the true data. To this end, a second network f[•, ϕ] with parameters ϕ called the discriminator is introduced. This network aims to classify its input as being a real example or a generated sample. If this
我们旨在生成新的样本 { x ∗ j},这些样本是从与一组真实训练数据 { x i} 相同的分布中抽取的。单个新样本 x ∗ j 的生成方式是: (i) 从一个简单的基础分布(例如标准正态分布)中选择一个隐变量 z j,然后 (ii) 将该数据输入网络 x ∗ j= g[ z j, θ],其参数为 θ。这个网络被称为生成器。在学习过程中,目标是找到参数 θ,使得样本 { x ∗
j} 看起来与真实数据 { x i} “相似”(见图 14.2a)。相似性可以有多种定义方式,但 GAN 采用的原则是,样本在统计上应与真实数据不可区分。为此,引入了一个参数为 ϕ 的第二个网络 f[•, ϕ],称为判别器。该网络旨在将其输入分类为真实样本或生成样本。如果这
proves impossible, the generated samples are indistinguishable from the real examples, and we have succeeded. If it is possible, the discriminator provides a signal that can be used to improve the generation process.
Figure 15.1 illustrates this scheme. We start with a training set{xi} of real 1D examples. A different batch of ten of these examples{xi}10 i=1 is shown in each panel (cyan arrows). To create a batch of samples{x∗
被证明不可能,则生成样本与真实样本不可区分,我们就成功了。如果可能,判别器会提供一个可用于改进生成过程的信号。图 15.1 说明了这一方案。我们从真实一维样本的训练集{xi} 开始。每个面板中展示的是这些样本中的另一批十个样本{xi}10 i=1 (青色箭头)。为了创建一批样本{x∗

j}, we use the simple generator:
where latent variables{zj} are drawn from a standard normal distribution, and the parameter θ translates the generated samples along the x-axis (figure 15.1).
j},我们使用简单的生成器:
其中隐变量{zj} 从标准正态分布中抽取,参数 θ 沿 x 轴平移生成的样本(图 15.1)。
At initialization, θ= 3.0, and the generated samples (orange arrows) lie to the left of the real examples (cyan arrows). The discriminator is trained to distinguish the generated samples from the real examples (the sigmoid curve indicates the probability that a data point is real). During training, the generator parameters θ are manipulated to increase the probability that its samples are classified as real. Here, this means increasing θ so that the samples move rightwards where the sigmoid curve is higher.
在初始化时, θ= 3.0,并且生成的样本(橙色箭头)位于真实样本(青色箭头)的左侧。判别器被训练用于区分生成的样本与真实样本(sigmoid 曲线表示数据点为真实的概率)。在训练过程中,生成器参数 θ 被调整,以提高其样本被分类为真实的概率。这里,这意味着增大 θ,使样本向右移动,移向 sigmoid 曲线更高的区域。
We alternate between updating the discriminator and the generator. Figures 15.1b–c show two iterations of this process. It gradually becomes harder to classify the data, so the impetus to change θ becomes weaker (i.e., the sigmoid becomes flatter). At the end of the process, there is no way to distinguish the two sets of data; the discriminator, which now has chance performance, is discarded, and we are left with a generator that makes plausible samples.
因此,变化的动力 θ 变弱了(即 sigmoid 变得更平缓)。在过程结束时,已经无法区分两组数据;此时判别器仅具有随机猜测的性能,因此被丢弃,最终留下一个能够生成合理样本的生成器。
We now define the loss function for training GANs more precisely.
The discriminator f[ x , ϕ] takes input x, has parameters ϕ, and returns a scalar that is higher when it believes the input is a real example. This is a binary classification task, so we adapt the binary cross-entropy loss function (section 5.4), which originally had the form:
现在,我们更精确地定义用于训练 GAN 的损失函数。判别器 f[ x ϕ] 接收输入 x,具有参数 ϕ,并返回一个标量,当它认为输入是真实样本时,该标量值更高。这是一个二分类任务,因此我们采用二分类交叉熵损失函数(第 5.4 节),其原始形式为:


where yi∈{0, 1} is the label, and sig[•] is the logistic sigmoid function (figure 5.7).
In this case, we assume that the real examples x have label y= 1 and the generated samples x ∗ have label y= 0 so that:
其中 yi∈{0, 1} 是标签, sig[•] 是 logistic sigmoid 函数(图 5.7)。
where i and j index the real examples and generated samples, respectively. Now we substitute the definition for the generator x ∗
j= g[ z j, θ] and note that we must maximize with respect to θ since we want the generated samples to be misclassified (i.e., have low likelihood of being synthetic or high negative log-likelihood):
其中 i 和 j 分别用于索引真实样本和生成样本。现在我们将生成器的定义 x ∗
j= g[ z j, θ] 代入,并注意我们必须关于 θ 进行最大化,因为我们希望生成样本被错误分类(即,是合成样本的可能性较低或负对数似然较高):
Equation 15.4 is a more complex loss function than we have seen before; the discriminator parameters ϕ are manipulated to minimize the loss function, and the generative parameters θ are manipulated to maximize the loss function. GAN training is characterized as a minimax game; the generator tries to find new ways to fool the discriminator, which in turn searches for new ways to distinguish generated samples from real examples. Technically, the solution is a Nash equilibrium — the optimization algorithm searches for a position that is simultaneously a minimum of one function and a maximum of the other. If training proceeds as planned, then upon convergence, g[ z , θ] will be drawn from the same distribution as the data, and sig[ f[•, ϕ]] will be at chance (i.e., 0.5).
To train the GAN, we can divide equation 15.4 into two loss functions:
公式 15.4 比我们以前见过的损失函数更复杂;判别器参数 ϕ 被调整以最小化损失函数,生成器参数 θ 被调整以最大化损失函数。 GAN 训练被刻画为一种极小极大博弈;生成器试图寻找新的方式来欺骗判别器,而判别器则反过来寻找新的方式来区分生成样本和真实样本。严格来说,解是一个纳什均衡 —— 优化算法寻找一个同时是某个函数最小值和另一个函数最大值的位置。如果训练按计划进行,那么收敛时, g[ z θ] 将从与数据相同的分布中采样,而 sig[ f[•, ϕ]] 将达到随机猜测水平(即 0.5)。
为了训练 GAN,我们可以将公式 15.4 分成两个损失函数:


where we multiplied the second function by minus one to convert to a minimization problem and dropped the second term, which has no dependence on θ. Minimizing the first loss function trains the discriminator. Minimizing the second trains the generator. At each step, we draw a batch of latent variables z j from the base distribution and pass these through the generator to create samples x ∗
j= g[ z j, θ]. Then we choose a batch of real training examples x i. Given the two batches, we can now perform one or more gradient descent steps on each loss function (figure 15.2).
其中,我们将第二个函数乘以 −1,以将其转换为最小化问题,并丢弃了第二项,因为该项不依赖于 θ。最小化第一个损失函数可以训练判别器。最小化第二个可以训练生成器。在每一步中,我们从基础分布中抽取一批隐变量 z j,并将它们通过生成器以生成样本 x ∗
j= g[ z j, θ]。然后我们选择一批真实训练样本 x i。给定这两个批次,我们现在可以对每个损失函数执行一次或多次梯度下降步骤(图 15.2)。
The deep convolutional GAN or DCGAN was an early GAN architecture specialized for generating images (figure 15.3). The input to the generator g[ z , θ] is a 100D latent
深度卷积 GAN 或 DCGAN 是一种早期的 GAN 架构,专门用于生成图像(图 15.3)。生成器 g[ z θ] 的输入是一个 100 维隐
variable z sampled from a uniform distribution. This is then mapped to a 4 × 4 spatial representation with 1024 channels using a linear transformation.
Four convolutional layers follow, each of which uses a fractionally-strided convolution that doubles the resolution (i.e., a convolution with a stride of 0.5). At the final layer, the 64 × 64 × 3 signal is passed through a tanh function to generate an image x ∗ in the range[−1, 1]. The discriminator f[•, ϕ] is a standard convolutional network where the final convolutional layer reduces the size to 1 × 1 with one channel. This single number is passed through a sigmoid function sig[•] to create the output probability.
变量 z 从均匀分布中采样。然后使用线性变换将其映射为一个具有 1024 个通道的 4 × 4 空间表示。随后有四个卷积层,每一层都使用一种分数步长卷积,使分辨率加倍(即步长为 0.5 的卷积)。在最后一层, 64 × 64 × 3 信号经过 tanh 函数,生成一个图像 x ∗,其范围为 [−1, 1]。判别器 f[•, ϕ] 是一个标准卷积网络,其最后的卷积层将尺寸减小为 1 × 1,仅保留一个通道。这个单一数值经过 sigmoid 函数 sig[•],生成输出概率。

After training, the discriminator is discarded. To create new samples, latent variables z are drawn from the base distribution and passed through the generator. Example results are shown in figure 15.4.
训练完成后,判别器会被丢弃。为了生成新样本,从基础分布中抽取隐变量 z 并传递给生成器。示例结果如图 15.4 所示。
Theoretically, the GAN is fairly straightforward. However, GANs are notoriously difficult to train. For example, to get the DCGAN to train reliably, it was necessary to (i) use strided convolutions for upsampling and downsampling; (ii) use BatchNorm in both generator and discriminator except in the last and first layers, respectively; (iii) use the leaky ReLU activation function (figure 3.13) in the discriminator; and (iv) use the Adam optimizer but with a lower momentum coefficient than usual. This is unusual. Most deep learning models are relatively robust to such choices.
理论上, GAN 相当简单。然而, GAN 以难以训练而闻名。例如,为了让 DCGAN 可靠地训练,必须: (i) 使用步幅卷积进行上采样和下采样; (ii) 在生成器和判别器中都使用 BatchNorm,但分别不在最后一层和第一层使用; (iii) 在判别器中使用泄漏 ReLU 激活函数(图 3.13);以及 (iv) 使用 Adam 优化器,但采用比通常更低的动量系数。这很不寻常。大多数深度学习模型对这类选择相对稳健。

A common failure mode is that the generator makes plausible samples, but these only represent a subset of the data (e.g., for faces, it might never generate faces with beards). This is known as mode dropping. An extreme version of this phenomenon can occur where the generator entirely or mostly ignores the latent variables z and collapses all samples to one or a few points; this is known as mode collapse (figure 15.5).
一种常见的失败模式是:生成器生成看似合理的样本,但这些样本只代表数据的一个子集(例如,对于人脸,它可能从不生成有胡子的人脸)。这被称为模式缺失。这种现象的极端版本可能是生成器完全或大部分忽略隐变量 z,并将所有样本坍缩到一个或少数几个点;这被称为模式崩溃(图 15.5)。

To understand why GANs are difficult to train, it’s necessary to understand exactly what the loss function represents.
要理解为什么 GANs 难以训练,有必要准确理解损失函数究竟代表什么。
If we divide the two sums in the first line of equation 15.5 by the numbers I, J of real and generated samples, then the loss function can be written in terms of expectations:
where Pr( x ∗) is the probability distribution over the generated samples, and Pr( x ) is the true probability distribution over the real examples.
如果将公式 15.5 第一行的两个和分别除以真实样本和生成样本的数量 I, J,则损失函数可以用期望表示:
其中, Pr (x ∗) 是生成样本上的概率分布,而 Pr (x) 是真实样本上的真实概率分布。
When I= J, the optimal discriminator for an example ˜ x of unknown origin is: Pr( real |˜ x ) = sig
当 I= J 时,对于来源未知的样本 ˜ x,最优判别器为: Pr( real |˜ x ) = sig

where on the right hand side, we evaluate ˜ x against the generated distribution Pr( x ∗) and the real distribution Pr( x ). Substituting into equation 15.6, we get:
其中,在等式右侧,我们将 ˜ x 针对生成分布 Pr (x ∗) 和真实分布 Pr (x) 进行评估。代入公式 15.6,得到:
Disregarding additive and multiplicative constants, this is the Jensen-Shannon divergence between the synthesized distribution Pr(x∗) and the true distribution Pr(x): coverage quality
忽略加法和乘法常数,这就是 Jensen-Shannon 散度合成分布 Pr (x∗) 与真实分布 Pr (x) 之间: coverage quality

where DKL[•||•] is the Kullback-Leibler divergence. The first term indicates the distance will be small if, wherever the sample den-
sity Pr( x ∗) is high, the mixture (Pr( x ∗)+Pr( x ))/2 has high probability. In other words, it penalizes regions with samples x ∗ but no real examples x; it enforces quality. The second term says that the distance will be small if, wherever the true density Pr( x )
其中 DKL[•||•] 是 Kullback-Leibler 散度。第一项表明,如果在样本密度 Pr( x ∗) 高的任何地方,混合分布 (Pr( x ∗)+Pr ( x ))/2 具有高概率,则距离会很小。换句话说,它惩罚有样本 x ∗ 但没有真实示例 x 的区域;它强调质量。第二项表明,如果真实密度 Pr( x ) 的任何地方,距离会很小
is high, the mixture(Pr( x ∗) + Pr( x ))/2 has high probability. In other words, it penalizes regions with real examples but no samples. It enforces coverage. Referring to equation 15.6, we see that the second term does not depend on the generator, which consequently doesn’t care about coverage; it is happy to generate a subset of possible examples accurately. This is the putative reason for mode dropping.
高,混合分布 (Pr (x ∗) + Pr (x)) /2 具有高概率。换句话说,它惩罚有真实示例但没有样本的区域。它强调覆盖度。参考方程 15.6,我们看到第二项不依赖于生成器,因此生成器不关心覆盖度;它乐于准确地生成可能示例的一个子集。这是模式坍塌的推测原因。

In the previous section, we saw that when the discriminator is optimal, the loss function maximizes a measure of the distance between the generated and real samples. However, there is a potential problem with using this distance between probability distributions as the criterion for optimizing GANs. If the probability distributions are completely disjoint, this distance is maximal, and any small change to the generator will not decrease the loss. The same phenomenon can be seen when we consider the original formulation; if the discriminator can perfectly separate the generated and real samples, no small change to the generated data will change the classification score (figure 15.6).
在前一节中,我们看到,当判别器达到最优时,损失函数会最大化生成样本与真实样本之间距离的某种度量。然而,将概率分布之间的这种距离作为优化 GAN 的准则存在潜在问题。如果概率分布完全不相交,这种距离就会达到最大值,并且对生成器的任何微小更改都不会降低损失。在考虑原始公式时也可以看到同样的现象;如果判别器能够完美区分生成样本和真实样本,那么对生成数据的任何微小更改都不会改变分类得分(图 15.6)。
Unfortunately, the distributions of generated samples and real examples may really be disjoint; the generated samples lie in a subspace that is the size of the latent variable z, and the real examples also lie in a low-dimensional subspace due to the physical processes that created the data (figure 1.9).
There may be little or no overlap between these subspaces, and the result is very small or no gradients.
Figure 15.7 provides empirical evidence to support this hypothesis. If the DCGAN generator is frozen and the discriminator is updated repeatedly so that its classification performance improves, the generator gradients decrease. In short, there is a very fine balance between the quality of the discriminator and the generator; if the discriminator becomes too good, the training updates of the generator are attenuated.
不幸的是,生成样本和真实样本的分布可能确实不相交;生成样本位于一个维度大小与隐变量 z 相同的子空间中,而真实样本由于产生数据的物理过程也位于一个低维子空间中(图 1.9)。这些子空间之间可能几乎没有或完全没有重叠,结果就是梯度非常小或根本没有梯度。
图 15.7 提供了支持这一假设的实证证据。如果冻结 DCGAN 生成器,并反复更新判别器,使其分类性能提升,则生成器梯度会减小。简言之,判别器与生成器的质量之间存在非常微妙的平衡;如果判别器变得太好,生成器的训练更新就会被削弱。
The previous sections showed that (i) the GAN loss can be interpreted in terms of distances between probability distributions and that (ii) the gradient of this distance
becomes zero when the generated samples are too easy to distinguish from the real examples. The obvious way forward is to choose a distance metric with better properties.
The Wasserstein or (for discrete distributions) earth mover’s distance is the quantity of work required to transport the probability mass from one distribution to create the other. Here, “work” is defined as the mass multiplied by the distance moved. This immediately sounds more promising; the Wasserstein distance is well-defined even when the distributions are disjoint and decreases smoothly as they become closer to one another.
前面几节表明, (i) GAN 损失可以从概率分布之间的距离来解释,并且 (ii) 该距离的梯度
瓦瑟斯坦距离,或(对于离散分布)推土机距离,是将一个分布中的概率质量搬运以形成另一个分布所需的工作量。这里,“工作”定义为质量乘以移动距离。这立刻听起来更有前景;即使分布不相交,瓦瑟斯坦距离也有明确定义,并随着它们彼此接近而平滑减小。

The Wasserstein distance is easiest to understand for discrete distributions (figure 15.8). Consider distributions Pr(x=i) and q(x=j) defined over K bins. Assume there is a cost Cij associated with moving one unit of mass from bin i in the first distribution to bin j in the second; this cost might be the absolute difference |i−j| between the indices. The amounts that are moved form the transportplan and are stored in a matrix P.
The Wasserstein distance is defined as:
对于离散分布,瓦瑟斯坦距离最容易理解(图 15.8)。考虑分布 Pr (x=i) 和 q (x=j),它们定义在 K 个箱上。假设存在成本 Cij,它与将一单位质量从第一个分布中的箱 i 移动到第二个分布中的箱 j 相关;该成本可能是索引之间的绝对差 |i−j|。被移动的量构成运输计划,并存储在矩阵 P 中。
Wasserstein 距离定义为:
In other words, the Wasserstein distance is the solution to a constrained minimization problem that maps the mass of one distribution to the other. This is inconvenient as we must solve this minimization problem over the elements Pij every time we want to compute the distance. Fortunately, this is a standard problem that is easily solved for small systems of equations. It is a linear programming problem in its primal form: primal form dual form where p contains the vectorized elements Pij that determine the amount of mass moved, c contains the distances, Ap = b contains the initial distribution constraints, and p ≥0 ensures the masses moved are non-negative. 1
满足以下约束条件:
换句话说, Wasserstein 距离是一个约束最小化问题的解,该问题将一个分布的质量映射到另一个分布。这很不方便,因为每次想要计算距离时,我们都必须针对元素 Pij 求解这个最小化问题。幸运的是,这是一个标准问题,对于小型方程组很容易求解。它是一个线性规划问题,采用其原始形式:原始形式对偶形式确保所移动的质量非负。 1

As for all linear programming problems, there is an equivalent dual problem with the same solution. Here, we maximize with respect to a variable f that is applied to the initial distributions, subject to constraints that depend on the distances c. The solution to this dual problem is:
初始分布,并受依赖于距离 c 的约束。该对偶问题的解为:
subject to the constraint that:
In other words, we optimize over a new set of variables {fi} where adjacent values cannot change by more than one.
受以下约束:
换句话说,我们在一组新的变量{fi} 上进行优化,其中相邻值的变化不能超过 1。

Translating these results back to the continuous multi-dimensional domain, the equivalent of the primal form (equation 15.10) is:
将这些结果转换回连续多维域,原始形式(公式 15.10)的等价形式为:
subject to constraints similar to equation 15.11 on the transport plan π( x 1, x 2) representing the mass moved from position x 1 to x 2.
The equivalent of the dual form (equation 15.12) is: subject to the constraint that the Lipschitz constant of the function f[ x ] is less than one
并施加类似于公式 15.11 的约束,其中传输方案 π (x 1, x 2) 表示从位置 x 1 移动到 x 2 的质量。对偶形式(公式 15.12)的等价形式为:受以下约束:函数 f[ x ] 的利普希茨常数小于 1
(i.e., the absolute gradient of the function is less than one).
(即函数的绝对梯度小于 1)。
In the context of neural networks, we maximize over the space of functions f[ x ] by optimizing the parameters ϕ in a neural network f[ x , ϕ], and we approximate these integrals using generated samples x ∗
i and real examples x i:
在神经网络的背景下,我们在函数空间 f[ x ] 进行最大化,通过优化神经网络 f[ x ϕ] 中的参数 ϕ,并使用生成的样本 x ∗
i 和真实样本 x i 来近似这些积分:
where we must constrain the neural network discriminator f[ x i, ϕ] to have an absolute gradient norm of less than one at every position x:
One way to achieve this is to clip the discriminator weights to a small range (e.g., ±0.01). An alternative is the gradient penalty Wasserstein GAN or WGAN-GP, which adds a regularization term that increases as the gradient norm deviates from unity.
其中,我们必须约束神经网络判别器 f[ x i, ϕ] 使其在每个位置 x 的绝对梯度范数小于 1:

The Wasserstein formulation makes GAN training more stable. However, further machinery is needed to generate high-quality images. We now review progressive growing, minibatch discrimination, and truncation, which all improve output quality. In progressive growing (figure 15.9), we first train a GAN that synthesizes 4 × 4 images using an architecture similar to the DCGAN. Then we add subsequent layers to the generator, which upsample the representation and perform further processing to create
Wasserstein 表述使 GAN 训练更加稳定。然而,要生成高质量图像还需要进一步的机制。我们现在回顾渐进式增长、小批量判别和截断,它们都能改善输出质量。

an 8 × 8 image. The discriminator also has extra layers added to it so that it can receive the higher-resolution images and classify them as either being generated samples or real examples. In practice, the higher-resolution layers gradually “fade in” over time; initially, the higher-resolution image is an upsampled version of the previous result, passed via a residual connection, and the new layers gradually take over.
一张 8 × 8 图像。判别器还增加了额外的层,以便能够接收更高分辨率的图像,并将其分类为生成样本或真实样本。在实践中,更高分辨率的层会随着时间逐渐“淡入”;最初,更高分辨率的图像是先前结果的上采样版本,通过残差连接传递,而新层逐渐接管。


Mini-batch discrimination ensures that the samples have sufficient variety and hence helps prevent mode collapse. This can be done by computing feature statistics across the mini-batches of synthesized and real data. These can be summarized and added as a feature map (usually toward the end of the discriminator). This allows the discriminator to send a signal back to the generator, encouraging it to include a similar amount of variation in the synthesized data as in the original dataset. Another trick to improve generation results is truncation (figure 15.10), in which only latent variables z with high probability (i.e., close to the mean) are chosen during sampling. This reduces the variation in the samples but improves their quality. Careful
normalization and regularization schemes also improve sample quality. Using combinations of these methods, GANs can synthesize varied and realistic images (figure 15.11). Moving smoothly through the latent space can also sometimes produce realistic interpolations from one synthesized image to another (figure 15.12).
小批量判别确保样本具有足够的多样性,从而有助于防止模式坍塌。这可以通过计算合成数据与真实数据的小批量特征统计量来实现。这些统计量可以被汇总并作为特征图添加(通常靠近判别器的末端)。这使得判别器能够向生成器回传信号,鼓励其在合成数据中包含与原始数据集中相似的变化量。另一个改善生成结果的技巧是截断(图 15.10),其中在采样期间只选择具有高概率(即接近均值)的隐变量 z。这会减少样本的变化量,但提高其质量。谨慎
归一化和正则化方案也能提升样本质量。结合使用这些方法, GAN 能够合成多样且逼真的图像(图 15.11)。在隐空间中平滑移动有时也能生成从一张合成图像到另一张合成图像的逼真插值(图 15.12)。
GANs produce realistic images but don’t specify their attributes: we can’t choose the hair color, ethnicity, or age of faces, without training separate GANs for each combination of characteristics. Conditional generation models provide us with this control.
GAN 能够生成逼真的图像,但不会指定其属性:我们无法选择人脸的发色、种族或年龄,除非为每种特征组合分别训练独立的 GAN。条件生成模型为我们提供了这种可控性。
The conditionalGAN passes a vector c of attributes to both the generator and discriminator, which are now written as g[ z , c , θ] and f[ x , c , ϕ], respectively. The generator aims to transform the latent variable z into a data sample x with the correct attribute c. The discriminator’s goal is to distinguish between (i) the generated sample with the target attribute or (ii) a real example with the real attribute (figure 15.13a).
For the generator, the attribute c can be appended to the latent vector z. For the discriminator, it may be appended to the input if the data are 1D. If the data comprise images, the attribute can be linearly transformed to a 2D representation and appended as an extra channel to the discriminator input or to one of its intermediate hidden layers.
条件 GAN 将属性向量 c 同时传递给生成器和判别器,二者现在分别写为 g[ z , c θ] 和 f[ x , c ϕ]。生成器旨在将隐变量 z 转换为带有正确属性 c 的数据样本 x。判别器的目标是区分(i)具有目标属性的生成样本,或(ii)具有真实属性的真实样本(图 15.13a)。
对于生成器,属性 c 可以附加到潜在向量 z。对于判别器,如果数据是 1D,可以将其附加到输入。如果数据包含图像,可以将属性线性转换为 2D 表示,并作为额外通道附加到判别器输入或其某个中间隐藏层。
The auxiliary classifier GAN or ACGAN simplifies conditional generation by requiring that the discriminator correctly predicts the attribute (figure 15.13b). For a discrete
辅助分类器 GAN 或 ACGAN 通过要求判别器正确预测属性来简化条件生成(图 15.13b)。对于离散

attribute with C categories, the discriminator takes the real/synthesized image as input and has C + 1 outputs; the first is passed through a sigmoid function and predicts if the sample is generated or real. The remaining outputs are passed through a softmax function to predict the probability that the data belongs to each of the C classes. Networks trained with this method can synthesize multiple classes from ImageNet (figure 15.14).
对于具有 C 个类别的属性,判别器以真实 / 合成图像作为输入,并产生 C + 1 个输出;第一个输出经过 sigmoid 函数,预测样本是生成的还是真实的。其余输出经过 Softmax 函数,预测数据属于 C 个类别中每一个类别的概率。使用此方法训练的网络可以合成来自 ImageNet 的多个类别(图 15.14)。

The conditional GAN and ACGAN both generate samples that have predetermined attributes. By contrast, InfoGAN (figure 15.13c) attempts to identify important attributes automatically. The generator takes a vector consisting of random noise variables z and random attribute variables c. The discriminator both predicts whether the image is real or synthesized and estimates the attribute variables.
The insight is that interpretable real-world characteristics should be easiest to predict and hence will be represented in the attribute variables c. The attributes in c may be discrete (and a binary or multiclass cross-entropy loss would be used) or continuous (and a least squares loss would be used). The discrete variables identify categories in the data, and the continuous ones identify gradual modes of variation (figure 15.15).
条件 GAN 和 ACGAN 都会生成具有预定属性的样本。相比之下, InfoGAN (图 15.13c)尝试自动识别重要属性。生成器接收一个由随机噪声变量 z 和随机属性变量 c 组成的向量。判别器既预测图像是真实的还是合成的,又估计属性变量。
其洞见是,可解释的现实世界特征应当最容易预测,因此会由属性变量 c 来表示。 c 中的属性可以是离散的(此时使用二分类或多分类交叉熵损失)或连续的(此时使用最小二乘损失)。离散变量用于识别数据中的类别,连续变量用于识别渐进的变化模式(图 15.15)。
Although the adversarial discriminator was first used in the context of the GAN for generating random samples, it can also be used as a prior that favors realism in tasks that translate one data example into another. This is most commonly done with images,

where we might want to translate a grayscale image to color, a noisy image to a clean one, a blurry image to a sharp one, or a sketch to a photo-realistic image.
This section discusses three image translation models that use different amounts of manual labeling. The Pix2Pix model uses before/after pairs for training. Models with adversarial losses use before/after pairs for the main model but also exploit unpaired “after” images in the discriminator. The CycleGAN model uses unpaired images.
尽管对抗性判别器最初是在 GAN 的语境中用于生成随机样本,但它也可以作为先验,在将一个数据样本转换为另一个数据样本的任务中促进真实感。这种情况最常见于图像,
其中,我们可能希望将灰度图像转换为彩色图像,将带噪图像转换为干净图像,将模糊图像转换为清晰图像,或将草图转换为照片级真实图像。
本节讨论三种使用不同数量人工标注的图像翻译模型。 Pix2Pix 模型使用前后图像对进行训练。采用对抗损失的模型在主模型中使用前后图像对,但也在判别器中利用未配对的“后”图像。 CycleGAN 模型使用未配对图像。
The Pix2Pix model (figure 15.16) is a network ˆ x = g[ c , θ] that maps one image c to a different style image x using a U-Net (figure 11.10) with parameters θ. A typical use case would be colorization, where the input c is grayscale, and the output g[ c , θ] is color. The output should be similar to the input, and this is encouraged using a content loss that penalizes the ℓ1 norm || x − g[ c , θ]||1 between the input c and ground truth output x.
Pix2Pix 模型(图 15.16)是一个网络 ˆ x = g[ c θ],它将一张图像 c 映射为不同风格的图像 x,该映射使用带有参数 θ 的 U-Net (图 11.10)。典型用例是上色,其中输入 c 是灰度图,而输出 g[ c θ] 是彩色图。输出应与输入相似,这通过一个内容损失来鼓励,该损失惩罚 ℓ1 范数 || x − g[ c θ]||1 (对于输入 c 与真值输出 x 这一对)。然而,输出图像还应看起来像对输入的逼真转换。这通过使用对抗性判别器 f[ c, x ϕ] 来鼓励,该判别器接收前后图像 c 和 x。在每一步,判别器尝试区分真实的前后图像对与前图像 / 合成图像对。只要这些
However, the output image should also look like a realistic conversion of the input. This is encouraged by using an adversarial discriminator f[ c , x , ϕ], which ingests the before and after images c and x. At each step, the discriminator tries to distinguish between a real before/after pair and a before/synthesized pair. To the extent that these
can be distinguished successfully, a feedback signal is provided to modify the U-Net to make its output more realistic. Since the content loss ensures that the large-scale image structure is correct, the discriminator is mainly needed to ensure that the local texture is plausible. To this end, the PatchGAN loss is based on a purely convolutional classifier. At the last layer, each hidden unit indicates whether the region within its receptive field is real or synthesized. These responses are averaged to provide the final output.
One way to think of this model is that it is a conditional GAN where the U-Net is the generator and is conditioned on an image rather than a label. Notice, though, that the U-Net input does not include noise and so is not really a “generator” in the conventional sense. Interestingly, the original authors experimented with adding noise z to the U-Net in addition to the input image c. However, the network just learned to ignore it.
能够被成功区分,就会提供反馈信号来修改 U-Net,使其输出更加逼真。由于内容损失确保大尺度图像结构正确,判别器主要用于确保局部纹理合理。为此, PatchGAN 损失基于一个纯卷积分类器。在最后一层,每个隐藏单元指示其感受野内的区域是真实的还是合成的。对这些响应进行平均,以得到最终输出。
一种理解这个模型的方式是,它是一个条件 GAN,其中 U-Net 是生成器,并且以图像而非标签作为条件。不过请注意, U-Net 的输入并不包含噪声,因此它并不是传统意义上的“生成器”。有趣的是,原作者曾尝试向 U-Net 添加噪声 z,以作为输入图像 c 的补充。然而,网络只是学会了忽略它。
The discriminator of the Pix2Pix model attempted to distinguish whether before/after pairs in an image translation task were plausible. This has the disadvantage that we need ground truth before/after pairs to exploit the discriminator loss. Fortunately, there is a simpler way to exploit the power of adversarial discriminators in the context of supervised learning without the need for additional labeled training data.
An adversarial loss adds a penalty if a discriminator can distinguish the output of a supervised network from a real example from its output domain. Accordingly, the supervised model changes its predictions to decrease this penalty. This may be done at the scale of the entire output or at the level of patches, as in the Pix2Pix algorithm. This helps improve the realism of complex structured outputs. However, it doesn’t necessarily lead to a better solution in terms of the original loss function.
Pix2Pix 模型的判别器试图区分图像转换任务中的前后配对是否可信。这样做的缺点是,我们需要真值前后配对才能利用判别器损失。幸运的是,在监督学习背景下,有一种更简单的方法可以利用对抗判别器的能力,而无需额外的带标签训练数据。
对抗损失会在判别器能够将监督网络的输出与其输出域中的真实示例区分开来时施加惩罚。相应地,监督模型会改变其预测以降低这种惩罚。这可以在整个输出的尺度上进行,也可以在图块级别上进行,就像 Pix2Pix 算法那样。这有助于提高复杂结构化输出的真实感。然而,从原始损失函数来看,这并不一定能带来更好的解。
The super-resolution GAN or SRGAN uses this approach (figure 15.17). The main model consists of a convolutional network with residual connections that ingests a lowresolution image and converts this via upsampling layers to a high-resolution image. The network is trained with three losses. The content loss measures the squared difference between the output and the true high-resolution image. The VGG loss or perceptual loss passes the synthesized and ground truth outputs through the VGG network and measures the squared difference between their activations. This encourages the image to be semantically similar to the target. Finally, the adversarial loss uses a discriminator that attempts to distinguish whether this is a real high-resolution image or an upsampled one. This encourages the output to be indistinguishable from real examples.
超分辨率 GAN 或 SRGAN 使用了这种方法(图 15.17)。主模型由带有残差连接的卷积网络组成,该网络接收低分辨率图像,并通过上采样层将其转换为高分辨率图像。该网络使用三种损失进行训练。内容损失衡量输出与真实高分辨率图像之间的平方差。 VGG 损失或感知损失将合成输出和真值输出送入 VGG 网络,并衡量它们激活值之间的平方差。这促使图像在语义上与目标相似。最后,对抗损失使用判别器,该判别器试图区分这是真实的高分辨率图像还是上采样得到的图像。这促使输出与真实样本难以区分。
The adversarial loss assumes that we have labeled before/after images for the main supervised network. The CycleGAN addresses the situation where we have two sets of data with distinct styles but no matching pairs. An example is converting a photo to the artistic style of Monet. There exist many photos and many Monet paintings, but no correspondence between them. CycleGAN exploits the idea that converting an image in
对抗损失假设我们拥有用于主监督网络的有标签前后图像。 CycleGAN 处理的是我们拥有两组风格不同但没有匹配对的数据的情况。一个例子是将照片转换为莫奈的艺术风格。存在许多照片和许多莫奈画作,但它们之间没有对应关系。 CycleGAN 利用了这样的想法:将图像转换在


one direction (e.g., photo → Monet) and then back again should recover the original. The CycleGAN loss function is a weighted sum of three losses (figure 15.18). The content loss encourages the before and after images to be similar and is based on the ℓ1 norm. The adversarial loss uses a discriminator to encourage the output to be indistin-
guishable from real examples of the target domain. Finally, the cycle-consistency loss encourages the mapping to be reversible. Here, two models are trained together. One maps from the first domain to the second, and the other in the opposite direction. The cycle-consistency loss will be low if the translated image can be itself translated successfully back to the image in the original domain. The model combines these three losses to train networks to translate images from one style to another and back again.
单向转换(例如,照片 → 莫奈)然后再返回,应能恢复原始图像。
范数。对抗损失使用判别器,促使输出与目标域的真实样本无法区分。最后,循环一致性损失促使映射可逆。这里,两个模型一起训练。一个模型从第一个域映射到第二个域,另一个模型沿相反方向映射。如果转换后的图像能够被再次成功转换回原始域中的图像,则循环一致性损失会较低。该模型组合这三种损失,训练网络将图像从一种风格转换到另一种风格,再转换回来。
StyleGAN is a more contemporary GAN that partitions the variation in a dataset into meaningful components, each of which is controlled by a subset of the latent variables. In particular, StyleGAN controls the output image at different scales and separates style from noise. For face images, large-scale changes include face shape and head pose, medium-scale changes include the shape and details of facial features, and fine-scale changes include hair and skin color.
The style components represent aspects of the image that are salient to human beings, and the noise aspects represent unimportant variation such as the exact placement of hairs, stubble, freckles, or skin pores.
The GANs that we have seen until now started from a latent variable z which is drawn from a standard base distribution. This was passed through a series of convolutional layers to produce the output image. However, the latent variable inputs to the generator can (i) be introduced at various points in the architecture and (ii) modify the current representation at these points in different ways. StyleGAN makes these choices judiciously to control scale and to separate style from noise (figure 15.19).
StyleGAN 是一种更为现代的 GAN,它将数据集中的变化划分为有意义的组件,每个组件都由隐变量的子集控制。具体而言, StyleGAN 在不同尺度上控制输出图像,并将风格与噪声分离。对于人脸图像,大尺度变化包括脸型与头部姿态,中尺度变化包括面部特征的形状与细节,细尺度变化包括头发和皮肤颜色。风格组件代表图像中人类显著感知的方面,而噪声方面代表不重要的变化,例如头发的确切位置、胡茬、雀斑或皮肤毛孔。
我们迄今所见的 GAN 都从一个隐变量 z 开始,该变量从标准基础分布中采样。然后将其通过一系列卷积层以生成输出图像。然而,输入到生成器的隐变量可以 (i) 在架构中的不同位置引入,并且 (ii) 以不同方式修改这些位置的当前表示。 StyleGAN 审慎地做出这些选择,以控制尺度并将风格与噪声分离(图 15.19)。
The main generative branch of StyleGAN starts with a learned constant 4 × 4 representation with 512 channels. This passes through a series of convolutional layers that gradually upsample the representation to generate the image at its final resolution. Two sets of random latent variables representing style and noise are introduced at each scale; the closer that they are to the output, the finer scale details they represent.
The latent variables that represent noise are independently sampled Gaussian vectors z 1, z 2... and are injected additively after each convolution operation in the main generative pipeline. They are the same spatial size as the main representation at the point that they are added but are multiplied by learned per-channel scaling factors ψ1, ψ2... and so contribute in different amounts to each channel. As the resolution of the network increases, this noise contributes at finer scales. The latent variables that represent style begin as a 1 × 1 × 512 noise tensor, which is passed through a seven-layer fully connected network to create an intermediate variable w. This allows the network to decorrelate aspects of style so that each dimension of w can represent an independent real-world factor such as head pose or hair color. This variable w is linearly transformed to a 2 × 1 × 512 tensor y, which is used to set the per-channel mean and variance of the representation across spatial positions in the
StyleGAN 的主生成分支以一个可学习的常量 4 × 4 表示开始,该表示具有 512 个通道。该表示经过一系列卷积层,逐步上采样,以在最终分辨率下生成图像。在每个尺度上引入两组随机隐变量,分别表示风格和噪声;它们越接近输出,所表示的细节尺度越精细。
表示噪声的隐变量是独立采样的 Gaussian vectors z 1, z 2...,并在主生成管线中每次卷积操作后以加法方式注入。在它们被添加的位置,它们与主表示具有相同的空间尺寸,但会乘以可学习的每通道缩放因子 ψ1, ψ2...,因此对每个通道的贡献量不同。随着网络分辨率提高,该噪声在更精细的尺度上起作用。表示风格的隐变量以一个 1 × 1 × 512 噪声张量开始,该张量经过一个七层全连接网络,生成一个中间变量 w。这使网络能够对风格的不同方面进行去相关,从而使 w 的每个维度都能表示一个独立的现实世界因素,例如头部姿态或头发颜色。该变量 w 被线性变换为一个 2 × 1 × 512 张量 y,用于设置该表示在空间位置上的每通道均值和方差,该表示在
main branch after noise addition. This is termed adaptive instance normalization (figure 11.14e). A series of vectors y 1, y 2,... are injected in this way at several different points in the main branch, so the same style contributes at different scales. Figure 15.20 shows examples of manipulating the style and noise vectors at different scales.
添加噪声后的主干分支。这被称为自适应实例归一化(图 11.14e)。一系列向量 y 1, y 2,... 以这种方式注入主干分支中的若干不同点,因此同一种风格在不同尺度上起作用。图 15.20 展示了在不同尺度上操纵风格向量和噪声向量的示例。
![图 15.18 CycleGAN。两个模型同时训练。第一个 c ′= g[ c j, θ] 将第一种风格(马)中的图像 c 转换为第二种风格(斑马)中的图像 c](/learning/udl/ch15/figures/ch15_p22_f0.webp)

GANs learn a generator network that transforms random noise into data that is indistinguishable from a training set. To this end, the generator is trained using a discriminator network that tries to distinguish real examples from generated samples. The generator is then updated so that the data that it creates is identified as being more “real” by the discriminator. The original formulation of this idea has the flaw that the training signal is weak when it’s easy to determine if the samples are real or generated. This led to the
GAN 学习一个生成器网络,该网络将随机噪声转换为与训练集难以区分的数据。为此,生成器通过一个判别器网络进行训练,该判别器网络试图区分真实样本和生成样本。然后更新生成器,使其创建的数据被判别器识别为更“真实”。这一思想的原始表述存在一个缺陷:当很容易判断样本是真实还是生成时,训练信号较弱。这催生了

Wasserstein GAN, which provides a more consistent training signal.
We reviewed convolutional GANs for generating images and a series of tricks that improve the quality of the generated images, including progressive growing, mini-batch discrimination, and truncation. Conditional GAN architectures introduce an auxiliary vector that allows control over the output (e.g., the choice of object class). Image translation tasks retain this conditional information in the form of an image but dispense with the random noise. The GAN discriminator now works as an additional loss term that favors “realistic” looking images. Finally, we described StyleGAN, which injects noise into the generator strategically to control the style and noise at different scales.
Wasserstein GAN,它提供了更一致的训练信号。
我们回顾了用于生成图像的卷积 GAN,以及一系列提升生成图像质量的技巧,包括渐进式增长、小批量判别和截断。条件 GAN 架构引入了一个辅助向量,从而允许对输出进行控制(例如对象类别的选择)。图像转换任务以图像的形式保留这一条件信息,但省去了随机噪声。此时, GAN 判别器充当一个额外的损失项,倾向于“逼真”的图像。最后,我们介绍了 StyleGAN,它战略性地向生成器注入噪声,以控制不同尺度上的风格和噪声。
Data:
GAN loss functions:
Tricks for training GANs:
Sample diversity:
Increasing diversity and preventing mode collapse:
Multiple scales:
增加多样性并防止模式崩溃:缺乏多样性的极端情况是模式崩溃,即网络反复生成同一图像
StyleGAN:
Conditional GANs:
Image translation:
Adversarial loss:
Inverting GANs:
Editing images with GANs: