Wikipedia 生成模型核心概念 (Wikipedia Generative Models Concepts)¶
来源: Wikipedia (英文维基百科)
编译时间: 2026-06-01
状态: 中英对照编译
基于: Generative adversarial network, Diffusion model, Variational autoencoder 等条目
关联: 深度学习概念, 强化学习概念
📚 目录 (Table of Contents)¶
1. 生成模型基础 (Generative Models Basics)¶
英文定义 (English Definition):
A generative model is a type of statistical model that can generate new data instances that are similar to the training data. Unlike discriminative models that learn to classify, generative models learn the underlying distribution of the data.
中文翻译 (Chinese Translation):
生成模型是一种统计模型,可以生成与训练数据相似的新数据实例。与学习分类的判别模型不同,生成模型学习数据的潜在分布。
生成 vs 判别模型 (Generative vs Discriminative Models):
| 特征 | 生成模型 | 判别模型 |
|---|---|---|
| 学习目标 | \(P(X,Y)\) 或 \(P(X)\) | \(P(Y\|X)\) |
| 能力 | 可生成新样本 | 仅能分类/预测 |
| 数据利用 | 无监督/自监督 | 通常需要标注 |
| 示例 | GAN, VAE, Diffusion | CNN, SVM, 逻辑回归 |
生成模型家族 (Generative Model Family):
生成模型
├── 隐变量模型 (Latent Variable Models)
│ ├── VAE (变分自编码器)
│ └── GAN (生成对抗网络)
│
├── 基于似然的模型 (Likelihood-based Models)
│ ├── 自回归模型 (PixelCNN, Transformer)
│ ├── 归一化流 (Normalizing Flows)
│ └── 基于能量的模型 (EBM)
│
└── 得分匹配模型 (Score Matching Models)
└── 扩散模型 (Diffusion Models)
2. 变分自编码器 (VAE)¶
英文定义:
A Variational Autoencoder (VAE) is a generative model that uses variational inference to learn a latent representation of the data. It consists of an encoder that maps data to a latent space and a decoder that reconstructs data from the latent space.
中文翻译:
变分自编码器 (VAE) 是一种使用变分推断学习数据潜在表示的生成模型。它由将数据映射到潜空间的编码器和从潜空间重建数据的解码器组成。
2.1 VAE 架构 (VAE Architecture)¶
VAE 结构:
输入 x
↓
┌──────────────┐
│ 编码器 │ q_φ(z|x)
│ Encoder │ 近似后验分布
└──────┬───────┘
│
↓
潜变量 z ~ q_φ(z|x)
(重参数化技巧)
│
↓
┌──────────────┐
│ 解码器 │ p_θ(x|z)
│ Decoder │ 生成分布
└──────┬───────┘
│
↓
重建的 x̂
损失 = 重建损失 + KL 散度
2.2 VAE 损失函数 (VAE Loss Function)¶
证据下界 (Evidence Lower Bound, ELBO):
VAE 损失 (VAE Loss):
其中: - \(q_\phi(z|x)\): 编码器 (近似后验) - \(p_\theta(x|z)\): 解码器 (似然) - \(p(z)\): 先验分布 (通常为标准正态) - KL: Kullback-Leibler 散度
2.3 重参数化技巧 (Reparameterization Trick)¶
英文:
The reparameterization trick allows gradients to flow through the sampling operation by expressing the latent variable as a deterministic function of the parameters and a noise variable.
中文:
重参数化技巧通过将潜变量表示为参数和噪声变量的确定性函数,允许梯度流过采样操作。
公式 (Formula):
Python 实现 (Python Implementation):
import torch
import torch.nn as nn
import torch.nn.functional as F
class VAE(nn.Module):
def __init__(self, input_dim, hidden_dim, latent_dim):
super(VAE, self).__init__()
# 编码器
self.encoder = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, hidden_dim),
nn.ReLU()
)
# 潜变量参数 (均值和对数方差)
self.fc_mu = nn.Linear(hidden_dim, latent_dim)
self.fc_logvar = nn.Linear(hidden_dim, latent_dim)
# 解码器
self.decoder = nn.Sequential(
nn.Linear(latent_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, input_dim),
nn.Sigmoid()
)
def encode(self, x):
h = self.encoder(x)
mu = self.fc_mu(h)
logvar = self.fc_logvar(h)
return mu, logvar
def reparameterize(self, mu, logvar):
std = torch.exp(0.5 * logvar)
eps = torch.randn_like(std)
return mu + eps * std
def decode(self, z):
return self.decoder(z)
def forward(self, x):
mu, logvar = self.encode(x)
z = self.reparameterize(mu, logvar)
x_recon = self.decode(z)
return x_recon, mu, logvar
def loss(self, x, x_recon, mu, logvar):
# 重建损失 (二元交叉熵)
recon_loss = F.binary_cross_entropy(x_recon, x, reduction='sum')
# KL 散度
kl_loss = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
return recon_loss + kl_loss
3. 生成对抗网络 (GAN)¶
英文定义:
A Generative Adversarial Network (GAN) is a generative model consisting of two neural networks: a generator that creates fake data and a discriminator that distinguishes between real and fake data. The two networks are trained simultaneously in a competitive game.
中文翻译:
生成对抗网络 (GAN) 是一种生成模型,由两个神经网络组成:生成器创建假数据,判别器区分真实和假数据。两个网络在竞争游戏中同时训练。
3.1 GAN 架构 (GAN Architecture)¶
GAN 结构:
真实数据 x_real 噪声 z
│ │
↓ ↓
┌──────────────┐ ┌──────────────┐
│ 判别器 D │ │ 生成器 G │
│ Discriminator│ │ Generator │
└──────┬───────┘ └──────┬───────┘
│ │
│ ↓
│ 生成的 x_fake
│ │
└──────────┬────────────┘
│
↓
D(x_real) vs D(x_fake)
判别真假
训练目标:
- 生成器:最小化 D 识别假数据的能力
- 判别器:最大化区分真假数据的能力
3.2 GAN 目标函数 (GAN Objective Function)¶
原始 GAN 损失 (Original GAN Loss):
其中: - \(G\): 生成器 - \(D\): 判别器 - \(x \sim p_{\text{data}}\): 真实数据 - \(z \sim p_z\): 噪声向量
改进的损失函数 (Improved Loss Functions):
| 变体 | 英文 | 损失函数 | 特点 |
|---|---|---|---|
| Original GAN | 原始 GAN | \(\log(1-D(G(z)))\) | 梯度消失问题 |
| Non-saturating | 非饱和 | \(-\log(D(G(z)))\) | 更好的梯度 |
| WGAN | Wasserstein GAN | \(-D(G(z))\) + 权重裁剪 | 更稳定训练 |
| WGAN-GP | WGAN + 梯度惩罚 | WGAN + GP 正则 | 无需权重裁剪 |
| LSGAN | 最小二乘 GAN | \((D(G(z)) - 1)^2\) | 最小二乘损失 |
3.3 WGAN-GP 实现 (WGAN-GP Implementation)¶
Wasserstein 距离 (Wasserstein Distance):
梯度惩罚 (Gradient Penalty):
Python 实现 (Python Implementation):
import torch
import torch.nn as nn
class Generator(nn.Module):
def __init__(self, latent_dim, output_dim):
super(Generator, self).__init__()
self.model = nn.Sequential(
nn.Linear(latent_dim, 256),
nn.ReLU(),
nn.Linear(256, 512),
nn.ReLU(),
nn.Linear(512, 1024),
nn.ReLU(),
nn.Linear(1024, output_dim),
nn.Tanh()
)
def forward(self, z):
return self.model(z)
class Discriminator(nn.Module):
def __init__(self, input_dim):
super(Discriminator, self).__init__()
self.model = nn.Sequential(
nn.Linear(input_dim, 1024),
nn.LeakyReLU(0.2),
nn.Linear(1024, 512),
nn.LeakyReLU(0.2),
nn.Linear(512, 256),
nn.LeakyReLU(0.2),
nn.Linear(256, 1)
)
def forward(self, x):
return self.model(x)
def gradient_penalty(discriminator, real_data, fake_data, lambda_gp=10):
"""计算 WGAN-GP 的梯度惩罚"""
batch_size = real_data.size(0)
# 随机插值
alpha = torch.rand(batch_size, 1).to(real_data.device)
alpha = alpha.expand_as(real_data)
interpolated = (alpha * real_data + (1 - alpha) * fake_data).requires_grad_(True)
# 判别器输出
d_interpolated = discriminator(interpolated)
# 计算梯度
gradients = torch.autograd.grad(
outputs=d_interpolated,
inputs=interpolated,
grad_outputs=torch.ones_like(d_interpolated),
create_graph=True,
retain_graph=True
)[0]
# 梯度范数
gradients_norm = gradients.view(batch_size, -1).norm(2, dim=1)
# 梯度惩罚
gp = ((gradients_norm - 1) ** 2).mean() * lambda_gp
return gp
def train_wgan_gp(generator, discriminator, dataloader, num_epochs, lr=1e-4):
optimizer_G = torch.optim.Adam(generator.parameters(), lr=lr, betas=(0.5, 0.9))
optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=lr, betas=(0.5, 0.9))
for epoch in range(num_epochs):
for i, (real_data, _) in enumerate(dataloader):
batch_size = real_data.size(0)
# 训练判别器
optimizer_D.zero_grad()
# 真实样本
real_labels = torch.ones(batch_size, 1).to(real_data.device)
d_real = discriminator(real_data)
# 假样本
z = torch.randn(batch_size, 100).to(real_data.device)
fake_data = generator(z)
d_fake = discriminator(fake_data)
# WGAN 损失
d_loss = -torch.mean(d_real) + torch.mean(d_fake)
# 梯度惩罚
gp = gradient_penalty(discriminator, real_data, fake_data)
d_loss_total = d_loss + gp
d_loss_total.backward()
optimizer_D.step()
# 训练生成器 (每 n_critic 次训练一次)
if i % 5 == 0:
optimizer_G.zero_grad()
z = torch.randn(batch_size, 100).to(real_data.device)
fake_data = generator(z)
d_fake = discriminator(fake_data)
g_loss = -torch.mean(d_fake)
g_loss.backward()
optimizer_G.step()
4. 扩散模型 (Diffusion Models)¶
英文定义:
Diffusion models are generative models that learn to reverse a gradual noising process. They have achieved state-of-the-art results in image generation and other domains.
中文翻译:
扩散模型是学习逆转逐渐加噪过程的生成模型。它们在图像生成和其他领域取得了最先进的结果。
4.1 扩散过程 (Diffusion Process)¶
前向过程 (Forward Process):
其中: - \(\beta_t\): 噪声调度 - \(\bar{\alpha}_t = \prod_{s=1}^t (1-\beta_s)\) - \(x_0\): 原始数据 - \(x_t\): t 步后的噪声数据
反向过程 (Reverse Process):
4.2 去噪得分匹配 (Denoising Score Matching)¶
预测噪声公式 (Predicting Noise Formula):
其中 \(\epsilon_\theta\) 是预测噪声的神经网络。
4.3 DDPM 实现 (DDPM Implementation)¶
import torch
import torch.nn as nn
import numpy as np
class UNet(nn.Module):
"""简化的 UNet 用于扩散模型"""
def __init__(self, time_dim, input_dim, output_dim):
super(UNet, self).__init__()
# 时间嵌入
self.time_mlp = nn.Sequential(
nn.Linear(1, time_dim),
nn.SiLU(),
nn.Linear(time_dim, time_dim)
)
# 网络
self.net = nn.Sequential(
nn.Linear(input_dim + time_dim, 256),
nn.SiLU(),
nn.Linear(256, 256),
nn.SiLU(),
nn.Linear(256, output_dim)
)
def forward(self, x, t):
# 时间嵌入
t_emb = self.time_mlp(t.unsqueeze(-1).float())
t_emb = t_emb.unsqueeze(1).expand(-1, x.size(1), -1)
# 拼接时间信息
x = torch.cat([x, t_emb], dim=-1)
return self.net(x)
class DiffusionModel:
def __init__(self, model, num_timesteps=1000, beta_start=1e-4, beta_end=0.02):
self.model = model
self.num_timesteps = num_timesteps
# 噪声调度
self.betas = torch.linspace(beta_start, beta_end, num_timesteps)
self.alphas = 1 - self.betas
self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
def add_noise(self, x0, t, noise=None):
"""前向扩散过程"""
if noise is None:
noise = torch.randn_like(x0)
alpha_cumprod_t = self.alphas_cumprod[t].view(-1, 1, 1).to(x0.device)
# q(x_t | x_0)
x_t = torch.sqrt(alpha_cumprod_t) * x0 + torch.sqrt(1 - alpha_cumprod_t) * noise
return x_t, noise
def sample(self, num_samples, input_dim, device):
"""采样新样本"""
# 从纯噪声开始
x = torch.randn(num_samples, 1, input_dim).to(device)
for t in reversed(range(self.num_timesteps)):
t_batch = torch.full((num_samples,), t, dtype=torch.long).to(device)
# 预测噪声
predicted_noise = self.model(x, t_batch)
# 计算均值
alpha_t = self.alphas[t].to(device)
alpha_cumprod_t = self.alphas_cumprod[t].to(device)
if t > 0:
alpha_cumprod_prev_t = self.alphas_cumprod[t-1].to(device)
else:
alpha_cumprod_prev_t = torch.ones_like(alpha_cumprod_t)
# 计算 mu
mu = (1.0 / torch.sqrt(alpha_t)) * (x - ((1 - alpha_t) / torch.sqrt(1 - alpha_cumprod_t)) * predicted_noise)
# 添加噪声 (除了最后一步)
if t > 0:
sigma_t = torch.sqrt((1 - alpha_cumprod_prev_t) / (1 - alpha_cumprod_t) * (1 - alpha_t))
noise = torch.randn_like(x)
x = mu + sigma_t * noise
else:
x = mu
return x
def train_step(self, x0, optimizer):
"""单步训练"""
# 随机选择时间步
t = torch.randint(0, self.num_timesteps, (x0.size(0),), dtype=torch.long).to(x0.device)
# 添加噪声
x_t, noise = self.add_noise(x0, t)
# 预测噪声
predicted_noise = self.model(x_t, t)
# 计算损失
loss = nn.functional.mse_loss(predicted_noise, noise)
# 反向传播
optimizer.zero_grad()
loss.backward()
optimizer.step()
return loss.item()
5. 归一化流 (Normalizing Flows)¶
英文定义:
Normalizing Flows are generative models that learn a bijective mapping between a simple base distribution (e.g., Gaussian) and the complex data distribution through a sequence of invertible transformations.
中文翻译:
归一化流是生成模型,通过一系列可逆变换学习简单基础分布(如高斯)和复杂数据分布之间的双射映射。
5.1 流模型基础 (Flow Model Basics)¶
变量变换公式 (Change of Variable Formula):
其中: - \(f\): 可逆变换 - \(\frac{\partial f}{\partial x}\): 雅可比矩阵 - \(\det\): 行列式
5.2 常见流层 (Common Flow Layers)¶
| 层类型 | 英文 | 变换 | 雅可比行列式 |
|---|---|---|---|
| Affine Coupling | 仿射耦合 | \(y = x \odot \exp(s(x)) + t(x)\) | \(\prod \exp(s_i)\) |
| Glow | Glow | 可逆 1x1 卷积 | 1 |
| RealNVP | RealNVP | 分段仿射 | 易计算 |
| Neural ODE | 神经 ODE | 连续深度 | 追踪行列式 |
6. 应用与比较 (Applications and Comparison)¶
6.1 生成模型对比 (Generative Models Comparison)¶
| 模型 | 样本质量 | 训练稳定性 | 似然估计 | 采样速度 | 主要应用 |
|---|---|---|---|---|---|
| VAE | 中等 | 稳定 | ✅ 有 | 快 | 表示学习、插值 |
| GAN | 高 | 不稳定 | ❌ 无 | 快 | 图像生成、风格迁移 |
| Diffusion | 非常高 | 稳定 | 近似 | 慢 | 图像生成、超分 |
| Flow | 中等 | 稳定 | ✅ 精确 | 快 | 密度估计、压缩 |
6.2 主要应用 (Main Applications)¶
| 应用领域 | 英文 | 中文 | 典型模型 |
|---|---|---|---|
| 图像生成 | Image Generation | 图像生成 | StyleGAN, Stable Diffusion |
| 图像编辑 | Image Editing | 图像编辑 | Diffusion, GAN inversion |
| 超分辨率 | Super-resolution | 超分辨率 | SR3, ESRGAN |
| 文本到图像 | Text-to-Image | 文本到图像 | DALL-E 2, Stable Diffusion |
| 数据增强 | Data Augmentation | 数据增强 | VAE, GAN |
| 异常检测 | Anomaly Detection | 异常检测 | Flow, VAE |
| 药物发现 | Drug Discovery | 药物发现 | GraphVAE, GraphGFN |
🔑 关键术语对照表 (Glossary)¶
| English | 中文 | 定义 |
|---|---|---|
| Generative model | 生成模型 | 学习数据分布并生成新样本的模型 |
| Discriminative model | 判别模型 | 学习条件概率 P(Y|X) 的模型 |
| Variational Autoencoder | 变分自编码器 | 使用变分推断的生成模型 |
| Generative Adversarial Network | 生成对抗网络 | 生成器和判别器对抗训练的模型 |
| Diffusion Model | 扩散模型 | 逆转加噪过程的生成模型 |
| Normalizing Flow | 归一化流 | 通过可逆变换建模的生成模型 |
| Latent space | 潜空间 | 数据的低维表示空间 |
| KL divergence | KL 散度 | 两个分布的差异度量 |
| Wasserstein distance | Wasserstein 距离 | 最优传输距离 |
| Score matching | 得分匹配 | 学习数据梯度场的方法 |
| Denoising | 去噪 | 从噪声中恢复原始数据 |
编译完成时间: 2026-06-01
来源: Wikipedia Generative adversarial network, Diffusion model, Variational autoencoder, Normalizing flow 等条目
关联文档: deep-learning-concepts-zh-en.md