当前位置: 首页 > web >正文

Python智能体开发

以下是一个基于Python的简单AI智能体实现示例,使用强化学习(Q-Learning算法)解决迷宫导航问题。这个案例可以帮助你快速理解AI Agent的核心实现逻辑。

 

---

 

### **1. 环境定义(迷宫)**

```python

import numpy as np

 

# 定义迷宫环境(0=可行走区域,1=障碍,2=目标)

maze = np.array([

    [0, 1, 0, 0],

    [0, 1, 0, 1],

    [0, 0, 0, 1],

    [1, 0, 2, 1]

])

start_pos = (0, 0) # 起始位置

```

 

---

 

### **2. Q-Learning智能体类**

```python

class QLearningAgent:

    def __init__(self, maze, alpha=0.1, gamma=0.9, epsilon=0.1):

        self.maze = maze

        self.actions = ['up', 'down', 'left', 'right'] # 可用动作

        self.q_table = np.zeros((maze.shape[0], maze.shape[1], len(self.actions))) # Q表

        self.alpha = alpha # 学习率

        self.gamma = gamma # 折扣因子

        self.epsilon = epsilon # 探索率

 

    def choose_action(self, state):

        # ε-greedy策略选择动作

        if np.random.uniform(0, 1) < self.epsilon:

            return np.random.choice(self.actions) # 随机探索

        else:

            x, y = state

            return self.actions[np.argmax(self.q_table[x, y])] # 选择最优动作

 

    def update_q_table(self, state, action, reward, next_state):

        # Q值更新公式

        x, y = state

        next_x, next_y = next_state

        action_idx = self.actions.index(action)

        old_value = self.q_table[x, y, action_idx]

        next_max = np.max(self.q_table[next_x, next_y])

        new_value = (1 - self.alpha) * old_value + self.alpha * (reward + self.gamma * next_max)

        self.q_table[x, y, action_idx] = new_value

 

    def get_next_state(self, state, action):

        # 根据动作计算下一个状态

        x, y = state

        if action == 'up' and x > 0 and self.maze[x-1][y] != 1:

            return (x-1, y)

        elif action == 'down' and x < self.maze.shape[0]-1 and self.maze[x+1][y] != 1:

            return (x+1, y)

        elif action == 'left' and y > 0 and self.maze[x][y-1] != 1:

            return (x, y-1)

        elif action == 'right' and y < self.maze.shape[1]-1 and self.maze[x][y+1] != 1:

            return (x, y+1)

        return state # 无效动作保持原地

```

 

---

 

### **3. 训练过程**

```python

def train_agent(episodes=500):

    agent = QLearningAgent(maze)

    for episode in range(episodes):

        state = start_pos

        total_reward = 0

        while True:

            action = agent.choose_action(state)

            next_state = agent.get_next_state(state, action)

            

            # 计算奖励

            if maze[next_state] == 2:

                reward = 10 # 到达目标

                done = True

            elif next_state == state:

                reward = -1 # 撞墙惩罚

                done = False

            else:

                reward = -0.1 # 每步小惩罚

                done = False

 

            # 更新Q表

            agent.update_q_table(state, action, reward, next_state)

            state = next_state

            total_reward += reward

 

            if done or total_reward < -20: # 防止无限循环

                break

                

        if (episode+1) % 100 == 0:

            print(f"Episode {episode+1}, Total Reward: {total_reward}")

    return agent

 

trained_agent = train_agent()

```

 

---

 

### **4. 测试智能体**

```python

def test_agent(agent):

    state = start_pos

    path = [state]

    while True:

        action = agent.actions[np.argmax(agent.q_table[state])]

        next_state = agent.get_next_state(state, action)

        path.append(next_state)

        if maze[next_state] == 2:

            print("Goal Reached! Path:", path)

            break

        state = next_state

 

test_agent(trained_agent)

```

 

---

 

### **代码解释**

1. **Q表结构**:`q_table[行][列][动作]` 存储每个状态-动作对的预期收益。

