智能体训练之模仿学习:GAIL 算法详解与实战

1. 引言:从模仿学习到 GAIL

在智能体(Agent)训练中,强化学习依赖精心设计的奖励函数,而现实中很多任务的奖励难以显式定义------比如"像人类一样开车""像专家一样操作机械臂"。模仿学习(Imitation Learning, IL) 提供了一条捷径:直接让智能体从专家示范中学习策略。

模仿学习主要有两条技术路线:

  • 行为克隆(Behavior Cloning, BC) :把专家轨迹当作监督学习数据,直接拟合状态到动作的映射。简单高效,但存在分布偏移(distribution shift) 问题------一旦智能体偏离专家分布,误差会累积放大。
  • 逆强化学习(Inverse Reinforcement Learning, IRL):从专家示范中反推奖励函数,再用强化学习优化策略。理论上更稳健,但计算代价高、需要在线 RL 内循环。

GAIL(Generative Adversarial Imitation Learning) 由 Ho 与 Ermon 于 2016 年提出,巧妙地把生成对抗网络(GAN)的思想引入模仿学习:用一个判别器区分"专家动作"与"智能体动作",判别器的输出直接作为智能体的奖励信号。它既避免了显式奖励设计,又绕开了 IRL 昂贵的 RL 内循环,成为模仿学习领域最具影响力的算法之一。

本文将从原理推导、算法流程、代码实现到实战调参,系统讲解 GAIL,并给出可直接运行的 PyTorch 实现。

2. 背景知识:模仿学习与逆强化学习

2.1 问题形式化

