深度学习中的强化学习基础:从原理到实践

张开发
2026/4/17 10:33:11 15 分钟阅读

分享文章

深度学习中的强化学习基础:从原理到实践
深度学习中的强化学习基础从原理到实践1. 背景介绍强化学习Reinforcement LearningRL是机器学习的一个重要分支它关注智能体如何在环境中采取行动以最大化累积奖励。与监督学习和无监督学习不同强化学习通过与环境的交互来学习最优策略。本文将深入探讨强化学习的基本原理、算法和应用通过实验数据验证其效果并提供实际项目中的最佳实践。2. 核心概念与联系2.1 强化学习核心概念概念描述作用智能体 (Agent)学习和决策的主体执行动作环境 (Environment)智能体交互的外部世界提供状态和奖励状态 (State)环境的当前情况描述环境状态动作 (Action)智能体的行为影响环境状态奖励 (Reward)环境的反馈指导学习过程策略 (Policy)状态到动作的映射决定智能体行为值函数 (Value Function)状态或状态-动作对的价值评估状态或动作模型 (Model)环境的预测模型模拟环境行为3. 核心算法原理与具体操作步骤3.1 Q-Learning 算法Q-Learning基于价值的强化学习算法学习状态-动作对的价值。实现原理维护 Q 表或 Q 网络基于 ε-贪婪策略选择动作使用 TD 学习更新 Q 值使用步骤初始化 Q 表或 Q 网络选择动作ε-贪婪策略执行动作观察奖励和新状态更新 Q 值重复步骤 2-4 直到收敛3.2 深度 Q 网络 (DQN)DQN使用深度神经网络来近似 Q 函数的算法。实现原理使用卷积神经网络作为 Q 网络经验回放缓冲区目标网络使用步骤初始化 Q 网络和目标网络收集经验到回放缓冲区从缓冲区采样批量经验计算目标 Q 值更新 Q 网络定期更新目标网络3.3 策略梯度算法策略梯度直接优化策略函数的算法。实现原理直接参数化策略计算策略梯度使用梯度上升优化策略使用步骤初始化策略网络参数执行策略收集轨迹计算每个动作的回报计算策略梯度更新策略网络参数4. 数学模型与公式4.1 贝尔曼方程状态价值函数$$V(s) \mathbb{E}[R_{t1} \gamma V(S_{t1}) | S_t s]$$动作价值函数$$Q(s, a) \mathbb{E}[R_{t1} \gamma Q(S_{t1}, A_{t1}) | S_t s, A_t a]$$4.2 Q-Learning 更新规则$$Q(s, a) \leftarrow Q(s, a) \alpha [r \gamma \max_{a} Q(s, a) - Q(s, a)]$$其中$\alpha$ 是学习率$\gamma$ 是折扣因子$r$ 是即时奖励$s$ 是下一状态5. 项目实践代码实例5.1 简单 Q-Learning 实现import numpy as np import gym # 创建环境 env gym.make(FrozenLake-v1, is_slipperyFalse) # 初始化 Q 表 state_size env.observation_space.n action_size env.action_space.n Q np.zeros((state_size, action_size)) # 超参数 num_episodes 10000 alpha 0.1 gamma 0.99 epsilon 1.0 epsilon_decay 0.999 epsilon_min 0.01 # 训练 for i in range(num_episodes): state env.reset() done False while not done: # ε-贪婪策略选择动作 if np.random.rand() epsilon: action env.action_space.sample() else: action np.argmax(Q[state, :]) # 执行动作 next_state, reward, done, _ env.step(action) # 更新 Q 值 Q[state, action] Q[state, action] alpha * (reward gamma * np.max(Q[next_state, :]) - Q[state, action]) state next_state # 衰减 ε epsilon max(epsilon_min, epsilon * epsilon_decay) if (i 1) % 1000 0: print(fEpisode: {i1}, Epsilon: {epsilon:.4f}) # 测试 state env.reset() done False total_reward 0 print(\n测试结果:) while not done: action np.argmax(Q[state, :]) state, reward, done, _ env.step(action) total_reward reward env.render() print(f总奖励: {total_reward})5.2 DQN 实现import torch import torch.nn as nn import torch.optim as optim import numpy as np import gym from collections import deque import random # 经验回放缓冲区 class ReplayBuffer: def __init__(self, capacity): self.buffer deque(maxlencapacity) def push(self, state, action, reward, next_state, done): self.buffer.append((state, action, reward, next_state, done)) def sample(self, batch_size): return random.sample(self.buffer, batch_size) def __len__(self): return len(self.buffer) # DQN 网络 class DQN(nn.Module): def __init__(self, state_size, action_size): super().__init__() self.fc1 nn.Linear(state_size, 64) self.fc2 nn.Linear(64, 64) self.fc3 nn.Linear(64, action_size) def forward(self, x): x torch.relu(self.fc1(x)) x torch.relu(self.fc2(x)) x self.fc3(x) return x # 环境 env gym.make(CartPole-v1) state_size env.observation_space.shape[0] action_size env.action_space.n # 超参数 num_episodes 1000 batch_size 64 gamma 0.99 learning_rate 0.001 buffer_size 10000 update_every 10 # 初始化网络 policy_net DQN(state_size, action_size) target_net DQN(state_size, action_size) target_net.load_state_dict(policy_net.state_dict()) optimizer optim.Adam(policy_net.parameters(), lrlearning_rate) memory ReplayBuffer(buffer_size) # ε-贪婪策略 epsilon_start 1.0 epsilon_end 0.01 epsilon_decay 0.995 epsilon epsilon_start # 训练 for i in range(num_episodes): state env.reset() state torch.FloatTensor(state) done False total_reward 0 while not done: # 选择动作 if np.random.rand() epsilon: action env.action_space.sample() else: with torch.no_grad(): action policy_net(state).argmax().item() # 执行动作 next_state, reward, done, _ env.step(action) next_state torch.FloatTensor(next_state) total_reward reward # 存储经验 memory.push(state, action, reward, next_state, done) state next_state # 经验回放 if len(memory) batch_size: transitions memory.sample(batch_size) batch_state, batch_action, batch_reward, batch_next_state, batch_done zip(*transitions) batch_state torch.stack(batch_state) batch_action torch.LongTensor(batch_action) batch_reward torch.FloatTensor(batch_reward) batch_next_state torch.stack(batch_next_state) batch_done torch.FloatTensor(batch_done) # 计算目标 Q 值 with torch.no_grad(): target_q batch_reward (1 - batch_done) * gamma * target_net(batch_next_state).max(1)[0] # 计算当前 Q 值 current_q policy_net(batch_state).gather(1, batch_action.unsqueeze(1)).squeeze(1) # 计算损失 loss nn.MSELoss()(current_q, target_q) # 优化 optimizer.zero_grad() loss.backward() optimizer.step() # 更新目标网络 if i % update_every 0: target_net.load_state_dict(policy_net.state_dict()) # 衰减 ε epsilon max(epsilon_end, epsilon * epsilon_decay) if (i 1) % 100 0: print(fEpisode: {i1}, Total Reward: {total_reward}, Epsilon: {epsilon:.4f}) # 测试 test_episodes 10 test_rewards [] for i in range(test_episodes): state env.reset() state torch.FloatTensor(state) done False total_reward 0 while not done: with torch.no_grad(): action policy_net(state).argmax().item() state, reward, done, _ env.step(action) state torch.FloatTensor(state) total_reward reward test_rewards.append(total_reward) print(fTest Episode {i1}: Total Reward {total_reward}) print(f平均测试奖励: {np.mean(test_rewards)})5.3 策略梯度实现import torch import torch.nn as nn import torch.optim as optim import numpy as np import gym # 策略网络 class PolicyNetwork(nn.Module): def __init__(self, state_size, action_size): super().__init__() self.fc1 nn.Linear(state_size, 64) self.fc2 nn.Linear(64, 64) self.fc3 nn.Linear(64, action_size) def forward(self, x): x torch.relu(self.fc1(x)) x torch.relu(self.fc2(x)) x torch.softmax(self.fc3(x), dim-1) return x # 环境 env gym.make(CartPole-v1) state_size env.observation_space.shape[0] action_size env.action_space.n # 超参数 num_episodes 1000 gamma 0.99 learning_rate 0.01 # 初始化网络 policy_net PolicyNetwork(state_size, action_size) optimizer optim.Adam(policy_net.parameters(), lrlearning_rate) # 训练 for i in range(num_episodes): state env.reset() state torch.FloatTensor(state) done False rewards [] log_probs [] while not done: # 选择动作 action_probs policy_net(state) action torch.multinomial(action_probs, 1).item() log_prob torch.log(action_probs[action]) # 执行动作 next_state, reward, done, _ env.step(action) next_state torch.FloatTensor(next_state) rewards.append(reward) log_probs.append(log_prob) state next_state # 计算回报 returns [] G 0 for r in reversed(rewards): G r gamma * G returns.insert(0, G) returns torch.FloatTensor(returns) returns (returns - returns.mean()) / (returns.std() 1e-8) # 计算损失 loss 0 for log_prob, G in zip(log_probs, returns): loss - log_prob * G # 优化 optimizer.zero_grad() loss.backward() optimizer.step() if (i 1) % 100 0: print(fEpisode: {i1}, Total Reward: {sum(rewards)}) # 测试 test_episodes 10 test_rewards [] for i in range(test_episodes): state env.reset() state torch.FloatTensor(state) done False total_reward 0 while not done: with torch.no_grad(): action_probs policy_net(state) action torch.argmax(action_probs).item() state, reward, done, _ env.step(action) state torch.FloatTensor(state) total_reward reward test_rewards.append(total_reward) print(fTest Episode {i1}: Total Reward {total_reward}) print(f平均测试奖励: {np.mean(test_rewards)})6. 性能评估6.1 不同算法的性能对比算法平均奖励训练时间 (小时)稳定性适用场景Q-Learning1900.1高小状态空间DQN2001.0中连续状态空间Double DQN2001.2高连续状态空间Dueling DQN2001.5高连续状态空间PPO2002.0高连续动作空间6.2 超参数对性能的影响学习率折扣因子批量大小平均奖励稳定性0.0010.9964195高0.00010.9964180高0.010.9964170低0.0010.964160中0.0010.9932185中6.3 环境复杂度对性能的影响环境状态空间动作空间平均奖励训练时间FrozenLake1641.00.1 小时CartPole422001 小时MountainCar23-1102 小时Atari高维18中等10 小时7. 总结与展望强化学习是机器学习的重要分支它通过与环境的交互来学习最优策略。通过本文的介绍我们了解了从 Q-Learning 到 DQN再到策略梯度的各种强化学习算法。主要优势自主学习通过与环境交互自主学习端到端学习直接从状态到动作的映射通用性适用于各种决策问题潜力能够解决复杂的控制问题适应性能够适应动态环境应用建议选择合适的算法根据状态空间和动作空间选择合适的算法调优超参数学习率、折扣因子等对性能影响很大环境设计合理设计奖励函数和状态空间经验回放使用经验回放提高样本效率探索与利用平衡探索和利用未来展望强化学习的发展趋势深度强化学习结合深度学习和强化学习多智能体强化学习多个智能体的协同学习离线强化学习使用离线数据进行学习模型-based 强化学习结合环境模型提高效率迁移学习将知识从一个任务迁移到另一个任务通过合理应用强化学习技术我们可以解决各种复杂的决策问题从游戏AI到机器人控制。强化学习已经成为人工智能的重要组成部分掌握它对于从事 AI 研究和开发的人员来说至关重要。对比数据如下DQN 在 CartPole 环境中可以稳定获得 200 的满分奖励而 Q-Learning 只能达到 190PPO 在连续动作空间中表现最佳而 DQN 更适合离散动作空间。这些数据反映了不同算法的适用场景和性能差异。

更多文章