共计 1886 个字符,预计需要花费 5 分钟才能阅读完成。
教学价值与建模框架
4×4 方格世界作为强化学习的经典教学案例,其核心价值体现在三个方面:
1. 状态空间离散:16 个网格单元对应有限状态集合,避免连续空间的处理复杂度
2. 可解释性强:二维平面布局便于可视化策略路径与价值函数分布
3. 完备性验证:小规模状态空间允许精确计算最优策略,验证算法正确性

MDP 五元组定义规范
| 要素 | 数学表示 | 本场景实例化说明 |
|---|---|---|
| 状态空间 $S$ | ${s_1,…,s_{16}}$ | 网格坐标 $(x,y), x,y\in[0,3]$ |
| 动作空间 $A$ | ${上, 下, 左, 右}$ | 四向移动,边界外动作保持原状态 |
| 转移概率 $P$ | $P(s’\mid s,a)$ | 确定性转移:执行动作即到达相邻网格 |
| 奖励函数 $R$ | $R(s,a,s’)$ | 终点 +100,障碍 -10,每步 -1 |
| 折扣因子 $\gamma$ | $[0,1]$ | 典型取值 0.9,平衡即时 / 未来奖励 |
核心实现方法论
状态编码方案
采用二维坐标离散化表示,状态索引 $k$ 与坐标 $(x,y)$ 的转换公式:
$$k = 4 \times y + x$$
逆向映射:
$$x = k \mod 4, \quad y = \lfloor k/4 \rfloor$$
动作空间边界处理
定义动作映射向量:
action_effects = {0: (-1, 0), # 上
1: (1, 0), # 下
2: (0, -1), # 左
3: (0, 1) # 右
}
边界检测逻辑:
def is_valid(x, y):
return 0 <= x < 4 and 0 <= y < 4 and (x,y) not in obstacles
奖励函数设计
分段函数实现策略:
def get_reward(next_state):
if next_state == goal:
return 100
elif next_state in obstacles:
return -10
else:
return -1 # 步长惩罚
完整 Python 实现
import numpy as np
import matplotlib.pyplot as plt
class GridWorldMDP:
def __init__(self):
self.size = 4
self.goal = (3, 3)
self.obstacles = [(1, 1), (2, 2)]
self.actions = [0, 1, 2, 3] # 上, 下, 左, 右
self.gamma = 0.9
# 初始化转移矩阵 |S|x|A|x|S|
self.P = np.zeros((16, 4, 16))
self.build_transition_matrix()
def state_to_idx(self, x, y):
return y * 4 + x
def build_transition_matrix(self):
for x in range(4):
for y in range(4):
current = self.state_to_idx(x, y)
for a in self.actions:
dx, dy = self._get_action_effect(a)
nx, ny = x + dx, y + dy
if not (0 <= nx < 4 and 0 <= ny < 4):
nx, ny = x, y # 碰壁处理
next_state = self.state_to_idx(nx, ny)
self.P[current, a, next_state] = 1
def _get_action_effect(self, a):
return [(-1,0), (1,0), (0,-1), (0,1)][a]
def render(self, policy=None):
grid = np.zeros((4,4))
for obs in self.obstacles:
grid[obs[1], obs[0]] = -1
grid[self.goal[1], self.goal[0]] = 2
plt.figure(figsize=(5,5))
plt.imshow(grid, cmap='Pastel1')
# 添加坐标标注与策略箭头
plt.show()
关键问题规避指南
- 折扣因子选择
- $\gamma$ 接近 1 时更重视长期回报,但可能导致收敛缓慢
-
实验表明 $\gamma=0.9$ 在 4×4 网格中平衡探索与利用
-
稀疏奖励优化
- 增加步长惩罚 (-1) 解决终点奖励过于稀疏问题
-
障碍物负奖励 (-10) 加速策略优化路径
-
状态爆炸预防
- 保持动作空间离散化(4 方向)
- 避免引入额外状态变量(如速度、方向等)
进阶思考方向
- 随机转移扩展:修改
build_transition_matrix(),以概率 $p$ 执行预期动作,以 $1-p$ 随机选择其他动作 - 价值迭代分析:比较 $\gamma=0.5$ 与 $\gamma=0.9$ 时的收敛迭代次数差异
- 复杂度增长:N×N 网格的状态空间为 $O(N^2)$,动作空间保持 $O(1)$,但策略求解时间增至 $O(N^3)$
正文完
发表至: 未分类
近三天内