我们考虑标准的马尔可夫决策过程(MDP):状态空间 S\mathcal{S}S、动作空间 A\mathcal{A}A、转移概率 P(s′∣s,a)P(s'|s,a)P(s′∣s,a)、折扣因子 γ\gammaγ。模仿学习的目标是:给定专家策略 πE\pi_EπE 产生的轨迹集合 DE={τ1,τ2,... }\mathcal{D}E = \{\tau_1, \tau_2, \dots\}DE={τ1,τ2,...},学习一个策略 πθ\pi\thetaπθ,使其行为尽可能接近专家。

2.2 行为克隆的局限

行为克隆最小化专家动作与策略动作的差异:

min⁡θE(s,a)∼DE−log⁡πθ(a∣s) \min_\theta \mathbb{E}_{(s,a)\sim \mathcal{D}_E}\left-\\log \\pi_\\theta(a\|s)\\right θminE(s,a)∼DE−logπθ(a∣s)

问题在于训练分布与测试分布不一致。经典结论(Ross & Bagnell, 2010)表明,BC 的误差随轨迹长度 TTT 呈 O(T2)O(T^2)O(T2) 累积,长程任务中极易崩溃。

2.3 逆强化学习

IRL 假设专家行为是最优的,试图找到奖励函数 rrr 使得专家策略优于其他策略。最大熵 IRL(MaxEnt IRL)将问题转化为:

max⁡rmin⁡πEπEr(s,a)−Eπr(s,a)−H(π) \max_r \min_\pi \mathbb{E}{\pi_E}r(s,a) - \mathbb{E}\pir(s,a) - H(\pi) rmaxπminEπEr(s,a)−Eπr(s,a)−H(π)

其中 H(π)H(\pi)H(π) 为策略熵。IRL 的代价是每次更新奖励都要解一个完整的 RL 问题,计算开销巨大。GAIL 正是为了消除这一内循环而生。

为便于横向比较,下表从奖励函数、在线 RL 内循环、样本效率、分布偏移鲁棒性、计算开销与适用场景六个维度,对行为克隆、MaxEnt IRL 与 GAIL 做简要对比:

方法 是否需要奖励函数 是否需在线 RL 内循环 样本效率 分布偏移鲁棒性 典型计算开销 适用场景
行为克隆(BC) 不需要 不需要 高(纯监督学习) 弱,误差随轨迹长度 O(T2)O(T^2)O(T2) 累积 低,单次监督训练 数据充足、任务短程、对精度要求不高的快速基线
MaxEnt IRL 需要(显式学习奖励) 需要(内层 RL 求解) 低,每轮奖励更新都要重解 RL 强,奖励可迁移 高,内外双层优化 需要可解释奖励、奖励可迁移到新任务的场景
GAIL 不需要(判别器隐式定义奖励) 需要(策略优化本身即 RL) 中,交替更新判别器与策略 较强,占用度量匹配 中,单层对抗式交替优化 奖励难设计、专家数据可得、连续控制等主流模仿学习任务

从表中可以看出:BC 最轻量但最脆弱;MaxEnt IRL 最稳健却最昂贵;GAIL 则在鲁棒性与开销之间取得了较好的折中,这也是它在实践中被广泛采用的原因。

3. GAIL 核心原理

3.1 从 GAN 到 GAIL

GAN 的核心是判别器 DDD 区分真实样本与生成样本,生成器 GGG 努力欺骗判别器。GAIL 把这一框架搬到策略学习上:

  • 生成器 :智能体策略 πθ\pi_\thetaπθ,生成"假"的状态-动作对;
  • 判别器 :Dω(s,a)D_\omega(s,a)Dω(s,a),判断 (s,a)(s,a)(s,a) 来自专家还是策略;
  • 奖励信号 :r(s,a)=−log⁡(1−Dω(s,a))r(s,a) = -\log(1 - D_\omega(s,a))r(s,a)=−log(1−Dω(s,a)),即判别器认为"像专家"的程度。

判别器越难区分,说明策略越接近专家。

3.2 目标函数

GAIL 的优化目标为:

min⁡θmax⁡ω EπElog⁡Dω(s,a)+Eπθlog⁡(1−Dω(s,a))−λH(πθ) \min_\theta \max_\omega \ \mathbb{E}{\pi_E}\left\\log D_\\omega(s,a)\\right + \mathbb{E}{\pi_\theta}\left\\log(1 - D_\\omega(s,a))\\right - \lambda H(\pi_\theta) θminωmax EπElogDω(s,a)+Eπθlog(1−Dω(s,a))−λH(πθ)

其中 λH(πθ)\lambda H(\pi_\theta)λH(πθ) 为熵正则项,鼓励探索、防止策略过早坍缩。Ho & Ermon 证明了该目标与"占用度量匹配(occupancy measure matching)"的等价性:当判别器无法区分时,策略的占用度量与专家一致。

3.3 与 IRL 的关系

GAIL 可以看作一种特殊的 IRL:判别器隐式定义了奖励函数,而策略优化通过任意 RL 算法完成。相比 MaxEnt IRL,GAIL 不需要显式求解奖励,也不需要内层 RL 收敛到最优,只需交替更新判别器与策略,效率大幅提升。

3.4 算法流程

#mermaid-svg-8kkiP0aW52rFZl3V{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-8kkiP0aW52rFZl3V .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-8kkiP0aW52rFZl3V .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-8kkiP0aW52rFZl3V .error-icon{fill:#552222;}#mermaid-svg-8kkiP0aW52rFZl3V .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-8kkiP0aW52rFZl3V .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-8kkiP0aW52rFZl3V .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-8kkiP0aW52rFZl3V .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-8kkiP0aW52rFZl3V .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-8kkiP0aW52rFZl3V .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-8kkiP0aW52rFZl3V .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-8kkiP0aW52rFZl3V .marker{fill:#333333;stroke:#333333;}#mermaid-svg-8kkiP0aW52rFZl3V .marker.cross{stroke:#333333;}#mermaid-svg-8kkiP0aW52rFZl3V svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-8kkiP0aW52rFZl3V p{margin:0;}#mermaid-svg-8kkiP0aW52rFZl3V .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-8kkiP0aW52rFZl3V .cluster-label text{fill:#333;}#mermaid-svg-8kkiP0aW52rFZl3V .cluster-label span{color:#333;}#mermaid-svg-8kkiP0aW52rFZl3V .cluster-label span p{background-color:transparent;}#mermaid-svg-8kkiP0aW52rFZl3V .label text,#mermaid-svg-8kkiP0aW52rFZl3V span{fill:#333;color:#333;}#mermaid-svg-8kkiP0aW52rFZl3V .node rect,#mermaid-svg-8kkiP0aW52rFZl3V .node circle,#mermaid-svg-8kkiP0aW52rFZl3V .node ellipse,#mermaid-svg-8kkiP0aW52rFZl3V .node polygon,#mermaid-svg-8kkiP0aW52rFZl3V .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-8kkiP0aW52rFZl3V .rough-node .label text,#mermaid-svg-8kkiP0aW52rFZl3V .node .label text,#mermaid-svg-8kkiP0aW52rFZl3V .image-shape .label,#mermaid-svg-8kkiP0aW52rFZl3V .icon-shape .label{text-anchor:middle;}#mermaid-svg-8kkiP0aW52rFZl3V .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-8kkiP0aW52rFZl3V .rough-node .label,#mermaid-svg-8kkiP0aW52rFZl3V .node .label,#mermaid-svg-8kkiP0aW52rFZl3V .image-shape .label,#mermaid-svg-8kkiP0aW52rFZl3V .icon-shape .label{text-align:center;}#mermaid-svg-8kkiP0aW52rFZl3V .node.clickable{cursor:pointer;}#mermaid-svg-8kkiP0aW52rFZl3V .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-8kkiP0aW52rFZl3V .arrowheadPath{fill:#333333;}#mermaid-svg-8kkiP0aW52rFZl3V .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-8kkiP0aW52rFZl3V .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-8kkiP0aW52rFZl3V .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-8kkiP0aW52rFZl3V .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-8kkiP0aW52rFZl3V .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-8kkiP0aW52rFZl3V .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-8kkiP0aW52rFZl3V .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-8kkiP0aW52rFZl3V .cluster text{fill:#333;}#mermaid-svg-8kkiP0aW52rFZl3V .cluster span{color:#333;}#mermaid-svg-8kkiP0aW52rFZl3V div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-8kkiP0aW52rFZl3V .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-8kkiP0aW52rFZl3V rect.text{fill:none;stroke-width:0;}#mermaid-svg-8kkiP0aW52rFZl3V .icon-shape,#mermaid-svg-8kkiP0aW52rFZl3V .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-8kkiP0aW52rFZl3V .icon-shape p,#mermaid-svg-8kkiP0aW52rFZl3V .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-8kkiP0aW52rFZl3V .icon-shape rect,#mermaid-svg-8kkiP0aW52rFZl3V .image-shape rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-8kkiP0aW52rFZl3V .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-8kkiP0aW52rFZl3V .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-8kkiP0aW52rFZl3V :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 否
是
初始化策略 π_θ 与判别器 D_ω
采样专家轨迹 D_E
用当前策略 π_θ 采样轨迹
用 D_ω 计算奖励 r = -log(1-D)
用 PPO/TRPO 更新策略 π_θ
用专家与策略数据更新判别器 D_ω
是否收敛
输出策略 π_θ

具体步骤:

  1. 用当前策略与环境交互,收集轨迹;
  2. 对每个 (s,a)(s,a)(s,a) 用判别器计算奖励 r=−log⁡(1−Dω(s,a))r = -\log(1 - D_\omega(s,a))r=−log(1−Dω(s,a));
  3. 用该奖励驱动 PPO/TRPO 更新策略;
  4. 用专家数据(标签 1)与策略数据(标签 0)训练判别器;
  5. 重复直到判别器准确率接近 50%(无法区分)。

4. 代码实现(PyTorch)

下面给出一个基于 PyTorch 的 GAIL 实现,策略优化使用 PPO,环境以 Gymnasium 的 Pendulum-v1 为例(连续动作空间)。

4.1 判别器

python 复制代码
import torch
import torch.nn as nn

class Discriminator(nn.Module):
    def __init__(self, state_dim, action_dim, hidden_dim=256):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(state_dim + action_dim, hidden_dim),
            nn.Tanh(),
            nn.Linear(hidden_dim, hidden_dim),
            nn.Tanh(),
            nn.Linear(hidden_dim, 1),
        )

    def forward(self, state, action):
        x = torch.cat([state, action], dim=-1)
        return self.net(x)  # 输出 logit

    def reward(self, state, action):
        # r = -log(1 - D(s,a)),用 softplus 数值稳定实现
        logit = self.forward(state, action)
        # -log(1 - sigmoid(logit)) = softplus(-logit)
        return torch.nn.functional.softplus(-logit)

