多智能体强化学习示例

程序功能

这段代码实现了一个多智能体强化学习环境,其中两个智能体在5x5的网格上移动:

智能体目标:

Agent 1 从 (0, 0) 出发,目标是 (4, 4)。

Agent 2 从 (4, 4) 出发,目标是 (0, 0)。

动作空间:每个智能体有4个动作(上、下、左、右)。

奖励:到达目标位置获得 10 分,否则每步 -1 分。

终止条件:两个智能体都到达目标。

主程序中,两个智能体在随机动作下执行5个回合,并打印每一步的状态和奖励。

代码

python 复制代码
import numpy as np
import gym
from gym import spaces


# 定义多智能体环境
class MultiAgentEnv(gym.Env):
    def __init__(self):
        super(MultiAgentEnv, self).__init__()

        # 定义网格世界大小
        self.grid_size = 5

        # 智能体的初始位置
        self.agent1_pos = np.array([0, 0])  # Agent 1 起始点
        self.agent2_pos = np.array([4, 4])  # Agent 2 起始点

        # 智能体的目标位置
        self.goal1 = np.array([4, 4])  # Agent 1 的目标
        self.goal2 = np.array([0, 0])  # Agent 2 的目标

        # 定义动作空间和状态空间
        self.action_space = spaces.Discrete(4)  # 上、下、左、右 4 个动作
        self.observation_space = spaces.Box(low=0, high=self.grid_size - 1, shape=(2,), dtype=np.int32)

    def reset(self):
        # 重置智能体的位置
        self.agent1_pos = np.array([0, 0])
        self.agent2_pos = np.array([4, 4])
        return self._get_obs()

    def step(self, actions):
        # 传入两个智能体的动作
        action1, action2 = actions

        # 更新智能体1的位置
        self.agent1_pos = self._move(self.agent1_pos, action1)
        # 更新智能体2的位置
        self.agent2_pos = self._move(self.agent2_pos, action2)

        # 检查是否到达目标
        reward1 = 10 if np.array_equal(self.agent1_pos, self.goal1) else -1
        reward2 = 10 if np.array_equal(self.agent2_pos, self.goal2) else -1

        done1 = np.array_equal(self.agent1_pos, self.goal1)
        done2 = np.array_equal(self.agent2_pos, self.goal2)

        done = done1 and done2

        return self._get_obs(), [reward1, reward2], done, {}

    def _move(self, position, action):
        # 根据动作移动智能体
        if action == 0 and position[0] > 0:  # 向上
            position[0] -= 1
        elif action == 1 and position[0] < self.grid_size - 1:  # 向下
            position[0] += 1
        elif action == 2 and position[1] > 0:  # 向左
            position[1] -= 1
        elif action == 3 and position[1] < self.grid_size - 1:  # 向右
            position[1] += 1
        return position

    def _get_obs(self):
        # 返回两个智能体的当前状态
        return np.array([self.agent1_pos, self.agent2_pos])


# 运行多智能体环境
if __name__ == '__main__':
    env = MultiAgentEnv()

    for episode in range(5):
        print(f"Episode {episode + 1}:")
        obs = env.reset()
        done = False
        step = 0

        while not done:
            actions = [env.action_space.sample(), env.action_space.sample()]  # 随机动作
            obs, rewards, done, info = env.step(actions)
            step += 1
            print(f" Step {step}:")
            print(f"  Agent 1 Position: {obs[0]}, Reward: {rewards[0]}")
            print(f"  Agent 2 Position: {obs[1]}, Reward: {rewards[1]}")
        print("Episode finished!\n")
相关推荐
埃博拉酱15 分钟前
Pip/Conda 混用导致的 CRT 版本冲突问题:[WinError 1114] 动态链接库(DLL)初始化例程失败
windows·python
刘小八15 分钟前
LangGraph 人机交互实战:Interrupt、人工审批与工作流恢复
人工智能·python·人机交互
YMWM_23 分钟前
python-venv虚拟环境
linux·开发语言·python
Tbisnic41 分钟前
23.大模型开发:深度学习----CNN 卷积神经网络 与 RNN 循环神经网络
人工智能·python·rnn·深度学习·cnn·ai大模型
CoderYanger1 小时前
视频切割脚本(Python版)
linux·开发语言·windows·后端·python·程序人生·职场和发展
迷途呀1 小时前
新闻头条后端:新闻缓存模块
前端·redis·python·缓存·fastapi
想会飞的蒲公英1 小时前
逻辑回归为什么叫回归,却用来做分类
人工智能·python·分类·回归·逻辑回归
CoderYanger2 小时前
视频裁剪+缩放+自动添加水印脚本(Python版)
开发语言·后端·python·程序人生·职场和发展·音视频·学习方法
霍格沃兹测试开发学社测试人社区2 小时前
Node.js 浏览器引擎 + Python 大脑:Playwright 混合架构爬虫系统深度解析
python·架构·node.js
绘梨衣5472 小时前
求助帖:pdf复杂表格解析
爬虫·python·pdf