2. **动作选择**:使用ε-greedy策略平衡探索与利用。

3. **奖励设计**:

   - 到达目标:+10

   - 撞墙:-1

   - 每步移动:-0.1(鼓励快速到达目标)

4. **训练输出示例**:

   ```

   Episode 100, Total Reward: -4.3

   Episode 200, Total Reward: 6.2

   Episode 500, Total Reward: 8.9

   Goal Reached! Path: [(0,0), (0,1), (1,1), (2,1), (2,2), (3,2)]

   ```

 

---

 

### **扩展方向**

1. **深度Q网络(DQN)**:使用神经网络替代Q表(适合更大状态空间):

   ```python

   import torch

   import torch.nn as nn

 

   class DQN(nn.Module):

       def __init__(self, input_size, output_size):

           super().__init__()

           self.net = nn.Sequential(

               nn.Linear(input_size, 64),

               nn.ReLU(),

               nn.Linear(64, output_size)

           )

       

       def forward(self, x):

           return self.net(x)

   ```

 

2. **集成OpenAI Gym**:使用标准环境(如`FrozenLake`):

   ```python

   import gym

   env = gym.make('FrozenLake-v1')

   ```

 

3. **多智能体协作**:使用`PettingZoo`库实现多Agent系统。

 

---

 

### **关键调试技巧**

1. **可视化Q表**:`print(agent.q_table)`

2. **调整超参数**:尝试不同的`alpha`(学习率)和`gamma`(未来奖励折扣)

3. **奖励塑形**:修改奖励函数以加速收敛

 

这个案例展示了AI Agent开发的核心要素:**环境交互、学习算法、奖励机制**。实际项目中可结合PyTorch/TensorFlow、ROS(机器人)或LangChain(语言模型)构建更复杂的系统。

http://www.xdnf.cn/news/3555.html

相关文章:

  • LeetCode[102]二叉树的层序遍历
  • 走进AI的奇妙世界:探索历史、革命与未来机遇
  • Mybatis中的一级二级缓存扫盲
  • 如何使用模块
  • [FPGA Video] AXI4-Stream Remapper
  • vue3+ts项目 配置vue-router
  • TS 安装
  • 仿腾讯会议——注册登录实现
  • AI算法可视化:如何用Matplotlib与Seaborn解释模型?
  • Bootstrap(自助法)​​:无需假设分布的统计推断工具
  • 「Mac畅玩AIGC与多模态13」开发篇09 - 基于多插件协同开发智能体应用(天气+名言查询助手)
  • DeepSeek实战--各版本对比
  • 【AI科技】AMD ROCm 6.4 新功能:突破性推理、即插即用容器和模块化部署,可在 AMD Instinct GPU 上实现可扩展 AI
  • [原创](现代Delphi 12指南):[macOS 64bit App开发]: [2]如何使用跨平台消息框?
  • 低代码/AI是否会取代前端开发?
  • C++之类和对象基础
  • 开启 Spring AI 之旅:从入门到实战
  • 【c++】【STL】priority_queue详解
  • 网络原理 - 13(HTTP/HTTPS - 4 - HTTPS)
  • 敏感词 v0.25.0 新特性之 wordCheck 策略支持用户自定义
  • Linux52 运行百度网盘 解决故障无法访问repo nosandbox 未解决:疑似libstdc++版本低导致无法运行baidu网盘
  • 兰亭妙微分享:B 端设计如何实现体验跃迁
  • [吾爱出品] 网文提取精灵_4.0
  • 2.4 GHz频段的11个信道通过 5 MHz中心频率间隔 实现覆盖
  • 开闭原则(OCP)
  • Qt/C++开发监控GB28181系统/云台控制/获取预置位信息/添加删除调用预置位
  • 为美好的XCPC献上典题 ABC359 G - Sum of Tree Distance(根号分治)
  • JVM性能调优的基础知识 | JVM内部优化与运行时优化
  • 3033. 修改矩阵
  • 2025年- H19-Lc127-48.旋转矩阵(矩阵)---java版