Wasserstein GAN:距离、评价函数与约束
Wasserstein GAN
计算运输与对偶证书,再检验线性评价函数和软惩罚的边界。
wgan概率质量需要搬多远?
把全部真实概率质量放在零,全部生成质量放在θ。θ很小但非零时,两者支持仍不相交。只根据能否分辨这些点质量建立的散度,不一定反映位置有多近。运输换了一个问题:多少概率需要移动,移动多远?
这个例子的Wasserstein-1距离为|θ|。θ趋近零时,距离连续趋近零,虽然零点有尖角。WGAN论文给出相关的平行线例子,并利用运输对偶提出可训练的critic。critic输出实数评分,不是真假概率。建议先读GAN与期望。
距离与它的对偶形式
耦合是一个联合分布,其两个边缘分别等于待比较分布。有限支持下,耦合矩阵说明从每个真实位置向每个生成位置搬多少质量。将质量乘距离后求和,再最小化:
对于欧氏空间中具有有限一阶矩的概率测度,Kantorovich–Rubinstein对偶用1-Lipschitz函数表示同一距离。1-Lipschitz指任意两点的评分差,都不超过输入距离。
WGAN用参数化critic近似这个优化。函数族受限,或critic没优化充分,都不一定达到上确界。把约束1换成K,不受参数族限制的上确界会乘K。第3节明确讨论这些条件;观测到的神经网络评分差不能自动标为精确Wasserstein距离。
在一维中构造证书
对有限一维分布,先排序支持点,再匹配最左边的剩余质量。若运输路径交叉,可以换成不交叉的配对而不增加绝对距离成本。反复做这个交换就得到单调最优耦合。第一个算法直接构造耦合,并检查边缘质量。
另一种独立计算使用累计质量差。把双方支持合并成有序位置t,定义各点质量差d,其前缀和为S。每段区间必须通过净质量S,所以把其绝对值乘区间长度,再相加就是成本:
还可以证明有对偶函数达到这个成本。令f0=0,每段斜率取S符号的反向;离散分部求和得到相等的原始与对偶值:
分段线性插值的斜率绝对值不超过1,在两端外用常值延拓,就得到全局1-Lipschitz函数。这是有限一维教学问题的精确证书,不是高维神经critic的精确求解器。
现在比较一个双模式分布与同均值的点质量。每个线性critic都给出零差异,但运输成本为1:
这里的瓶颈是critic表达能力。把这个线性函数再多训练几轮,也不会凭空增加缺失的非线性函数。
运输、critic更新与惩罚反例
保存为wgan.py,用Python 3.12与NumPy 1.26.4运行。排序为O(n log n+m log m),单调匹配随后为O(n+m)。为便于检查,程序保存O(nm)耦合矩阵;如果只累计成本,就不必存整张矩阵。对偶计算在排序后为线性。
最后一个实验实际更新线性critic和点质量生成器:P在零,Q在θ。critic权重被投影到[−1,1],每次生成器更新前做五次critic更新,普通梯度步长为0.05。这是教学优化器,不是原论文的RMSProp实现。同时保留滞后critic的差值与精确|θ|,便能看出训练损失为什么会误导。
"""Original 1D transport/dual certificate and hard-versus-soft linear critic examples."""
import json
import numpy as np
def measure(support, weights):
x, p = np.asarray(support, float), np.asarray(weights, float)
if (x.ndim != 1 or not 1 <= x.size <= 64 or p.shape != x.shape
or not np.isfinite(x).all() or not np.isfinite(p).all()
or np.max(abs(x)) > 10 or np.any(p < 0) or abs(float(p.sum())-1) > 1e-12):
raise ValueError('1..64 support points in [-10,10] and probability weights required.')
unique, inverse = np.unique(x, return_inverse=True)
merged = np.bincount(inverse, weights=p, minlength=len(unique))
return unique, merged/p.sum()
def transport(x, p, y, q):
"""Greedy monotone coupling. Rows/columns refer to sorted, merged supports."""
x, p = measure(x, p)
y, q = measure(y, q)
remaining_p, remaining_q = p.copy(), q.copy()
coupling = np.zeros((len(p), len(q)))
i = j = 0
while i < len(p) and j < len(q):
mass = min(remaining_p[i], remaining_q[j])
coupling[i, j] += mass
remaining_p[i] -= mass
remaining_q[j] -= mass
if remaining_p[i] <= 0:
i += 1
if remaining_q[j] <= 0:
j += 1
cost = float(np.sum(coupling*abs(x[:, None]-y)))
return cost, coupling
def dual_certificate(x, p, y, q):
x, p = measure(x, p)
y, q = measure(y, q)
grid = np.union1d(x, y)
difference = np.zeros(len(grid))
np.add.at(difference, np.searchsorted(grid, x), p)
np.add.at(difference, np.searchsorted(grid, y), -q)
cumulative = np.cumsum(difference)[:-1]
intervals = np.diff(grid)
potential = np.r_[0., np.cumsum(-np.sign(cumulative)*intervals)]
return dict(grid=grid, potential=potential, cumulative=cumulative,
cdf_cost=float(abs(cumulative)@intervals), dual=float(difference@potential))
def soft_linear_critic(theta=2., penalty=10.):
"""Exact optimum of -w*theta-lambda*(abs(w)-1)^2; theta must be positive."""
if (not np.isfinite(theta) or not 0 < theta <= 10
or not np.isfinite(penalty) or not .01 <= penalty <= 100):
raise ValueError('Theta in (0,10] and penalty in [.01,100] required.')
w = -(1+theta/(2*penalty))
gap = -w*theta
penalized = gap-penalty*(abs(w)-1)**2
return dict(weight=float(w), gap=float(gap), penalized=float(penalized), true_w1=float(theta))
def train_linear(steps=100, rate=.05, critic_steps=5):
if (isinstance(steps, bool) or not isinstance(steps, int) or not 0 <= steps <= 1000
or not np.isfinite(rate) or not 0 < rate <= .1
or isinstance(critic_steps, bool) or not isinstance(critic_steps, int)
or not 1 <= critic_steps <= 20):
raise ValueError('Bounded integer iteration counts and rate in (0,.1] required.')
theta, w = 2., 0.
history = [[0, theta, w, -w*theta, abs(theta)]]
for step in range(1, steps+1):
for _ in range(critic_steps):
w = float(np.clip(w-rate*theta, -1, 1))
theta += rate*w # generator minimizes -w*theta with w fixed
history.append([step, theta, w, -w*theta, abs(theta)])
return history
def demo():
x, p, y, q = [-1., 1.], [.5, .5], [0.], [1.]
cost, coupling = transport(x, p, y, q)
certificate = dual_certificate(x, p, y, q)
certificate = {k: v.tolist() if isinstance(v, np.ndarray) else v for k, v in certificate.items()}
history = train_linear()
return dict(same_mean_example=dict(w1=cost, coupling=coupling.tolist(), linear_gap=0., **certificate),
soft_penalty=soft_linear_critic(),
checkpoints=history[::10], minimum_lagging_gap=min(r[3] for r in history))
if __name__ == '__main__':
print(json.dumps(demo(), indent=2, allow_nan=False))
软惩罚不是硬约束
原始WGAN把网络权重限制在有界盒中。对于固定的适当架构,这给出共同Lipschitz界,但界不自动等于1。论文也讨论裁切过紧或过松的问题。固定作者训练代码采用变化的critic更新次数,且在优化器更新前裁切;不能假定实现每一行的时序都与论文伪码相同。
WGAN-GP用真实与生成点之间插值位置上的输入梯度范数惩罚代替裁切。按下面的符号约定,两个损失都需要最小化:
求导对象是输入,不是critic权重。论文省去critic中的batch normalization,因为它让样本间输出耦合,与逐输入惩罚的解释冲突。论文默认λ为10,而固定toy实现为0.1。这是不同配置,不能当作可互换的复现说明。
有限惩罚仍可能偏好绝对值大于1的斜率。令P在零、Q在θ>0,f(x)=wx,最大化真实减生成的差值,再减去惩罚:
θ=2、λ=10时,最优w=−1.1,原始差值2.2,带罚最大化值2.1,真正W1为2。这个最大化值是对应最小化critic损失的负数。精确线性反例已经排除了“有限梯度惩罚保证1-Lipschitz或返回精确距离”的一般说法;仅在选定输入上采样惩罚,又增加了一层限制。
投影线性训练中,|w|始终不超过1,但滞后critic的差值最低约−0.236000,精确距离仍非负。某个可行函数的期望差可以为负,定义W1的上确界不能为负。这个差值、完整带罚损失、精确运输距离,是三个不同的量。裁切或梯度惩罚本身都不能证明普遍收敛或完整模式覆盖。
审查一个距离结论
- 把单位点质量从零移到二,给出耦合与成本。
答案:唯一耦合把质量1从0送到2,成本2。真实质量在零、生成质量在二时,f(x)=−x取得对偶差值2。
- 两个分布均值相同,W1必为零吗?
答案:不必。±1混合与零点质量均值相同,但W1=1。线性critic漏掉这种区别,分段线性证书能够检出。
- 在线性软惩罚例中取θ=2、λ=10,计算最优斜率、差值与惩罚。
答案:斜率−1.1,差值2.2,惩罚10×0.1²=0.1。带罚最大化值为2.1,不是真实距离2。
- 日志中真实减生成的差值为负,Wasserstein度量变成负数了吗?
答案:没有。当前critic可能优化不足或落后于G。可行critic的差值可以为负,最优上确界仍非负。先确认日志记录的是原始差值,还是带符号、带惩罚的损失。
沿着不同问题读论文
WGAN与WGAN-GP都首发于2017年,但这里所读文件分别是12月6日的WGAN v3和3月31日的WGAN-GP v1。比较WGAN第2—3节与WGAN-GP算法1、第4节;解释损失时同时写清版本、符号约定、优化器、裁切或惩罚配置。固定作者实现提供具体对照,包括与论文默认值不同的toy惩罚权重;本篇没有声称重新运行过上游训练。
先判断,再看解释
有限的WGAN-GP惩罚保证critic全局1-Lipschitz吗?
学习目标
- 计算有限一维运输方案。
- 构造Lipschitz对偶证书。
- 区分critic估计与精确距离。
- 解释裁切与采样梯度惩罚。
先修与延伸
查看知识关联图 →参考文献
- Wasserstein GAN (v3): transport, dual critic and clipping
Martin Arjovsky; Soumith Chintala; Léon Bottou · 2017 - Improved Training of Wasserstein GANs (v1): sampled gradient penalty
Ishaan Gulrajani; Faruk Ahmed; Martin Arjovsky; Vincent Dumoulin; Aaron Courville · 2017 - WassersteinGAN author training code at f7a01e8
Martin Arjovsky; Soumith Chintala; Léon Bottou and contributors · 2018 - Improved WGAN toy implementation at fa66c57
Ishaan Gulrajani and contributors · 2017
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-13 · Single AI author checked WGAN v3 selected transport/dual/clipping sections, WGAN-GP v1 method and fixed author code. Seven paired equations, four explained exercises; original finite one-dimensional transport/dual certificate, linear soft-penalty counterexample and actual lagging-critic updates. No high-dimensional exact solver or image benchmark.
- 核对单调耦合边缘/成本与独立CDF及对偶、分段线性全局Lipschitz证书、同均值critic能力反例、软罚斜率/差值和投影有限critic更新中的负滞后差值。
- 每题四张计算SVG绑定真实双语程序。组内16项数值/几何与390/768/1536共24响应式组合及四字体通过,实际查看8张最终代表截图。补VQ数字标签、相图等单位轴并保留原件,数值未改。完整文章页验收另记,不称独立人工审校。
- 冻结后措辞纠错:图示最优斜率为-1.1,超过1的是绝对值。双语句子与图标题明确改为绝对值,公式/程序/数据不变,冻结原件保留。精确差异与重新验证见editorial/corrections/012b-wgan-slope-magnitude。
核对的来源位置:
- Wasserstein GAN (v3): transport, dual critic and clipping · Read Section2 transport/parallel-line example and Section3 selected duality, K scaling, optimality assumptions, clipping/algorithm and fixed-D collapse discussion. Inspected PDF page7. First2017-01-26; v3 dated2017-12-06. No appendix proof or benchmark replication.
- Improved Training of Wasserstein GANs (v1): sampled gradient penalty · Read selected Section3 clipping failures, Algorithm1 and Section4 penalty/interpolates/default lambda/no critic batch normalization. Inspected PDF page5. Explicit v1 dated2017-03-31, not latest v3. No full experiments or appendix review.
- WassersteinGAN author training code at f7a01e8 · Read lines150–225, RMSProp/Adam choice, dynamic critic counts and clipping placement. Commit2018-12-26; full root BSD3-Clause license read. Reference only; no upstream execution or copied code.
- Improved WGAN toy implementation at fa66c57 · Read lines20–90, lambda=.1 in toy code versus10 in paper, losses/interpolation/input-gradient penalty. Commit2017-06-22; full root MIT license read. No upstream execution or copied code.
相关主题