适用于离散动作空间,且智能体具有不同奖励函数的MADDPG代码案例

时间: 2023-12-27 13:02:34 浏览: 54
以下是一个适用于离散动作空间,且智能体具有不同奖励函数的MADDPG代码案例: ```python import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F # 定义 Actor 和 Critic 网络 class Actor(nn.Module): def __init__(self, obs_dim, n_actions, hidden_size): super().__init__() self.fc1 = nn.Linear(obs_dim, hidden_size) self.fc2 = nn.Linear(hidden_size, hidden_size) self.fc3 = nn.Linear(hidden_size, n_actions) def forward(self, obs): x = F.relu(self.fc1(obs)) x = F.relu(self.fc2(x)) x = self.fc3(x) return F.softmax(x, dim=-1) class Critic(nn.Module): def __init__(self, obs_dim, n_actions, hidden_size): super().__init__() self.fc1 = nn.Linear(obs_dim + n_actions, hidden_size) self.fc2 = nn.Linear(hidden_size, hidden_size) self.fc3 = nn.Linear(hidden_size, 1) def forward(self, obs, actions): x = torch.cat([obs, actions], dim=-1) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x # 定义 MADDPG 算法 class MADDPG: def __init__(self, n_agents, obs_dim, n_actions, hidden_size, lr=1e-3, gamma=0.99, tau=0.01): self.n_agents = n_agents self.obs_dim = obs_dim self.n_actions = n_actions self.hidden_size = hidden_size self.lr = lr self.gamma = gamma self.tau = tau self.actors = [Actor(obs_dim, n_actions, hidden_size) for _ in range(n_agents)] self.critics = [Critic(obs_dim * n_agents, n_actions * n_agents, hidden_size) for _ in range(n_agents)] self.actor_optimizers = [optim.Adam(actor.parameters(), lr=lr) for actor in self.actors] self.critic_optimizers = [optim.Adam(critic.parameters(), lr=lr) for critic in self.critics] def get_actions(self, obs, noise=0.1): actions = [] for i in range(self.n_agents): obs_tensor = torch.FloatTensor(obs[i]).unsqueeze(0) action_probs = self.actors[i](obs_tensor) action = torch.multinomial(action_probs, 1).item() action += np.random.normal(scale=noise) action = np.clip(action, 0, self.n_actions - 1) actions.append(action) return actions def update(self, transitions, reward_fn): obs, actions, next_obs, rewards, done = zip(*transitions) obs = torch.FloatTensor(obs) actions = torch.FloatTensor(actions) next_obs = torch.FloatTensor(next_obs) rewards = torch.FloatTensor(rewards) done = torch.FloatTensor(done) # 计算每个智能体的 Q 值 q_values = [] for i in range(self.n_agents): obs_i = obs[:, i, :] actions_i = actions.view(len(actions), -1)[:, i*self.n_actions:(i+1)*self.n_actions] q_value_i = self.critics[i](obs_i, actions_i) q_values.append(q_value_i) # 计算每个智能体的 target Q 值 target_q_values = [] for i in range(self.n_agents): next_actions = [] for j in range(self.n_agents): next_obs_j = next_obs[:, j, :] next_action_probs_j = self.actors[j](next_obs_j) next_action_j = torch.argmax(next_action_probs_j, dim=-1, keepdim=True) next_actions.append(next_action_j) next_actions = torch.cat(next_actions, dim=-1) target_q_value_i = reward_fn(i, obs, actions, next_obs, rewards, done) + self.gamma * self.critics[i](next_obs[:, i, :], next_actions) target_q_values.append(target_q_value_i) # 更新每个智能体的 Critic 网络 for i in range(self.n_agents): critic_loss = F.mse_loss(q_values[i], target_q_values[i]) self.critic_optimizers[i].zero_grad() critic_loss.backward() self.critic_optimizers[i].step() # 更新每个智能体的 Actor 网络 for i in range(self.n_agents): actions_i = actions.view(len(actions), -1)[:, i*self.n_actions:(i+1)*self.n_actions] actor_loss = -self.critics[i](obs[:, i, :], actions_i).mean() self.actor_optimizers[i].zero_grad() actor_loss.backward() self.actor_optimizers[i].step() # 更新每个智能体的 target Actor 网络 for i in range(self.n_agents): for param, target_param in zip(self.actors[i].parameters(), self.target_actors[i].parameters()): target_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data) ``` 其中,`n_agents` 表示智能体的数量,`obs_dim` 表示每个智能体的观察空间维度,`n_actions` 表示每个智能体的动作空间维度,`hidden_size` 表示神经网络的隐藏层大小,`lr` 表示学习率,`gamma` 表示折扣因子,`tau` 表示目标网络更新速率。`get_actions` 方法用于根据当前观察状态选择动作,`update` 方法用于根据经验样本更新模型参数。`reward_fn` 是一个函数,用于计算每个智能体的奖励值。在 `update` 方法中,首先计算每个智能体的 Q 值和 target Q 值,然后分别更新 Critic 和 Actor 网络,最后更新每个智能体的 target Actor 网络。

相关推荐

最新推荐

recommend-type

离散数学手写笔记.pdf

西电计科离散数学手写笔记(笔者期末95+),内容较多较为详实,适合在期末复习的时候翻翻看看
recommend-type

数字信号处理实验报告-(2)-离散傅里叶变换(DFT).doc

数字信号处理实验报告-(2)-离散傅里叶变换(DFT),有代码,几乎每行都有注释,高清原图,完全能看得懂的那种
recommend-type

图像变换之傅里叶_离散余弦变换.ppt

该PPT介绍了图像变换领域中的两个基础的变换, 傅里叶变换和离散余弦变换. 涉及内容包括一维傅里叶变换, 二维离散傅里叶变换, 二维离散傅里叶变换的性质, 快速傅里叶变换, 傅里叶变换在图像处理中的应用; 离散余弦...
recommend-type

使用python实现离散时间傅里叶变换的方法

主要介绍了使用python实现离散时间傅里叶变换的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
recommend-type

数字信号处理实验_2_离散时间系统的时域分析.doc

1.加深对离散线性移不变(LSI)系统基本理论的理解,明确差分方程与系统函数之间的关系密切。 2.初步了解用MATLAB语言进行离散时间系统研究的基本方法。 3.掌握求解离散时间系统单位脉冲响应及任意输入序列引起...
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

【实战演练】MATLAB用遗传算法改进粒子群GA-PSO算法

![MATLAB智能算法合集](https://static.fuxi.netease.com/fuxi-official/web/20221101/83f465753fd49c41536a5640367d4340.jpg) # 2.1 遗传算法的原理和实现 遗传算法(GA)是一种受生物进化过程启发的优化算法。它通过模拟自然选择和遗传机制来搜索最优解。 **2.1.1 遗传算法的编码和解码** 编码是将问题空间中的解表示为二进制字符串或其他数据结构的过程。解码是将编码的解转换为问题空间中的实际解的过程。常见的编码方法包括二进制编码、实数编码和树形编码。 **2.1.2 遗传算法的交叉和
recommend-type

openstack的20种接口有哪些

以下是OpenStack的20种API接口: 1. Identity (Keystone) API 2. Compute (Nova) API 3. Networking (Neutron) API 4. Block Storage (Cinder) API 5. Object Storage (Swift) API 6. Image (Glance) API 7. Telemetry (Ceilometer) API 8. Orchestration (Heat) API 9. Database (Trove) API 10. Bare Metal (Ironic) API 11. DNS
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。