4.2 策略网络(Actor-Critic)

python 复制代码
import torch
import torch.nn as nn
from torch.distributions import Normal

class ActorCritic(nn.Module):
    def __init__(self, state_dim, action_dim, hidden_dim=256):
        super().__init__()
        self.actor = nn.Sequential(
            nn.Linear(state_dim, hidden_dim), nn.Tanh(),
            nn.Linear(hidden_dim, hidden_dim), nn.Tanh(),
        )
        self.mu_head = nn.Linear(hidden_dim, action_dim)
        self.log_std = nn.Parameter(torch.zeros(action_dim))
        self.critic = nn.Sequential(
            nn.Linear(state_dim, hidden_dim), nn.Tanh(),
            nn.Linear(hidden_dim, hidden_dim), nn.Tanh(),
            nn.Linear(hidden_dim, 1),
        )

    def forward(self, state):
        h = self.actor(state)
        mu = torch.tanh(self.mu_head(h))  # Pendulum 动作范围 [-1, 1]
        std = self.log_std.exp().expand_as(mu)
        value = self.critic(state).squeeze(-1)
        return Normal(mu, std), value

4.3 PPO 更新

python 复制代码
def ppo_update(policy, optimizer, states, actions, old_log_probs,
               rewards, values, clip_eps=0.2, epochs=10, batch_size=64):
    returns = compute_gae(rewards, values)
    advantages = returns - values
    advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)

    n = states.size(0)
    for _ in range(epochs):
        idx = torch.randperm(n)
        for start in range(0, n, batch_size):
            b = idx[start:start + batch_size]
            dist, new_values = policy(states[b])
            new_log_probs = dist.log_prob(actions[b]).sum(-1)
            ratio = (new_log_probs - old_log_probs[b]).exp()

            surr1 = ratio * advantages[b]
            surr2 = torch.clamp(ratio, 1 - clip_eps, 1 + clip_eps) * advantages[b]
            policy_loss = -torch.min(surr1, surr2).mean()
            value_loss = ((new_values - returns[b]) ** 2).mean()
            entropy = dist.entropy().sum(-1).mean()

            loss = policy_loss + 0.5 * value_loss - 0.01 * entropy
            optimizer.zero_grad()
            loss.backward()
            nn.utils.clip_grad_norm_(policy.parameters(), 0.5)
            optimizer.step()

