蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 MDP 5x5 网格 Q-learning、4x4 贝尔曼最优价值求解与延迟奖励实验

PYTHONWindows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。explore-basic-framework-of-reinforcement-learning.py
explore-basic-framework-of-reinforcement-learning.py249 行
"""Independent NumPy reinforcement learning MDP framework, GridWorld Q-learning & Bellman value-function lab."""
import json
import platform
import random
from typing import List, Tuple

import numpy as np


class GridWorldEnv:
    """5x5 GridWorld MDP with obstacle-collision tracking and differentiated rewards."""

    def __init__(
        self,
        grid_size: Tuple[int, int] = (5, 5),
        start_pos: Tuple[int, int] = (0, 0),
        goal_pos: Tuple[int, int] = (4, 4),
        obstacle_pos: List[Tuple[int, int]] | None = None,
    ):
        self.grid_size = grid_size
        self.start_pos = start_pos
        self.goal_pos = goal_pos
        self.obstacle_pos = list(obstacle_pos) if obstacle_pos is not None else [(1, 1), (2, 2), (3, 1)]
        self.current_pos = start_pos
        self.actions = ["up", "down", "left", "right"]
        self.num_actions = len(self.actions)

    def reset(self) -> int:
        self.current_pos = self.start_pos
        return self.pos_to_state(self.current_pos)

    def pos_to_state(self, pos: Tuple[int, int]) -> int:
        return pos[0] * self.grid_size[1] + pos[1]

    def state_to_pos(self, state: int) -> Tuple[int, int]:
        return (state // self.grid_size[1], state % self.grid_size[1])

    def action_to_direction(self, action: int) -> str:
        return self.actions[action]

    def step(self, action: int) -> Tuple[int, float, bool]:
        x, y = self.current_pos
        if action == 0:
            x = max(0, x - 1)
        elif action == 1:
            x = min(self.grid_size[0] - 1, x + 1)
        elif action == 2:
            y = max(0, y - 1)
        elif action == 3:
            y = min(self.grid_size[1] - 1, y + 1)

        new_pos = (x, y)
        hit_obstacle = new_pos in self.obstacle_pos
        if hit_obstacle:
            new_pos = self.current_pos
        self.current_pos = new_pos
        next_state = self.pos_to_state(new_pos)

        if new_pos == self.goal_pos:
            return next_state, 100.0, True
        if hit_obstacle:
            return next_state, -50.0, False
        return next_state, -1.0, False


def run_cases():
    cases = []

    # 1. MDP GridWorld environment dynamics, state-coordinate bijection & obstacle collision fix
    env = GridWorldEnv()
    bijection_ok = all(
        env.state_to_pos(env.pos_to_state((r, c))) == (r, c)
        for r in range(5) for c in range(5)
    )
    s0 = env.reset()
    # Moving up at (0,0) stays at (0,0) with -1.0
    s_wall, r_wall, d_wall = env.step(0)
    # Move right to (0,1), then down into obstacle (1,1) -> stays at (0,1) with -50.0
    s_01, r_01, d_01 = env.step(3)
    s_obs, r_obs, d_obs = env.step(1)
    # Jump to (4,3) and step right to goal (4,4) -> +100.0, done=True
    env.current_pos = (4, 3)
    s_goal, r_goal, d_goal = env.step(3)

    c1_ok = (
        bijection_ok
        and s0 == 0
        and (s_wall, r_wall, d_wall) == (0, -1.0, False)
        and (s_01, r_01, d_01) == (1, -1.0, False)
        and (s_obs, r_obs, d_obs) == (1, -50.0, False)
        and (s_goal, r_goal, d_goal) == (24, 100.0, True)
    )
    cases.append(dict(
        name="mdp_gridworld_env_and_obstacle_reward",
        inputs=dict(grid_size=[5, 5], obstacles=[[1, 1], [2, 2], [3, 1]]),
        prerequisites="5x5 网格 MDP 交互接口、状态坐标双向映射与碰撞障碍物提前标记逻辑",
        action="验证 25 个状态坐标双向映射、常规移动 -1.0、撞障碍物停留原地并触发 -50.0 惩罚以及到达终点 +100.0 终止。",
        expected=dict(bijection_25=True, obstacle_penalty=-50.0, obstacle_stays_put=True, goal_reward=100.0, goal_done=True),
        actual=dict(bijection_25=bijection_ok, obstacle_penalty=r_obs, obstacle_stays_put=(s_obs == s_01), goal_reward=r_goal, goal_done=d_goal),
        measurements=dict(wall_reward=r_wall, obstacle_state_after_hit=env.state_to_pos(s_obs), goal_state=s_goal),
        passed=c1_ok,
    ))

    # 2. Tabular Q-Learning convergence on 5x5 GridWorld (exact setup with tie-breaking)
    random.seed(42)
    np.random.seed(42)
    env = GridWorldEnv()
    Q_table = np.zeros((25, 4), dtype=np.float64)
    lr, gamma, eps, episodes = 0.1, 0.9, 0.1, 1000
    ep_rewards = []
    for _ in range(episodes):
        state = env.reset()
        done = False
        tot = 0.0
        while not done:
            if random.uniform(0.0, 1.0) < eps:
                action = random.randint(0, 3)
            else:
                q_vals = Q_table[state]
                best = np.where(q_vals == np.max(q_vals))[0]
                action = int(random.choice(best))
            next_state, reward, done = env.step(action)
            tot += reward
            next_max = 0.0 if done else float(np.max(Q_table[next_state]))
            Q_table[state, action] += lr * (reward + gamma * next_max - Q_table[state, action])
            state = next_state
        ep_rewards.append(tot)

    # Greedy rollout evaluation
    state = env.reset()
    done = False
    path = [env.state_to_pos(state)]
    greedy_return = 0.0
    while not done and len(path) <= 50:
        a = int(np.argmax(Q_table[state]))
        next_state, reward, done = env.step(a)
        greedy_return += reward
        path.append(env.state_to_pos(next_state))
        state = next_state

    # Optimal Manhattan distance from (0,0) to (4,4) is 8 steps -> 7*(-1) + 100 = 93.0
    no_obs_in_path = all(p not in env.obstacle_pos for p in path)
    c2_ok = done and len(path) - 1 == 8 and greedy_return == 93.0 and no_obs_in_path
    cases.append(dict(
        name="tabular_q_learning_5x5_convergence",
        inputs=dict(episodes=1000, alpha=0.1, gamma=0.9, epsilon=0.1, seed=42),
        prerequisites="ε-贪婪与平局随机打破的表格型 Q-learning 在 5x5 网格收敛",
        action="验证训练 1000 回合后贪婪策略从 (0,0) 避开障碍物用最短 8 步抵达 (4,4),总回报精确为 93.0。",
        expected=dict(reached_goal=True, optimal_steps=8, greedy_return=93.0, avoided_obstacles=True),
        actual=dict(reached_goal=done, optimal_steps=len(path) - 1, greedy_return=greedy_return, avoided_obstacles=no_obs_in_path),
        measurements=dict(
            first10_mean_reward=round(float(np.mean(ep_rewards[:10])), 2),
            last50_mean_reward=round(float(np.mean(ep_rewards[-50:])), 2),
            start_max_q=round(float(np.max(Q_table[0])), 4),
            greedy_path=[list(p) for p in path],
        ),
        passed=c2_ok,
    ))

    # 3. 4x4 Prose GridWorld exact Bellman V*(s) and Q*(s, a) via Value Iteration
    obs4 = {(1, 1), (2, 2)}
    goal4 = (3, 3)
    deltas = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    V = np.zeros((4, 4), dtype=np.float64)
    Q4 = np.zeros((4, 4, 4), dtype=np.float64)
    gamma4 = 0.9
    for _ in range(200):
        V_new = np.zeros_like(V)
        for r in range(4):
            for c in range(4):
                if (r, c) == goal4 or (r, c) in obs4:
                    continue
                for ai, (dr, dc) in enumerate(deltas):
                    nr, nc = r + dr, c + dc
                    if not (0 <= nr < 4 and 0 <= nc < 4) or (nr, nc) in obs4:
                        Q4[r, c, ai] = -5.0 + gamma4 * V[r, c]
                    elif (nr, nc) == goal4:
                        Q4[r, c, ai] = 10.0
                    else:
                        Q4[r, c, ai] = -0.1 + gamma4 * V[nr, nc]
                V_new[r, c] = np.max(Q4[r, c])
        if np.max(np.abs(V_new - V)) < 1e-12:
            V = V_new
            break
        V = V_new

    # Rollout optimal policy on 4x4 grid
    pos = (0, 0)
    steps4 = 0
    ret4 = 0.0
    while pos != goal4 and steps4 < 20:
        ai = int(np.argmax(Q4[pos[0], pos[1]]))
        dr, dc = deltas[ai]
        pos = (pos[0] + dr, pos[1] + dc)
        steps4 += 1
        ret4 += 10.0 if pos == goal4 else -0.1
    bellman_gap = float(np.max([abs(V[r, c] - np.max(Q4[r, c])) for r in range(4) for c in range(4) if (r, c) != goal4 and (r, c) not in obs4]))
    c3_ok = pos == goal4 and steps4 == 6 and bellman_gap < 1e-11 and round(ret4, 2) == 9.5
    cases.append(dict(
        name="mdp_4x4_value_iteration_v_and_q",
        inputs=dict(grid_size=[4, 4], obstacles=[[1, 1], [2, 2]], rewards=dict(goal=10.0, hit=-5.0, step=-0.1), gamma=0.9),
        prerequisites="在正文 4x4 网格 MDP 上精确求解最优状态价值函数 V*(s) 与动作价值函数 Q*(s,a)",
        action="验证贝尔曼最优性恒等式 V*(s)=max_a Q*(s,a) 误差 <1e-11,且最优策略 6 步抵达终点获得回报 9.5。",
        expected=dict(bellman_exact=True, optimal_steps=6, total_return=9.5),
        actual=dict(bellman_exact=(bellman_gap < 1e-11), optimal_steps=steps4, total_return=round(ret4, 2)),
        measurements=dict(
            v_start=round(float(V[0, 0]), 4),
            v_near_goal=round(float(V[3, 2]), 4),
            bellman_max_gap=round(bellman_gap, 13),
        ),
        passed=c3_ok,
    ))

    # 4. Delayed reward vs myopic trap: gamma=0 (myopic) vs gamma=0.9 (long-term value)
    # State 0: action 0 gives +2 now then -10 trap next step; action 1 gives 0 now then +10 goal next step
    def q_two_step(gamma_val: float):
        q_trap = 2.0 + gamma_val * (-10.0)
        q_long = 0.0 + gamma_val * (10.0)
        return round(q_trap, 4), round(q_long, 4), ("trap" if q_trap > q_long else "long_term")

    myopic_t, myopic_l, myopic_choice = q_two_step(0.0)
    far_t, far_l, far_choice = q_two_step(0.9)
    c4_ok = myopic_choice == "trap" and far_choice == "long_term" and far_l == 9.0 and far_t == -7.0
    cases.append(dict(
        name="discount_factor_and_delayed_reward",
        inputs=dict(bait_sequence=[2.0, -10.0], delayed_sequence=[0.0, 10.0], gammas=[0.0, 0.9]),
        prerequisites="对比只看即时奖励(γ=0)与考虑延迟回报(γ=0.9)的价值函数决策差异",
        action="验证 γ=0 时短视选择 +2 陷阱分支,而 γ=0.9 时价值函数正确识别长期回报更高的 +10 分支。",
        expected=dict(myopic_choice="trap", longterm_choice="long_term"),
        actual=dict(myopic_choice=myopic_choice, longterm_choice=far_choice),
        measurements=dict(
            gamma0_values=dict(bait=myopic_t, delayed=myopic_l),
            gamma09_values=dict(bait=far_t, delayed=far_l),
        ),
        passed=c4_ok,
    ))

    payload = dict(
        version=platform.python_version(),
        numpy=np.__version__,
        system=platform.system(),
        cases=cases,
    )
    print(json.dumps(payload, ensure_ascii=False))


if __name__ == "__main__":
    run_cases()
本例需在 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。

入口文件:projects/ml-basic-framework-of-reinforcement-learning-lab/explore-basic-framework-of-reinforcement-learning.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-basic-framework-of-reinforcement-learning.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:机器学习

课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip

下载课程关联工程包:机器学习

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a450.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习