4.4 广义优势估计(GAE)

ppo_update 中的 compute_gae 负责把逐步奖励转换为优势估计。GAE(Generalized Advantage Estimation,Schulman et al., 2016)通过参数 λ∈0,1\lambda \in 0,1λ∈0,1 在偏差 与方差之间做权衡:

  • λ=0\lambda = 0λ=0:退化为单步 TD 误差 δt=rt+γV(st+1)−V(st)\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t)δt=rt+γV(st+1)−V(st),偏差大、方差小;
  • λ=1\lambda = 1λ=1:退化为蒙特卡洛回报减基线,偏差小、方差大;
  • 实践中常取 λ=0.95\lambda = 0.95λ=0.95,兼顾稳定性与样本效率。

计算分两步:先算每步的 TD 误差 δt\delta_tδt,再从后向前递推优势 A^t=δt+γλ A^t+1\hat{A}t = \delta_t + \gamma\lambda\,\hat{A}{t+1}A^t=δt+γλA^t+1,最后加上状态价值得到回报目标。

python 复制代码
def compute_gae(rewards, values, gamma=0.99, lam=0.95):
    """
    广义优势估计(Generalized Advantage Estimation)

    参数:
        rewards: (T,) 每步奖励,GAIL 中即判别器给出的 r = -log(1-D)
        values:  (T,) 每步状态价值 V(s_t),由 Critic 输出
        gamma:   折扣因子,控制远期奖励的权重
        lam:     GAE 的 λ 参数,平衡偏差与方差(常用 0.95)

    返回:
        returns: (T,) 回报目标 = 优势 + 价值,作为 Critic 的回归目标
    """
    T = rewards.size(0)
    advantages = torch.zeros_like(rewards)
    last_gae = 0.0

    # 从后向前递推:A_t = δ_t + γλ·A_{t+1}
    for t in reversed(range(T)):
        if t == T - 1:
            # 轨迹末尾没有后继状态,next_value 视为 0
            next_value = 0.0
        else:
            next_value = values[t + 1]

        # TD 误差:δ_t = r_t + γ·V(s_{t+1}) - V(s_t)
        delta = rewards[t] + gamma * next_value - values[t]
        # 优势递推:A_t = δ_t + γλ·A_{t+1}
        last_gae = delta + gamma * lam * last_gae
        advantages[t] = last_gae

    # 回报目标 = 优势 + 价值基线
    returns = advantages + values
    return returns

说明:compute_gae 已在上方给出完整实现,ppo_update 直接调用即可;专家数据 expert.npz 需包含 states 与 actions 两个数组,可用训练好的专家策略或人工示教采集。

4.5 训练主循环

python 复制代码
import gymnasium as gym
import numpy as np

def collect_trajectory(env, policy, max_steps=200):
    states, actions, log_probs, rewards, values = [], [], [], [], []
    state, _ = env.reset()
    episode_return = 0.0
    for _ in range(max_steps):
        s = torch.as_tensor(state, dtype=torch.float32)
        with torch.no_grad():
            dist, value = policy(s)
            action = dist.sample()
            log_prob = dist.log_prob(action).sum(-1)
        next_state, reward, terminated, truncated, _ = env.step(action.numpy())
        states.append(s); actions.append(action)
        log_probs.append(log_prob); rewards.append(reward)
        values.append(value)
        episode_return += reward
        state = next_state
        if terminated or truncated:
            break
    return (torch.stack(states), torch.stack(actions),
            torch.stack(log_probs), torch.tensor(rewards),
            torch.stack(values), episode_return)

class RunningMeanStd:
    """奖励 running mean/std 归一化,用于稳定 PPO 的价值函数"""
    def __init__(self, epsilon=1e-4):
        self.mean = 0.0
        self.var = 1.0
        self.count = epsilon

    def update(self, x):
        x = x.detach().cpu().numpy().astype(np.float64)
        batch_mean = x.mean()
        batch_var = x.var()
        batch_count = x.size
        delta = batch_mean - self.mean
        total = self.count + batch_count
        self.mean += delta * batch_count / total
        m2 = self.var * self.count + batch_var * batch_count + delta ** 2 * self.count * batch_count / total
        self.var = m2 / total
        self.count = total

    def normalize(self, x):
        return (x - self.mean) / (np.sqrt(self.var) + 1e-8)

def train_gail(env_name="Pendulum-v1", expert_path="expert.npz",
               total_iters=500, disc_steps=3):
    env = gym.make(env_name)
    state_dim = env.observation_space.shape[0]
    action_dim = env.action_space.shape[0]

    policy = ActorCritic(state_dim, action_dim)
    disc = Discriminator(state_dim, action_dim)
    opt_policy = torch.optim.Adam(policy.parameters(), lr=3e-4)
    opt_disc = torch.optim.Adam(disc.parameters(), lr=3e-4)

    expert = np.load(expert_path)
    exp_s = torch.as_tensor(expert["states"], dtype=torch.float32)
    exp_a = torch.as_tensor(expert["actions"], dtype=torch.float32)

    # 记录训练曲线,供 plot_training 使用
    history = {"iters": [], "disc_acc": [], "avg_return": []}
    reward_rms = RunningMeanStd()

    for it in range(total_iters):
        s, a, lp, _, v, episode_return = collect_trajectory(env, policy)

        # 用判别器重写奖励
        with torch.no_grad():
            gail_r = disc.reward(s, a)
        # 可选:与原环境奖励混合,gail_r + 0.1 * env_r

        # 奖励 running mean/std 归一化,避免价值函数震荡
        reward_rms.update(gail_r)
        gail_r = torch.as_tensor(reward_rms.normalize(gail_r), dtype=torch.float32)

        ppo_update(policy, opt_policy, s, a, lp, gail_r, v)

        # 训练判别器
        for _ in range(disc_steps):
            idx_e = torch.randint(0, exp_s.size(0), (256,))
            idx_p = torch.randint(0, s.size(0), (256,))
            d_expert = disc(exp_s[idx_e], exp_a[idx_e])
            d_policy = disc(s[idx_p], a[idx_p])
            loss_d = (torch.nn.functional.binary_cross_entropy_with_logits(
                d_expert, torch.ones_like(d_expert)) +
                torch.nn.functional.binary_cross_entropy_with_logits(
                d_policy, torch.zeros_like(d_policy)))
            opt_disc.zero_grad(); loss_d.backward(); opt_disc.step()

        # 记录判别器准确率与策略回报
        acc = ((d_expert > 0).float().mean() +
               (d_policy < 0).float().mean()) / 2
        history["iters"].append(it)
        history["disc_acc"].append(acc.item())
        history["avg_return"].append(episode_return)

        if it % 20 == 0:
            print(f"iter {it} | disc_acc {acc.item():.3f} | return {episode_return:.2f}")

    # 训练结束后绘制判别器准确率与策略平均回报曲线
    plot_training(history)
    return policy, disc

4.6 收敛判据与早停策略

GAIL 没有显式的损失函数可以单调下降,训练是否收敛需要综合多条信号判断。单看某一条曲线很容易误判,实践中建议同时观察以下三条:

  • 判别器准确率趋近 0.5:这是 GAIL 理论上的收敛标志。判别器无法区分专家与策略数据,说明策略的占用度量已与专家匹配。若准确率长期稳定在 0.5~0.6 区间,通常意味着策略已接近专家水平。
  • 策略平均回报进入平台期 :avg_return 曲线在连续若干轮内波动幅度很小、不再有上升趋势,说明策略性能已饱和。注意要结合滑动平均看,单轮回报受随机性影响较大。
  • 判别器损失曲线趋于平稳 :判别器损失(专家与策略样本的二元交叉熵之和)稳定在 ln⁡4≈1.386\ln 4 \approx 1.386ln4≈1.386 附近,对应判别器输出概率约 0.5,是博弈达到均衡的数值表现。若损失持续下降,说明判别器仍在变强,策略尚未跟上。

三条信号中,判别器准确率是最直接的收敛指标,回报平台期用于确认策略确实学到了东西(而非判别器失效导致的假收敛),判别器损失则用于排除数值异常。三者一致时才可判定收敛。

下面在 train_gail 中加入早停逻辑:当判别器准确率连续 patience 轮低于阈值,或平均回报连续多轮不再提升时提前结束训练。

python 复制代码
def train_gail(env_name="Pendulum-v1", expert_path="expert.npz",
               total_iters=500, disc_steps=3,
               acc_threshold=0.6, patience=20, min_iters=50):
    env = gym.make(env_name)
    state_dim = env.observation_space.shape[0]
    action_dim = env.action_space.shape[0]

    policy = ActorCritic(state_dim, action_dim)
    disc = Discriminator(state_dim, action_dim)
    opt_policy = torch.optim.Adam(policy.parameters(), lr=3e-4)
    opt_disc = torch.optim.Adam(disc.parameters(), lr=3e-4)

    expert = np.load(expert_path)
    exp_s = torch.as_tensor(expert["states"], dtype=torch.float32)
    exp_a = torch.as_tensor(expert["actions"], dtype=torch.float32)

    history = {"iters": [], "disc_acc": [], "avg_return": []}
    reward_rms = RunningMeanStd()

    # 早停状态
    low_acc_count = 0        # 连续低准确率轮数
    best_return = -float("inf")
    no_improve_count = 0     # 回报未提升的连续轮数

    for it in range(total_iters):
        s, a, lp, _, v, episode_return = collect_trajectory(env, policy)

        with torch.no_grad():
            gail_r = disc.reward(s, a)

        reward_rms.update(gail_r)
        gail_r = torch.as_tensor(reward_rms.normalize(gail_r), dtype=torch.float32)

        ppo_update(policy, opt_policy, s, a, lp, gail_r, v)

        for _ in range(disc_steps):
            idx_e = torch.randint(0, exp_s.size(0), (256,))
            idx_p = torch.randint(0, s.size(0), (256,))
            d_expert = disc(exp_s[idx_e], exp_a[idx_e])
            d_policy = disc(s[idx_p], a[idx_p])
            loss_d = (torch.nn.functional.binary_cross_entropy_with_logits(
                d_expert, torch.ones_like(d_expert)) +
                torch.nn.functional.binary_cross_entropy_with_logits(
                d_policy, torch.zeros_like(d_policy)))
            opt_disc.zero_grad(); loss_d.backward(); opt_disc.step()

        acc = ((d_expert > 0).float().mean() +
               (d_policy < 0).float().mean()) / 2
        history["iters"].append(it)
        history["disc_acc"].append(acc.item())
        history["avg_return"].append(episode_return)

        if it % 20 == 0:
            print(f"iter {it} | disc_acc {acc.item():.3f} | "
                  f"return {episode_return:.2f} | loss_d {loss_d.item():.3f}")

        # ---- 早停判据 ----
        if it < min_iters:
            continue  # 前期波动大,不触发早停

        # 信号一:判别器准确率持续低于阈值(已无法区分)
        if acc.item() < acc_threshold:
            low_acc_count += 1
        else:
            low_acc_count = 0

        # 信号二:平均回报不再提升
        if episode_return > best_return + 1e-3:
            best_return = episode_return
            no_improve_count = 0
        else:
            no_improve_count += 1

        if low_acc_count >= patience:
            print(f"[early stop] disc_acc 连续 {patience} 轮低于 "
                  f"{acc_threshold},判定收敛于 iter {it}")
            break
        if no_improve_count >= patience:
            print(f"[early stop] 平均回报连续 {patience} 轮未提升,"
                  f"判定收敛于 iter {it}")
            break

    plot_training(history)
    return policy, disc

几点使用建议:

  • min_iters 用于跳过训练初期的剧烈波动,避免过早误判;patience 越大越保守,一般取 15~30。
  • 若判别器准确率很快掉到 0.5 但回报始终不涨,多半是假收敛(判别器失效而非策略变好),此时应检查奖励归一化与专家数据质量,而不是直接停止。
  • 早停只是节省算力,最终仍建议用 plot_training 画出完整曲线人工复核,确认三条信号一致后再部署策略。

4.6 训练过程可视化

训练 GAIL 时,光看终端打印的 disc_acc 很难判断训练是否健康。建议把判别器准确率 与策略平均回报两条曲线画出来,直观观察判别器与策略的博弈状态。

python 复制代码
import matplotlib.pyplot as plt

def plot_training(history, save_path="gail_curves.png"):
    """
    绘制 GAIL 训练曲线

    参数:
        history: dict,包含
            - "iters":        迭代轮次列表
            - "disc_acc":     每轮判别器准确率(0.5 表示无法区分)
            - "avg_return":   每轮策略在环境中的平均回报
        save_path: 图片保存路径
    """
    iters = history["iters"]

    fig, axes = plt.subplots(1, 2, figsize=(12, 4))

    # 左图:判别器准确率
    axes[0].plot(iters, history["disc_acc"], color="tab:red", label="disc_acc")
    axes[0].axhline(0.5, linestyle="--", color="gray", label="ideal 0.5")
    axes[0].set_xlabel("iteration")
    axes[0].set_ylabel("discriminator accuracy")
    axes[0].set_title("Discriminator Accuracy")
    axes[0].set_ylim(0.4, 1.05)
    axes[0].legend()
    axes[0].grid(alpha=0.3)

    # 右图:策略平均回报
    axes[1].plot(iters, history["avg_return"], color="tab:blue", label="avg_return")
    axes[1].set_xlabel("iteration")
    axes[1].set_ylabel("average return")
    axes[1].set_title("Policy Average Return")
    axes[1].legend()
    axes[1].grid(alpha=0.3)

    fig.tight_layout()
    fig.savefig(save_path, dpi=150)
    plt.close(fig)

在 train_gail 主循环里记录数据即可:

python 复制代码
history = {"iters": [], "disc_acc": [], "avg_return": []}

# 在 for it in range(total_iters) 循环内、判别器更新之后追加:
history["iters"].append(it)
history["disc_acc"].append(acc.item())
history["avg_return"].append(episode_return)  # 本轮轨迹的累计回报

# 训练结束后统一绘图
plot_training(history)

如何读曲线:

  • 判别器准确率长期贴近 1.0:说明判别器过强,能轻易区分专家与策略数据,奖励信号饱和、策略梯度消失。此时应降低判别器学习率、减少判别器更新次数,或加入梯度惩罚 / 标签平滑。
  • 判别器准确率稳定在 0.5 附近,但平均回报不涨:判别器已无法区分,理论上策略应接近专家;若回报仍低,多半是奖励未归一化、PPO 超参不当或专家数据本身质量差,需回到 5.2、5.4 节排查。
  • 平均回报曲线剧烈震荡 :常见于奖励尺度未归一化或 α 混合系数过大,建议对奖励做 running mean/std 标准化。
  • 健康状态:判别器准确率从接近 1.0 逐步下降到 0.5~0.7 区间,同时平均回报稳步上升并趋于平台,说明策略正在逼近专家。

5. 实战要点与调参经验

5.1 判别器与策略的平衡

GAIL 训练中最常见的问题是判别器过强:判别器迅速达到 100% 准确率,奖励信号饱和,策略梯度消失。常用对策:

  • 降低判别器学习率(如策略的 1/3);
  • 每轮策略更新多次、判别器只更新 1~3 次;
  • 对判别器输出做梯度惩罚(类似 WGAN-GP),限制其 Lipschitz 常数;
  • 使用标签平滑(专家标签 0.9 而非 1.0)。

5.2 奖励归一化

判别器输出的奖励尺度随训练变化,直接送入 PPO 会导致价值函数震荡。建议对奖励做 running mean/std 归一化,或使用 softplus(-logit) 的数值稳定形式。

5.3 与环境奖励混合

纯 GAIL 奖励在部分任务中会丢失任务本身的稀疏信号。实践中常采用混合奖励:

rtotal=renv+α⋅rGAIL r_{\text{total}} = r_{\text{env}} + \alpha \cdot r_{\text{GAIL}} rtotal=renv+α⋅rGAIL

α\alphaα 一般取 0.1~1.0,可根据任务调整。

5.4 专家数据质量

GAIL 对专家数据质量敏感。若专家轨迹含噪声或次优行为,判别器会把这些行为也当作"专家"学习。建议:

  • 专家数据尽量来自确定性策略或高质量示教;
  • 数据量至少覆盖状态空间的主要区域(通常数千到数万条转移);
  • 必要时对专家数据做状态归一化,与策略输入保持一致。

5.5 常见问题排查

现象 可能原因 对策
判别器准确率长期接近 1 判别器过强 降学习率、加梯度惩罚
策略不收敛、奖励震荡 奖励未归一化 奖励标准化、调小 α
智能体学到专家坏习惯 专家数据含噪声 清洗数据、过滤低回报轨迹
训练后期性能下降 过拟合判别器 早停、正则化、增加专家多样性

6. GAIL 的变体与扩展

  • GAIL-PPO / GAIL-TRPO:将策略优化替换为 PPO 或 TRPO,是当前最常用的组合。
  • WGAIL:用 Wasserstein 距离替代 JS 散度,缓解判别器饱和。
  • InfoGAIL:引入潜变量,学习多模态专家行为(如不同驾驶风格)。
  • AIRL(Adversarial IRL) :对奖励做可分离分解 r(s,a)=g(s)+γh(s′)−h(s)r(s,a) = g(s) + \gamma h(s') - h(s)r(s,a)=g(s)+γh(s′)−h(s),学到的奖励可迁移到新环境。
  • Diffusion Policy / Implicit BC:近年兴起的生成式模仿学习方法,在机器人操作任务中表现优异,可与 GAIL 互补。

7. 总结

GAIL 将生成对抗思想引入模仿学习,用判别器隐式定义奖励,避免了显式奖励设计与 IRL 的昂贵内循环,是智能体从专家示范中高效学习的利器。其核心在于:

  1. 判别器即奖励 :r=−log⁡(1−D(s,a))r = -\log(1 - D(s,a))r=−log(1−D(s,a)),越像专家奖励越高;
  2. 交替优化:策略与判别器博弈,最终达到占用度量匹配;
  3. 工程关键:判别器与策略的平衡、奖励归一化、专家数据质量。

实践中建议从 GAIL-PPO 起步,配合奖励归一化与梯度惩罚,先在 Pendulum-v1 等低维连续控制任务上验证,再迁移到机械臂、自动驾驶等复杂场景。若任务对奖励可解释性有要求,可进一步尝试 AIRL;若专家数据多模态明显,InfoGAIL 是更好的选择。

8. 参考资料

  • Ho, J., & Ermon, S. (2016). Generative Adversarial Imitation Learning. NeurIPS.
  • Fu, J., Luo, K., & Levine, S. (2018). Learning Robust Rewards with Adversarial Inverse Reinforcement Learning. ICLR.
  • Li, Y., Song, J., & Ermon, S. (2017). InfoGAIL: Interpretable Imitation Learning from Visual Demonstrations. NeurIPS.
  • Schulman, J., et al. (2017). Proximal Policy Optimization Algorithms. arXiv:1707.06347.
  • Ross, S., & Bagnell, J. A. (2010). Efficient Reductions for Imitation Learning. AISTATS.
相关推荐
databook1 小时前
处理一批 PDF,怎么算真的处理完了
后端·python
leobertlan2 小时前
痛苦系列 | DSP-04 截断时空的“窗”:FIR 滤波器设计与线性相位
算法
承渊政道3 小时前
【Python编程快速上手—让繁琐工作自动化】(列表:把数据排成队,从下标取值到深拷贝)
开发语言·python·pycharm·自动化·列表
秋天的怀念_David3 小时前
算法一千零一夜 · 第三十五夜 · 恢复风暴
java·程序人生·算法
大胖爱学习_MJ3 小时前
Agent 如何安全地拿数据库密码?基于 HashiCorp Vault 的动态凭证下发
经验分享·python
tryCbest4 小时前
Python 爬虫从入门到实战(一):基础篇——从零写出第一个爬虫
开发语言·爬虫·python
无小道4 小时前
Python语句的特色
python·语句
2601_967980115 小时前
python pytest如何编写测试
python·测试用例·pytest·函数·assert