使用Matplotlib绘制游戏内表示论的可视化方法与实例解析

引言:游戏内表示论与数据可视化的重要性
在现代游戏开发中,
游戏内表示论(Game Representation Theory)
是一个核心概念,它涉及如何将复杂的游戏状态、玩家行为和系统动态转化为可计算、可分析的数学表示。这种表示通常包括状态空间、动作空间、奖励函数、策略网络等。然而,这些高维、抽象的数据往往难以直观理解。
Matplotlib
作为Python中最强大的数据可视化库之一,能够将这些抽象概念转化为直观的图表,帮助开发者、研究人员和玩家更好地理解游戏机制。
通过可视化,我们可以:
洞察状态转移规律
:观察游戏状态如何随时间演变
分析策略有效性
:比较不同策略的性能差异
调试强化学习模型
:直观展示训练过程中的收敛情况
增强教学演示
:让抽象概念变得具体可感
本文将深入探讨如何使用Matplotlib绘制游戏内表示论的各种可视化方法,并通过完整的代码实例进行详细解析。
1. 基础准备:环境配置与数据结构
1.1 安装与导入
首先,确保你的环境中安装了必要的库:
# 核心库
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.patches import Circle, Rectangle, FancyArrowPatch
import matplotlib.animation as animation

# 游戏环境模拟(我们将创建一个简单的网格世界)
import gym
from collections import defaultdict
import random
1.2 数据结构设计
在游戏表示论中,我们通常需要处理以下数据结构:
# 示例:网格世界游戏的状态表示
class GridWorldState:
def __init__(self, x, y, grid_size=5):
self.x = x
self.y = y
self.grid_size = grid_size

def to_tuple(self):
return (self.x, self.y)

def is_terminal(self):
# 终端状态:右上角
return self.x == self.grid_size – 1 and self.y == self.grid_size – 1

# 示例:Q值表(状态-动作值函数)
class QTable:
def __init__(self, states, actions):
self.q_table = defaultdict(lambda: {a: 0.0 for a in actions})

def get(self, state, action):
return self.q_table[state.to_tuple()][action]

def set(self, state, action, value):
self.q_table[state.to_tuple()][action] = value
2. 状态空间可视化
2.1 网格世界状态图
状态空间是游戏表示论的基础。对于离散状态(如网格世界),我们可以用热力图表示状态价值函数 V(s)。
完整实例:绘制状态价值函数热力图
def visualize_state_value_function(v_function, grid_size=5, title=”State Value Function”):
“””
可视化状态价值函数 V(s)

参数:
– v_function: 字典,键为状态元组 (x,y),值为价值
– grid_size: 网格大小
– title: 图表标题
“””
# 创建价值矩阵
value_matrix = np.zeros((grid_size, grid_size))
for state, value in v_function.items():
x, y = state
value_matrix[y, x] = value # 注意:y轴向下

# 创建图形
fig, ax = plt.subplots(figsize=(10, 8))

# 使用imshow绘制热力图
im = ax.imshow(value_matrix, cmap=’viridis’, interpolation=’nearest’)

# 添加数值标签
for i in range(grid_size):
for j in range(grid_size):
text = ax.text(j, i, f'{value_matrix[i, j]:.2f}’,
ha=”center”, va=”center”, color=”w”, fontsize=12)

# 设置网格线
ax.set_xticks(np.arange(grid_size))
ax.set_yticks(np.arange(grid_size))
ax.set_xticklabels([f’x={i}’ for i in range(grid_size)])
ax.set_yticklabels([f’y={i}’ for i in range(grid_size)])

# 添加标题和颜色条
ax.set_title(title, fontsize=16, pad=20)
plt.colorbar(im, ax=ax, label=’Value’)

# 标记终端状态
ax.add_patch(Rectangle((grid_size-1, grid_size-1), 1, 1,
fill=False, edgecolor=’red’, linewidth=3))
ax.text(grid_size-1, grid_size-1, ‘Terminal’,
ha=”center”, va=”center”, color=”red”, fontsize=10, weight=’bold’)

plt.tight_layout()
return fig, ax

# 示例数据:随机生成的状态价值函数(模拟训练结果)
def generate_sample_v_function(grid_size=5):
“””生成示例状态价值函数”””
v_func = {}
for x in range(grid_size):
for y in range(grid_size):
# 模拟价值:越接近右上角价值越高
distance = (grid_size – 1 – x) + (grid_size – 1 – y)
value = 10 * np.exp(-distance * 0.3) + np.random.normal(0, 0.1)
v_func[(x, y)] = value
return v_func

# 执行可视化
v_function = generate_sample_v_function()
fig, ax = visualize_state_value_function(v_function, grid_size=5)
plt.show()
2.2 状态转移概率可视化
在游戏表示论中,状态转移概率 P(s’|s,a) 是核心。我们可以用箭头图表示。
def visualize_state_transitions(transition_prob, grid_size=5):
“””
可视化状态转移概率

参数:
– transition_prob: 字典,键为 (state, action),值为 {next_state: probability}
– grid_size: 网格大小
“””
fig, ax = plt.subplots(figsize=(10, 10))

# 绘制网格
for i in range(grid_size + 1):
ax.axhline(i, color=’gray’, alpha=0.3)
ax.axvline(i, color=’gray’, alpha=0.3)

# 绘制状态点
for x in range(grid_size):
for y in range(grid_size):
ax.plot(x, y, ‘o’, markersize=10, color=’blue’)
if x == grid_size – 1 and y == grid_size – 1:
ax.plot(x, y, ‘s’, markersize=15, color=’red’, label=’Terminal’)

# 绘制转移箭头
arrow_colors = {‘up’: ‘green’, ‘down’: ‘red’, ‘left’: ‘orange’, ‘right’: ‘purple’}
action_offsets = {
‘up’: (0, 0.3), ‘down’: (0, -0.3),
‘left’: (-0.3, 0), ‘right’: (0.3, 0)
}

for (state, action), next_states in transition_prob.items():
x, y = state
for next_state, prob in next_states.items():
nx, ny = next_state
# 只绘制高概率转移
if prob > 0.1:
# 计算箭头位置(偏移避免重叠)
offset = action_offsets[action]
start_x = x + offset[0] * 0.5
start_y = y + offset[1] * 0.5
end_x = nx + offset[0] * 0.5
end_y = ny + offset[1] * 0.5

# 绘制箭头
ax.annotate(”, xy=(end_x, end_y), xytext=(start_x, start_y),
arrowprops=dict(arrowstyle=’->’,
color=arrow_colors[action],
lw=prob * 5, # 线宽与概率成正比
alpha=0.7))

# 添加图例
from matplotlib.lines import Line2D
legend_elements = [
Line2D([0], [0], marker=’o’, color=’w’, markerfacecolor=’blue’, markersize=10, label=’State’),
Line2D([0], [0], marker=’s’, color=’w’, markerfacecolor=’red’, markersize=10, label=’Terminal’),
Line2D([0], [0], color=’green’, lw=2, label=’Up’),
Line2D([0], [0], color=’red’, lw=2, label=’Down’),
Line2D([0], [0], color=’orange’, lw=2, label=’Left’),
Line2D([0], [0], color=’purple’, lw=2, label=’Right’)
]
ax.legend(handles=legend_elements, loc=’upper right’)

ax.set_title(‘State Transition Probabilities’, fontsize=16)
ax.set_aspect(‘equal’)
ax.set_xlim(-1, grid_size)
ax.set_ylim(-1, grid_size)

return fig, ax

# 示例:创建转移概率数据
def generate_transition_probabilities(grid_size=5):
“””生成示例状态转移概率”””
transitions = {}
actions = [‘up’, ‘down’, ‘left’, ‘right’]

for x in range(grid_size):
for y in range(grid_size):
state = (x, y)
for action in actions:
next_states = {}
# 确定性转移(简化)
if action == ‘up’:
ny = max(0, y – 1)
next_states[(x, ny)] = 0.8
next_states[(x, y)] = 0.2 # 滑移
elif action == ‘down’:
ny = min(grid_size – 1, y + 1)
next_states[(x, ny)] = 0.8
next_states[(x, y)] = 0.2
elif action == ‘left’:
nx = max(0, x – 1)
next_states[(nx, y)] = 0.8
next_states[(x, y)] = 0.2
elif action == ‘right’:
nx = min(grid_size – 1, x + 1)
next_states[(nx, y)] = 0.8
next_states[(x, y)] = 0.2

transitions[(state, action)] = next_states

return transitions

# 执行可视化
transitions = generate_transition_probabilities()
fig, ax = visualize_state_transitions(transitions, grid_size=5)
plt.show()
3. 策略与动作空间可视化
3.1 策略热力图
策略 π(a|s) 表示在给定状态下选择每个动作的概率。我们可以用分组热力图表示。
def visualize_policy_heatmap(policy, grid_size=5, action_names=None):
“””
可视化策略 π(a|s) 作为热力图

参数:
– policy: 字典,键为状态,值为动作概率分布 {action: prob}
– grid_size: 网格大小
– action_names: 动作名称列表
“””
if action_names is None:
action_names = [‘up’, ‘down’, ‘left’, ‘right’]

# 创建子图网格
n_actions = len(action_names)
fig, axes = plt.subplots(1, n_actions, figsize=(4 * n_actions, 8))
if n_actions == 1:
axes = [axes]

# 为每个动作创建一个热力图
for idx, action in enumerate(action_names):
prob_matrix = np.zeros((grid_size, grid_size))

for x in range(grid_size):
for y in range(grid_size):
state = (x, y)
if state in policy:
prob_matrix[y, x] = policy[state].get(action, 0)

im = axes[idx].imshow(prob_matrix, cmap=’Blues’, vmin=0, vmax=1)

# 添加数值标签
for i in range(grid_size):
for j in range(grid_size):
axes[idx].text(j, i, f'{prob_matrix[i, j]:.2f}’,
ha=”center”, va=”center”, color=”black”, fontsize=8)

axes[idx].set_title(f’Action: {action}’, fontsize=12)
axes[idx].set_xticks(np.arange(grid_size))
axes[idx].set_yticks(np.arange(grid_size))

# 添加颜色条
plt.colorbar(im, ax=axes[idx], fraction=0.046, pad=0.04)

plt.suptitle(‘Policy Heatmap per Action’, fontsize=16, y=1.02)
plt.tight_layout()
return fig, axes

# 示例:生成随机策略
def generate_random_policy(grid_size=5):
“””生成示例策略”””
policy = {}
actions = [‘up’, ‘down’, ‘left’, ‘right’]

for x in range(grid_size):
for y in range(grid_size):
state = (x, y)
# 靠近目标时偏向右和上
if x < grid_size - 1 and y < grid_size - 1: probs = [0.2, 0.2, 0.2, 0.4] # 右和上概率稍高 else: probs = [0.25, 0.25, 0.25, 0.25] policy[state] = {action: prob for action, prob in zip(actions, probs)} return policy # 执行可视化 policy = generate_random_policy() fig, axes = visualize_policy_heatmap(policy, grid_size=5) plt.show() 3.2 策略箭头图 另一种直观表示策略的方式是用箭头表示最可能的动作。 def visualize_policy_arrows(policy, grid_size=5, title="Policy Arrows"): """ 用箭头可视化策略 参数: - policy: 字典,键为状态,值为动作概率分布 - grid_size: 网格大小 - title: 图表标题 """ fig, ax = plt.subplots(figsize=(10, 10)) # 绘制网格 for i in range(grid_size + 1): ax.axhline(i, color='gray', alpha=0.3) ax.axvline(i, color='gray', alpha=0.3) # 绘制状态点 for x in range(grid_size): for y in range(grid_size): ax.plot(x, y, 'o', markersize=8, color='lightblue') # 绘制箭头 action_offsets = { 'up': (0, 0.3), 'down': (0, -0.3), 'left': (-0.3, 0), 'right': (0.3, 0) } action_vectors = { 'up': (0, 0.4), 'down': (0, -0.4), 'left': (-0.4, 0), 'right': (0.4, 0) } for state, action_probs in policy.items(): x, y = state # 找到最大概率动作 best_action = max(action_probs, key=action_probs.get) prob = action_probs[best_action] # 只绘制概率足够高的动作 if prob > 0.3:
dx, dy = action_vectors[best_action]
offset = action_offsets[best_action]

# 绘制箭头
ax.annotate(”, xy=(x + dx, y + dy), xytext=(x + offset[0], y + offset[1]),
arrowprops=dict(arrowstyle=’->’,
color=’darkblue’,
lw=2 + prob * 3,
alpha=0.8))

# 添加概率文本
ax.text(x, y, f'{prob:.2f}’, ha=”center”, va=”center”,
fontsize=9, color=’darkred’, weight=’bold’)

# 标记终端状态
ax.add_patch(Rectangle((grid_size-1, grid_size-1), 1, 1,
fill=False, edgecolor=’red’, linewidth=3))
ax.text(grid_size-1, grid_size-1, ‘Terminal’,
ha=”center”, va=”center”, color=”red”, fontsize=10, weight=’bold’)

ax.set_title(title, fontsize=16)
ax.set_aspect(‘equal’)
ax.set_xlim(-1, grid_size)
ax.set_ylim(-1, grid_size)
ax.set_xlabel(‘X coordinate’)
ax.set_ylabel(‘Y coordinate’)

return fig, ax

# 执行可视化
fig, ax = visualize_policy_arrows(policy, grid_size=5)
plt.show()
4. 训练过程可视化
4.1 学习曲线
在强化学习中,监控训练过程至关重要。我们可以绘制累积奖励、损失函数等。
class TrainingMonitor:
“””训练监控器,记录训练指标”””
def __init__(self):
self.episode_rewards = []
self.episode_lengths = []
self.losses = []
self.q_values = []
self.episode_numbers = []

def add_episode(self, episode_num, reward, length):
self.episode_numbers.append(episode_num)
self.episode_rewards.append(reward)
self.episode_lengths.append(length)

def add_loss(self, loss):
self.losses.append(loss)

def add_q_value(self, q_value):
self.q_values.append(q_value)

def plot_training_curves(monitor, window=100):
“””
绘制训练曲线

参数:
– monitor: TrainingMonitor对象
– window: 滑动平均窗口大小
“””
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
fig.suptitle(‘Training Metrics’, fontsize=16)

# 1. 累积奖励
if monitor.episode_rewards:
ax = axes[0, 0]
episodes = monitor.episode_numbers

# 原始奖励
ax.plot(episodes, monitor.episode_rewards, alpha=0.3, color=’blue’, label=’Raw’)

# 滑动平均
if len(monitor.episode_rewards) >= window:
moving_avg = np.convolve(monitor.episode_rewards,
np.ones(window)/window, mode=’valid’)
ax.plot(episodes[window-1:], moving_avg, color=’blue’, linewidth=2,
label=f’Moving Avg ({window})’)

ax.set_xlabel(‘Episode’)
ax.set_ylabel(‘Cumulative Reward’)
ax.set_title(‘Episode Rewards’)
ax.legend()
ax.grid(True, alpha=0.3)

# 2. Episode长度
if monitor.episode_lengths:
ax = axes[0, 1]
ax.plot(monitor.episode_numbers, monitor.episode_lengths,
color=’green’, alpha=0.7)
ax.set_xlabel(‘Episode’)
ax.set_ylabel(‘Length’)
ax.set_title(‘Episode Length’)
ax.grid(True, alpha=0.3)

# 3. 损失函数
if monitor.losses:
ax = axes[1, 0]
ax.plot(monitor.losses, color=’red’, alpha=0.7)
ax.set_xlabel(‘Step’)
ax.set_ylabel(‘Loss’)
ax.set_title(‘Training Loss’)
ax.set_yscale(‘log’) # 对数尺度
ax.grid(True, alpha=0.3)

# 4. Q值分布
if monitor.q_values:
ax = axes[1, 1]
# 绘制Q值的直方图
ax.hist(monitor.q_values, bins=30, color=’purple’, alpha=0.7, edgecolor=’black’)
ax.set_xlabel(‘Q-Value’)
ax.set_ylabel(‘Frequency’)
ax.set_title(‘Q-Value Distribution’)
ax.grid(True, alpha=0.3)

plt.tight_layout()
return fig, axes

# 模拟训练过程
def simulate_training(monitor, n_episodes=500):
“””模拟训练过程并记录指标”””
for episode in range(n_episodes):
# 模拟累积奖励(收敛趋势)
base_reward = 100 * (1 – np.exp(-episode / 100))
noise = np.random.normal(0, 10)
reward = max(0, base_reward + noise)

# 模拟episode长度(逐渐减少)
length = max(10, int(200 – episode * 0.3) + np.random.randint(-5, 5))

monitor.add_episode(episode, reward, length)

# 模拟损失(波动下降)
if episode % 10 == 0:
loss = 10 * np.exp(-episode / 50) * (1 + 0.1 * np.random.randn())
monitor.add_loss(loss)

# 模拟Q值(逐渐增加)
if episode % 5 == 0:
q_value = 50 * (1 – np.exp(-episode / 80)) + np.random.normal(0, 2)
monitor.add_q_value(q_value)

# 执行可视化
monitor = TrainingMonitor()
simulate_training(monitor, n_episodes=500)
fig, axes = plot_training_curves(monitor, window=50)
plt.show()
4.2 动态策略演化动画
使用Matplotlib的动画功能展示策略如何随训练演化。
def create_policy_animation(policies, grid_size=5, interval=200):
“””
创建策略演化动画

参数:
– policies: 列表,每个元素是某次训练迭代的策略
– grid_size: 网格大小
– interval: 帧间隔(毫秒)
“””
fig, ax = plt.subplots(figsize=(10, 10))

# 初始化
def init():
ax.clear()
# 绘制网格
for i in range(grid_size + 1):
ax.axhline(i, color=’gray’, alpha=0.3)
ax.axvline(i, color=’gray’, alpha=0.3)
# 绘制状态点
for x in range(grid_size):
for y in range(grid_size):
ax.plot(x, y, ‘o’, markersize=8, color=’lightblue’)
# 标记终端
ax.add_patch(Rectangle((grid_size-1, grid_size-1), 1, 1,
fill=False, edgecolor=’red’, linewidth=3))
return []

# 动画更新函数
def update(frame):
ax.clear()
policy = policies[frame]

# 重新绘制基础元素
for i in range(grid_size + 1):
ax.axhline(i, color=’gray’, alpha=0.3)
ax.axvline(i, color=’gray’, alpha=0.3)
for x in range(grid_size):
for y in range(grid_size):
ax.plot(x, y, ‘o’, markersize=8, color=’lightblue’)
ax.add_patch(Rectangle((grid_size-1, grid_size-1), 1, 1,
fill=False, edgecolor=’red’, linewidth=3))

# 绘制当前策略箭头
action_vectors = {
‘up’: (0, 0.4), ‘down’: (0, -0.4),
‘left’: (-0.4, 0), ‘right’: (0.4, 0)
}

for state, action_probs in policy.items():
x, y = state
best_action = max(action_probs, key=action_probs.get)
prob = action_probs[best_action]

if prob > 0.3:
dx, dy = action_vectors[best_action]
ax.annotate(”, xy=(x + dx, y + dy), xytext=(x, y),
arrowprops=dict(arrowstyle=’->’,
color=’darkblue’,
lw=2 + prob * 3,
alpha=0.8))

ax.set_title(f’Policy Evolution – Iteration {frame + 1}’, fontsize=16)
ax.set_aspect(‘equal’)
ax.set_xlim(-1, grid_size)
ax.set_ylim(-1, grid_size)
return []

# 创建动画
anim = animation.FuncAnimation(fig, update, frames=len(policies),
init_func=init, interval=interval, blit=False)

return anim

# 生成策略演化序列
def generate_policy_evolution(grid_size=5, n_iterations=10):
“””生成策略演化序列”””
policies = []
actions = [‘up’, ‘down’, ‘left’, ‘right’]

for iteration in range(n_iterations):
policy = {}
progress = iteration / (n_iterations – 1)

for x in range(grid_size):
for y in range(grid_size):
state = (x, y)
# 随着迭代,策略逐渐收敛到最优(右上)
if x < grid_size - 1 and y < grid_size - 1: # 偏向右和上,且随迭代增强 right_prob = 0.2 + 0.6 * progress up_prob = 0.2 + 0.2 * progress left_prob = 0.2 * (1 - progress) down_prob = 0.2 * (1 - progress) probs = [up_prob, down_prob, left_prob, right_prob] else: probs = [0.25, 0.25, 0.25, 0.25] policy[state] = {action: prob for action, prob in zip(actions, probs)} policies.append(policy) return policies # 创建并显示动画(注意:在Jupyter中需要特定设置才能显示动画) policies = generate_policy_evolution(grid_size=5, n_iterations=15) anim = create_policy_animation(policies, grid_size=5, interval=300) # 保存为GIF(需要pillow库) # anim.save('policy_evolution.gif', writer='pillow', fps=3) # 在Jupyter中显示 from IPython.display import HTML HTML(anim.to_jshtml()) 5. 高级可视化:Q值与价值函数 5.1 Q值表面图 对于连续或高维状态空间,我们可以用3D表面图表示Q值函数。 def plot_q_surface(q_table, grid_size=5, action='right'): """ 绘制Q值表面图(3D) 参数: - q_table: Q值表对象 - grid_size: 网格大小 - action: 要绘制的动作 """ fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(111, projection='3d') # 创建网格 X = np.arange(0, grid_size, 1) Y = np.arange(0, grid_size, 1) X, Y = np.meshgrid(X, Y) Z = np.zeros_like(X, dtype=float) # 填充Q值 for i in range(grid_size): for j in range(grid_size): state = (i, j) Z[j, i] = q_table.get(GridWorldState(i, j), action) # 绘制表面 surf = ax.plot_surface(X, Y, Z, cmap=cm.viridis, linewidth=0, antialiased=True, alpha=0.8) # 添加等高线 ax.contour(X, Y, Z, zdir='z', offset=Z.min() - 1, cmap=cm.viridis, alpha=0.5) # 设置标签 ax.set_xlabel('X coordinate') ax.set_ylabel('Y coordinate') ax.set_zlabel(f'Q-value for {action}') ax.set_title(f'Q-Value Surface: {action}', fontsize=16) # 添加颜色条 fig.colorbar(surf, ax=ax, shrink=0.5, aspect=5, label='Q-Value') # 调整视角 ax.view_init(elev=30, azim=45) return fig, ax # 示例:创建Q值表并绘制 q_table = QTable(states=[], actions=['up', 'down', 'left', 'right']) # 填充一些示例数据 for x in range(5): for y in range(5): state = GridWorldState(x, y) for action in ['up', 'down', 'left', 'right']: # 模拟Q值:越接近目标,Q值越高 distance = (4 - x) + (4 - y) base_q = 10 * np.exp(-distance * 0.3) noise = np.random.normal(0, 0.5) q_table.set(state, action, base_q + noise) # 绘制右动作的Q值表面 fig, ax = plot_q_surface(q_table, grid_size=5, action='right') plt.show() 5.2 价值函数等高线图 等高线图是展示价值函数梯度的优秀方式。 def plot_value_contour(v_function, grid_size=5, title="Value Function Contour"): """ 绘制价值函数等高线图 参数: - v_function: 状态价值函数字典 - grid_size: 网格大小 - title: 图表标题 """ fig, ax = plt.subplots(figsize=(10, 8)) # 创建网格数据 X = np.arange(0, grid_size, 1) Y = np.arange(0, grid_size, 1) X, Y = np.meshgrid(X, Y) Z = np.zeros_like(X, dtype=float) for i in range(grid_size): for j in range(grid_size): Z[j, i] = v_function.get((i, j), 0) # 绘制等高线 contour = ax.contourf(X, Y, Z, levels=20, cmap='viridis', alpha=0.8) contour_lines = ax.contour(X, Y, Z, levels=10, colors='black', linewidths=0.5) # 添加标签 ax.clabel(contour_lines, inline=True, fontsize=8, fmt='%.1f') # 标记终端状态 ax.plot(grid_size-1, grid_size-1, 'rs', markersize=15, label='Terminal') # 添加颜色条 fig.colorbar(contour, ax=ax, label='Value') ax.set_title(title, fontsize=16) ax.set_xlabel('X coordinate') ax.set_ylabel('Y coordinate') ax.legend() ax.grid(True, alpha=0.3) return fig, ax # 执行可视化 fig, ax = plot_value_contour(v_function, grid_size=5) plt.show() 6. 实战案例:完整游戏表示论可视化系统 6.1 综合可视化仪表板 将所有可视化整合到一个仪表板中。 def create_game_representation_dashboard(v_function, policy, q_table, monitor, grid_size=5): """ 创建游戏表示论综合可视化仪表板 参数: - v_function: 状态价值函数 - policy: 策略 - q_table: Q值表 - monitor: 训练监控器 - grid_size: 网格大小 """ fig = plt.figure(figsize=(20, 16)) # 创建子图布局 gs = fig.add_gridspec(4, 4, hspace=0.3, wspace=0.3) # 1. 状态价值函数热力图 (左上) ax1 = fig.add_subplot(gs[0, 0]) value_matrix = np.zeros((grid_size, grid_size)) for (x, y), value in v_function.items(): value_matrix[y, x] = value im1 = ax1.imshow(value_matrix, cmap='viridis') ax1.set_title('State Value', fontsize=10) ax1.set_xticks([]) ax1.set_yticks([]) plt.colorbar(im1, ax=ax1, fraction=0.046, pad=0.04) # 2. 策略箭头图 (右上) ax2 = fig.add_subplot(gs[0, 1]) for i in range(grid_size + 1): ax2.axhline(i, color='gray', alpha=0.2) ax2.axvline(i, color='gray', alpha=0.2) action_vectors = {'up': (0, 0.4), 'down': (0, -0.4), 'left': (-0.4, 0), 'right': (0.4, 0)} for state, action_probs in policy.items(): x, y = state best_action = max(action_probs, key=action_probs.get) prob = action_probs[best_action] if prob > 0.3:
dx, dy = action_vectors[best_action]
ax2.annotate(”, xy=(x + dx, y + dy), xytext=(x, y),
arrowprops=dict(arrowstyle=’->’, color=’darkblue’, lw=2))
ax2.set_title(‘Policy Arrows’, fontsize=10)
ax2.set_xticks([])
ax2.set_yticks([])
ax2.set_aspect(‘equal’)
ax2.set_xlim(-0.5, grid_size – 0.5)
ax2.set_ylim(-0.5, grid_size – 0.5)

# 3. Q值分布直方图 (左中)
ax3 = fig.add_subplot(gs[1, 0])
if monitor.q_values:
ax3.hist(monitor.q_values, bins=20, color=’purple’, alpha=0.7, edgecolor=’black’)
ax3.set_title(‘Q-Value Dist’, fontsize=10)
ax3.set_xlabel(‘Q’, fontsize=8)
ax3.set_ylabel(‘Freq’, fontsize=8)
ax3.grid(True, alpha=0.2)

# 4. 训练奖励曲线 (右中)
ax4 = fig.add_subplot(gs[1, 1])
if monitor.episode_rewards:
episodes = monitor.episode_numbers
ax4.plot(episodes, monitor.episode_rewards, alpha=0.4, color=’blue’)
if len(monitor.episode_rewards) >= 50:
moving_avg = np.convolve(monitor.episode_rewards, np.ones(50)/50, mode=’valid’)
ax4.plot(episodes[49:], moving_avg, color=’blue’, linewidth=2)
ax4.set_title(‘Rewards’, fontsize=10)
ax4.set_xlabel(‘Episode’, fontsize=8)
ax4.set_ylabel(‘Reward’, fontsize=8)
ax4.grid(True, alpha=0.2)

# 5. 动作概率热力图 (第二行)
ax5 = fig.add_subplot(gs[2, :2])
prob_matrix = np.zeros((grid_size, grid_size))
for x in range(grid_size):
for y in range(grid_size):
state = (x, y)
if state in policy:
prob_matrix[y, x] = policy[state].get(‘right’, 0) # 显示右动作概率
im5 = ax5.imshow(prob_matrix, cmap=’Blues’, vmin=0, vmax=1)
ax5.set_title(‘P(right|s)’, fontsize=10)
ax5.set_xticks([])
ax5.set_yticks([])
plt.colorbar(im5, ax=ax5, fraction=0.046, pad=0.04)

# 6. 状态转移图 (第二行右)
ax6 = fig.add_subplot(gs[2, 2:])
for i in range(grid_size + 1):
ax6.axhline(i, color=’gray’, alpha=0.2)
ax6.axvline(i, color=’gray’, alpha=0.2)
for x in range(grid_size):
for y in range(grid_size):
ax6.plot(x, y, ‘o’, markersize=5, color=’gray’)
# 简单转移箭头示例
ax6.annotate(”, xy=(1, 1), xytext=(0, 1), arrowprops=dict(arrowstyle=’->’, color=’green’))
ax6.annotate(”, xy=(2, 1), xytext=(1, 1), arrowprops=dict(arrowstyle=’->’, color=’green’))
ax6.set_title(‘State Transitions’, fontsize=10)
ax6.set_xticks([])
ax6.set_yticks([])
ax6.set_aspect(‘equal’)
ax6.set_xlim(-0.5, grid_size – 0.5)
ax6.set_ylim(-0.5, grid_size – 0.5)

# 7. 损失函数曲线 (第三行)
ax7 = fig.add_subplot(gs[3, :])
if monitor.losses:
ax7.plot(monitor.losses, color=’red’, linewidth=1.5)
ax7.set_title(‘Training Loss’, fontsize=12)
ax7.set_xlabel(‘Step’)
ax7.set_ylabel(‘Loss (log scale)’)
ax7.set_yscale(‘log’)
ax7.grid(True, alpha=0.3)

# 主标题
fig.suptitle(‘Game Representation Theory Dashboard’, fontsize=20, y=0.995)

return fig

# 生成完整仪表板
monitor = TrainingMonitor()
simulate_training(monitor, n_episodes=300)
fig = create_game_representation_dashboard(v_function, policy, q_table, monitor, grid_size=5)
plt.show()
7. 最佳实践与优化技巧
7.1 性能优化
对于大规模状态空间,使用以下技巧:
def optimize_visualization_large_state_space(state_values, grid_size=100):
“””
优化大规模状态空间的可视化

技巧:
1. 采样显示:只显示部分状态点
2. 使用rasterized=True加速渲染
3. 降低分辨率
“””
fig, ax = plt.subplots(figsize=(12, 8))

# 采样:每5个点显示1个
sample_rate = 5
sampled_states = []
sampled_values = []

for (x, y), value in state_values.items():
if x % sample_rate == 0 and y % sample_rate == 0:
sampled_states.append((x, y))
sampled_values.append(value)

# 转换为矩阵
max_x = max(s[0] for s in sampled_states) + 1
max_y = max(s[1] for s in sampled_states) + 1
value_matrix = np.zeros((max_y, max_x))

for (x, y), value in zip(sampled_states, sampled_values):
value_matrix[y, x] = value

# 使用rasterized加速
im = ax.imshow(value_matrix, cmap=’viridis’, rasterized=True)

# 添加颜色条
plt.colorbar(im, ax=ax, label=’Value’)

ax.set_title(‘Large State Space Visualization (Sampled)’, fontsize=14)
ax.set_xlabel(‘State X’)
ax.set_ylabel(‘State Y’)

return fig, ax

# 示例:模拟大规模状态空间
large_state_values = {}
for x in range(0, 100, 5):
for y in range(0, 100, 5):
large_state_values[(x, y)] = np.sin(x * 0.1) * np.cos(y * 0.1)

fig, ax = optimize_visualization_large_state_space(large_state_values, grid_size=100)
plt.show()
7.2 交互式可视化
使用Matplotlib的事件处理创建交互式图表。
class InteractiveStateVisualizer:
“””交互式状态可视化器”””
def __init__(self, v_function, policy, grid_size=5):
self.v_function = v_function
self.policy = policy
self.grid_size = grid_size
self.fig, self.ax = plt.subplots(figsize=(10, 8))
self.selected_state = None
self.setup_plot()
self.connect_events()

def setup_plot(self):
“””初始化绘图”””
# 绘制基础网格
for i in range(self.grid_size + 1):
self.ax.axhline(i, color=’gray’, alpha=0.3)
self.ax.axvline(i, color=’gray’, alpha=0.3)

# 绘制状态点
for x in range(self.grid_size):
for y in range(self.grid_size):
self.ax.plot(x, y, ‘o’, markersize=10, color=’lightblue’, picker=True)

# 标记终端状态
self.ax.add_patch(Rectangle((self.grid_size-1, self.grid_size-1), 1, 1,
fill=False, edgecolor=’red’, linewidth=3))

self.ax.set_title(‘Click on a state to see details’, fontsize=14)
self.ax.set_aspect(‘equal’)
self.ax.set_xlim(-1, self.grid_size)
self.ax.set_ylim(-1, self.grid_size)

# 添加信息文本框
self.info_text = self.ax.text(0.02, 0.98, ”, transform=self.ax.transAxes,
fontsize=10, verticalalignment=’top’,
bbox=dict(boxstyle=’round’, facecolor=’wheat’, alpha=0.8))

def connect_events(self):
“””连接事件”””
self.fig.canvas.mpl_connect(‘pick_event’, self.on_pick)

def on_pick(self, event):
“””处理点击事件”””
if event.artist.get_picker() is not False:
# 获取点击的点
ind = event.ind[0]
x, y = event.artist.get_xdata()[ind], event.artist.get_ydata()[ind]
state = (int(x), int(y))

# 更新选中状态
self.selected_state = state

# 获取状态信息
value = self.v_function.get(state, 0)
action_probs = self.policy.get(state, {})

# 构建信息文本
info = f”State: {state}\nValue: {value:.3f}\n\nActions:\n”
for action, prob in action_probs.items():
info += f” {action}: {prob:.3f}\n”

# 更新文本框
self.info_text.set_text(info)

# 高亮选中状态
self.ax.plot(x, y, ‘o’, markersize=15, color=’yellow’, alpha=0.7)

# 重新绘制
self.fig.canvas.draw()

# 使用示例(在Jupyter中运行)
# visualizer = InteractiveStateVisualizer(v_function, policy, grid_size=5)
# plt.show()
8. 总结
本文详细介绍了使用Matplotlib绘制游戏内表示论的多种可视化方法,从基础的状态空间、策略可视化,到高级的3D表面图和交互式仪表板。通过这些可视化技术,开发者可以:
直观理解游戏机制
:通过热力图、箭头图等快速把握状态价值和策略分布
监控训练过程
:实时跟踪学习曲线、损失函数等关键指标
调试和优化
:识别策略中的问题区域或训练中的异常模式
教学和演示
:将抽象的数学概念转化为直观的视觉表示
关键要点
:
使用
imshow
绘制热力图适合离散状态空间
箭头图能清晰展示策略方向
3D表面图适合展示连续或高维Q值函数
动画和交互式图表能提供动态洞察
仪表板整合多种视图,提供全面分析
通过组合这些技术,你可以创建强大的可视化工具,显著提升对游戏表示论的理解和开发效率。
# 使用Matplotlib绘制游戏内表示论的可视化方法与实例解析
引言:游戏内表示论与数据可视化的重要性
在现代游戏开发中,
游戏内表示论(Game Representation Theory)
是一个核心概念,它涉及如何将复杂的游戏状态、玩家行为和系统动态转化为可计算、可分析的数学表示。这种表示通常包括状态空间、动作空间、奖励函数、策略网络等。然而,这些高维、抽象的数据往往难以直观理解。
Matplotlib
作为Python中最强大的数据可视化库之一,能够将这些抽象概念转化为直观的图表,帮助开发者、研究人员和玩家更好地理解游戏机制。
通过可视化,我们可以:
洞察状态转移规律
:观察游戏状态如何随时间演变
分析策略有效性
:比较不同策略的性能差异
调试强化学习模型
:直观展示训练过程中的收敛情况
增强教学演示
:让抽象概念变得具体可感
本文将深入探讨如何使用Matplotlib绘制游戏内表示论的各种可视化方法,并通过完整的代码实例进行详细解析。
1. 基础准备:环境配置与数据结构
1.1 安装与导入
首先,确保你的环境中安装了必要的库:
# 核心库
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.patches import Circle, Rectangle, FancyArrowPatch
import matplotlib.animation as animation

# 游戏环境模拟(我们将创建一个简单的网格世界)
import gym
from collections import defaultdict
import random
1.2 数据结构设计
在游戏表示论中,我们通常需要处理以下数据结构:
# 示例:网格世界游戏的状态表示
class GridWorldState:
def __init__(self, x, y, grid_size=5):
self.x = x
self.y = y
self.grid_size = grid_size

def to_tuple(self):
return (self.x, self.y)

def is_terminal(self):
# 终端状态:右上角
return self.x == self.grid_size – 1 and self.y == self.grid_size – 1

# 示例:Q值表(状态-动作值函数)
class QTable:
def __init__(self, states, actions):
self.q_table = defaultdict(lambda: {a: 0.0 for a in actions})

def get(self, state, action):
return self.q_table[state.to_tuple()][action]

def set(self, state, action, value):
self.q_table[state.to_tuple()][action] = value
2. 状态空间可视化
2.1 网格世界状态图
状态空间是游戏表示论的基础。对于离散状态(如网格世界),我们可以用热力图表示状态价值函数 V(s)。
完整实例:绘制状态价值函数热力图
def visualize_state_value_function(v_function, grid_size=5, title=”State Value Function”):
“””
可视化状态价值函数 V(s)

参数:
– v_function: 字典,键为状态元组 (x,y),值为价值
– grid_size: 网格大小
– title: 图表标题
“””
# 创建价值矩阵
value_matrix = np.zeros((grid_size, grid_size))
for state, value in v_function.items():
x, y = state
value_matrix[y, x] = value # 注意:y轴向下

# 创建图形
fig, ax = plt.subplots(figsize=(10, 8))

# 使用imshow绘制热力图
im = ax.imshow(value_matrix, cmap=’viridis’, interpolation=’nearest’)

# 添加数值标签
for i in range(grid_size):
for j in range(grid_size):
text = ax.text(j, i, f'{value_matrix[i, j]:.2f}’,
ha=”center”, va=”center”, color=”w”, fontsize=12)

# 设置网格线
ax.set_xticks(np.arange(grid_size))
ax.set_yticks(np.arange(grid_size))
ax.set_xticklabels([f’x={i}’ for i in range(grid_size)])
ax.set_yticklabels([f’y={i}’ for i in range(grid_size)])

# 添加标题和颜色条
ax.set_title(title, fontsize=16, pad=20)
plt.colorbar(im, ax=ax, label=’Value’)

# 标记终端状态
ax.add_patch(Rectangle((grid_size-1, grid_size-1), 1, 1,
fill=False, edgecolor=’red’, linewidth=3))
ax.text(grid_size-1, grid_size-1, ‘Terminal’,
ha=”center”, va=”center”, color=”red”, fontsize=10, weight=’bold’)

plt.tight_layout()
return fig, ax

# 示例数据:随机生成的状态价值函数(模拟训练结果)
def generate_sample_v_function(grid_size=5):
“””生成示例状态价值函数”””
v_func = {}
for x in range(grid_size):
for y in range(grid_size):
# 模拟价值:越接近右上角价值越高
distance = (grid_size – 1 – x) + (grid_size – 1 – y)
value = 10 * np.exp(-distance * 0.3) + np.random.normal(0, 0.1)
v_func[(x, y)] = value
return v_func

# 执行可视化
v_function = generate_sample_v_function()
fig, ax = visualize_state_value_function(v_function, grid_size=5)
plt.show()
2.2 状态转移概率可视化
在游戏表示论中,状态转移概率 P(s’|s,a) 是核心。我们可以用箭头图表示。
def visualize_state_transitions(transition_prob, grid_size=5):
“””
可视化状态转移概率

参数:
– transition_prob: 字典,键为 (state, action),值为 {next_state: probability}
– grid_size: 网格大小
“””
fig, ax = plt.subplots(figsize=(10, 10))

# 绘制网格
for i in range(grid_size + 1):
ax.axhline(i, color=’gray’, alpha=0.3)
ax.axvline(i, color=’gray’, alpha=0.3)

# 绘制状态点
for x in range(grid_size):
for y in range(grid_size):
ax.plot(x, y, ‘o’, markersize=10, color=’blue’)
if x == grid_size – 1 and y == grid_size – 1:
ax.plot(x, y, ‘s’, markersize=15, color=’red’, label=’Terminal’)

# 绘制转移箭头
arrow_colors = {‘up’: ‘green’, ‘down’: ‘red’, ‘left’: ‘orange’, ‘right’: ‘purple’}
action_offsets = {
‘up’: (0, 0.3), ‘down’: (0, -0.3),
‘left’: (-0.3, 0), ‘right’: (0.3, 0)
}

for (state, action), next_states in transition_prob.items():
x, y = state
for next_state, prob in next_states.items():
nx, ny = next_state
# 只绘制高概率转移
if prob > 0.1:
# 计算箭头位置(偏移避免重叠)
offset = action_offsets[action]
start_x = x + offset[0] * 0.5
start_y = y + offset[1] * 0.5
end_x = nx + offset[0] * 0.5
end_y = ny + offset[1] * 0.5

# 绘制箭头
ax.annotate(”, xy=(end_x, end_y), xytext=(start_x, start_y),
arrowprops=dict(arrowstyle=’->’,
color=arrow_colors[action],
lw=prob * 5, # 线宽与概率成正比
alpha=0.7))

# 添加图例
from matplotlib.lines import Line2D
legend_elements = [
Line2D([0], [0], marker=’o’, color=’w’, markerfacecolor=’blue’, markersize=10, label=’State’),
Line2D([0], [0], marker=’s’, color=’w’, markerfacecolor=’red’, markersize=10, label=’Terminal’),
Line2D([0], [0], color=’green’, lw=2, label=’Up’),
Line2D([0], [0], color=’red’, lw=2, label=’Down’),
Line2D([0], [0], color=’orange’, lw=2, label=’Left’),
Line2D([0], [0], color=’purple’, lw=2, label=’Right’)
]
ax.legend(handles=legend_elements, loc=’upper right’)

ax.set_title(‘State Transition Probabilities’, fontsize=16)
ax.set_aspect(‘equal’)
ax.set_xlim(-1, grid_size)
ax.set_ylim(-1, grid_size)

return fig, ax

# 示例:创建转移概率数据
def generate_transition_probabilities(grid_size=5):
“””生成示例状态转移概率”””
transitions = {}
actions = [‘up’, ‘down’, ‘left’, ‘right’]

for x in range(grid_size):
for y in range(grid_size):
state = (x, y)
for action in actions:
next_states = {}
# 确定性转移(简化)
if action == ‘up’:
ny = max(0, y – 1)
next_states[(x, ny)] = 0.8
next_states[(x, y)] = 0.2 # 滑移
elif action == ‘down’:
ny = min(grid_size – 1, y + 1)
next_states[(x, ny)] = 0.8
next_states[(x, y)] = 0.2
elif action == ‘left’:
nx = max(0, x – 1)
next_states[(nx, y)] = 0.8
next_states[(x, y)] = 0.2
elif action == ‘right’:
nx = min(grid_size – 1, x + 1)
next_states[(nx, y)] = 0.8
next_states[(x, y)] = 0.2

transitions[(state, action)] = next_states

return transitions

# 执行可视化
transitions = generate_transition_probabilities()
fig, ax = visualize_state_transitions(transitions, grid_size=5)
plt.show()
3. 策略与动作空间可视化
3.1 策略热力图
策略 π(a|s) 表示在给定状态下选择每个动作的概率。我们可以用分组热力图表示。
def visualize_policy_heatmap(policy, grid_size=5, action_names=None):
“””
可视化策略 π(a|s) 作为热力图

参数:
– policy: 字典,键为状态,值为动作概率分布 {action: prob}
– grid_size: 网格大小
– action_names: 动作名称列表
“””
if action_names is None:
action_names = [‘up’, ‘down’, ‘left’, ‘right’]

# 创建子图网格
n_actions = len(action_names)
fig, axes = plt.subplots(1, n_actions, figsize=(4 * n_actions, 8))
if n_actions == 1:
axes = [axes]

# 为每个动作创建一个热力图
for idx, action in enumerate(action_names):
prob_matrix = np.zeros((grid_size, grid_size))

for x in range(grid_size):
for y in range(grid_size):
state = (x, y)
if state in policy:
prob_matrix[y, x] = policy[state].get(action, 0)

im = axes[idx].imshow(prob_matrix, cmap=’Blues’, vmin=0, vmax=1)

# 添加数值标签
for i in range(grid_size):
for j in range(grid_size):
axes[idx].text(j, i, f'{prob_matrix[i, j]:.2f}’,
ha=”center”, va=”center”, color=”black”, fontsize=8)

axes[idx].set_title(f’Action: {action}’, fontsize=12)
axes[idx].set_xticks(np.arange(grid_size))
axes[idx].set_yticks(np.arange(grid_size))

# 添加颜色条
plt.colorbar(im, ax=axes[idx], fraction=0.046, pad=0.04)

plt.suptitle(‘Policy Heatmap per Action’, fontsize=16, y=1.02)
plt.tight_layout()
return fig, axes

# 示例:生成随机策略
def generate_random_policy(grid_size=5):
“””生成示例策略”””
policy = {}
actions = [‘up’, ‘down’, ‘left’, ‘right’]

for x in range(grid_size):
for y in range(grid_size):
state = (x, y)
# 靠近目标时偏向右和上
if x < grid_size - 1 and y < grid_size - 1: probs = [0.2, 0.2, 0.2, 0.4] # 右和上概率稍高 else: probs = [0.25, 0.25, 0.25, 0.25] policy[state] = {action: prob for action, prob in zip(actions, probs)} return policy # 执行可视化 policy = generate_random_policy() fig, axes = visualize_policy_heatmap(policy, grid_size=5) plt.show() 3.2 策略箭头图 另一种直观表示策略的方式是用箭头表示最可能的动作。 def visualize_policy_arrows(policy, grid_size=5, title="Policy Arrows"): """ 用箭头可视化策略 参数: - policy: 字典,键为状态,值为动作概率分布 - grid_size: 网格大小 - title: 图表标题 """ fig, ax = plt.subplots(figsize=(10, 10)) # 绘制网格 for i in range(grid_size + 1): ax.axhline(i, color='gray', alpha=0.3) ax.axvline(i, color='gray', alpha=0.3) # 绘制状态点 for x in range(grid_size): for y in range(grid_size): ax.plot(x, y, 'o', markersize=8, color='lightblue') # 绘制箭头 action_offsets = { 'up': (0, 0.3), 'down': (0, -0.3), 'left': (-0.3, 0), 'right': (0.3, 0) } action_vectors = { 'up': (0, 0.4), 'down': (0, -0.4), 'left': (-0.4, 0), 'right': (0.4, 0) } for state, action_probs in policy.items(): x, y = state # 找到最大概率动作 best_action = max(action_probs, key=action_probs.get) prob = action_probs[best_action] # 只绘制概率足够高的动作 if prob > 0.3:
dx, dy = action_vectors[best_action]
offset = action_offsets[best_action]

# 绘制箭头
ax.annotate(”, xy=(x + dx, y + dy), xytext=(x + offset[0], y + offset[1]),
arrowprops=dict(arrowstyle=’->’,
color=’darkblue’,
lw=2 + prob * 3,
alpha=0.8))

# 添加概率文本
ax.text(x, y, f'{prob:.2f}’, ha=”center”, va=”center”,
fontsize=9, color=’darkred’, weight=’bold’)

# 标记终端状态
ax.add_patch(Rectangle((grid_size-1, grid_size-1), 1, 1,
fill=False, edgecolor=’red’, linewidth=3))
ax.text(grid_size-1, grid_size-1, ‘Terminal’,
ha=”center”, va=”center”, color=”red”, fontsize=10, weight=’bold’)

ax.set_title(title, fontsize=16)
ax.set_aspect(‘equal’)
ax.set_xlim(-1, grid_size)
ax.set_ylim(-1, grid_size)
ax.set_xlabel(‘X coordinate’)
ax.set_ylabel(‘Y coordinate’)

return fig, ax

# 执行可视化
fig, ax = visualize_policy_arrows(policy, grid_size=5)
plt.show()
4. 训练过程可视化
4.1 学习曲线
在强化学习中,监控训练过程至关重要。我们可以绘制累积奖励、损失函数等。
class TrainingMonitor:
“””训练监控器,记录训练指标”””
def __init__(self):
self.episode_rewards = []
self.episode_lengths = []
self.losses = []
self.q_values = []
self.episode_numbers = []

def add_episode(self, episode_num, reward, length):
self.episode_numbers.append(episode_num)
self.episode_rewards.append(reward)
self.episode_lengths.append(length)

def add_loss(self, loss):
self.losses.append(loss)

def add_q_value(self, q_value):
self.q_values.append(q_value)

def plot_training_curves(monitor, window=100):
“””
绘制训练曲线

参数:
– monitor: TrainingMonitor对象
– window: 滑动平均窗口大小
“””
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
fig.suptitle(‘Training Metrics’, fontsize=16)

# 1. 累积奖励
if monitor.episode_rewards:
ax = axes[0, 0]
episodes = monitor.episode_numbers

# 原始奖励
ax.plot(episodes, monitor.episode_rewards, alpha=0.3, color=’blue’, label=’Raw’)

# 滑动平均
if len(monitor.episode_rewards) >= window:
moving_avg = np.convolve(monitor.episode_rewards,
np.ones(window)/window, mode=’valid’)
ax.plot(episodes[window-1:], moving_avg, color=’blue’, linewidth=2,
label=f’Moving Avg ({window})’)

ax.set_xlabel(‘Episode’)
ax.set_ylabel(‘Cumulative Reward’)
ax.set_title(‘Episode Rewards’)
ax.legend()
ax.grid(True, alpha=0.3)

# 2. Episode长度
if monitor.episode_lengths:
ax = axes[0, 1]
ax.plot(monitor.episode_numbers, monitor.episode_lengths,
color=’green’, alpha=0.7)
ax.set_xlabel(‘Episode’)
ax.set_ylabel(‘Length’)
ax.set_title(‘Episode Length’)
ax.grid(True, alpha=0.3)

# 3. 损失函数
if monitor.losses:
ax = axes[1, 0]
ax.plot(monitor.losses, color=’red’, alpha=0.7)
ax.set_xlabel(‘Step’)
ax.set_ylabel(‘Loss’)
ax.set_title(‘Training Loss’)
ax.set_yscale(‘log’) # 对数尺度
ax.grid(True, alpha=0.3)

# 4. Q值分布
if monitor.q_values:
ax = axes[1, 1]
# 绘制Q值的直方图
ax.hist(monitor.q_values, bins=30, color=’purple’, alpha=0.7, edgecolor=’black’)
ax.set_xlabel(‘Q-Value’)
ax.set_ylabel(‘Frequency’)
ax.set_title(‘Q-Value Distribution’)
ax.grid(True, alpha=0.3)

plt.tight_layout()
return fig, axes

# 模拟训练过程
def simulate_training(monitor, n_episodes=500):
“””模拟训练过程并记录指标”””
for episode in range(n_episodes):
# 模拟累积奖励(收敛趋势)
base_reward = 100 * (1 – np.exp(-episode / 100))
noise = np.random.normal(0, 10)
reward = max(0, base_reward + noise)

# 模拟episode长度(逐渐减少)
length = max(10, int(200 – episode * 0.3) + np.random.randint(-5, 5))

monitor.add_episode(episode, reward, length)

# 模拟损失(波动下降)
if episode % 10 == 0:
loss = 10 * np.exp(-episode / 50) * (1 + 0.1 * np.random.randn())
monitor.add_loss(loss)

# 模拟Q值(逐渐增加)
if episode % 5 == 0:
q_value = 50 * (1 – np.exp(-episode / 80)) + np.random.normal(0, 2)
monitor.add_q_value(q_value)

# 执行可视化
monitor = TrainingMonitor()
simulate_training(monitor, n_episodes=500)
fig, axes = plot_training_curves(monitor, window=50)
plt.show()
4.2 动态策略演化动画
使用Matplotlib的动画功能展示策略如何随训练演化。
def create_policy_animation(policies, grid_size=5, interval=200):
“””
创建策略演化动画

参数:
– policies: 列表,每个元素是某次训练迭代的策略
– grid_size: 网格大小
– interval: 帧间隔(毫秒)
“””
fig, ax = plt.subplots(figsize=(10, 10))

# 初始化
def init():
ax.clear()
# 绘制网格
for i in range(grid_size + 1):
ax.axhline(i, color=’gray’, alpha=0.3)
ax.axvline(i, color=’gray’, alpha=0.3)
# 绘制状态点
for x in range(grid_size):
for y in range(grid_size):
ax.plot(x, y, ‘o’, markersize=8, color=’lightblue’)
# 标记终端
ax.add_patch(Rectangle((grid_size-1, grid_size-1), 1, 1,
fill=False, edgecolor=’red’, linewidth=3))
return []

# 动画更新函数
def update(frame):
ax.clear()
policy = policies[frame]

# 重新绘制基础元素
for i in range(grid_size + 1):
ax.axhline(i, color=’gray’, alpha=0.3)
ax.axvline(i, color=’gray’, alpha=0.3)
for x in range(grid_size):
for y in range(grid_size):
ax.plot(x, y, ‘o’, markersize=8, color=’lightblue’)
ax.add_patch(Rectangle((grid_size-1, grid_size-1), 1, 1,
fill=False, edgecolor=’red’, linewidth=3))

# 绘制当前策略箭头
action_vectors = {
‘up’: (0, 0.4), ‘down’: (0, -0.4),
‘left’: (-0.4, 0), ‘right’: (0.4, 0)
}

for state, action_probs in policy.items():
x, y = state
best_action = max(action_probs, key=action_probs.get)
prob = action_probs[best_action]

if prob > 0.3:
dx, dy = action_vectors[best_action]
ax.annotate(”, xy=(x + dx, y + dy), xytext=(x, y),
arrowprops=dict(arrowstyle=’->’,
color=’darkblue’,
lw=2 + prob * 3,
alpha=0.8))

ax.set_title(f’Policy Evolution – Iteration {frame + 1}’, fontsize=16)
ax.set_aspect(‘equal’)
ax.set_xlim(-1, grid_size)
ax.set_ylim(-1, grid_size)
return []

# 创建动画
anim = animation.FuncAnimation(fig, update, frames=len(policies),
init_func=init, interval=interval, blit=False)

return anim

# 生成策略演化序列
def generate_policy_evolution(grid_size=5, n_iterations=10):
“””生成策略演化序列”””
policies = []
actions = [‘up’, ‘down’, ‘left’, ‘right’]

for iteration in range(n_iterations):
policy = {}
progress = iteration / (n_iterations – 1)

for x in range(grid_size):
for y in range(grid_size):
state = (x, y)
# 随着迭代,策略逐渐收敛到最优(右上)
if x < grid_size - 1 and y < grid_size - 1: # 偏向右和上,且随迭代增强 right_prob = 0.2 + 0.6 * progress up_prob = 0.2 + 0.2 * progress left_prob = 0.2 * (1 - progress) down_prob = 0.2 * (1 - progress) probs = [up_prob, down_prob, left_prob, right_prob] else: probs = [0.25, 0.25, 0.25, 0.25] policy[state] = {action: prob for action, prob in zip(actions, probs)} policies.append(policy) return policies # 创建并显示动画(注意:在Jupyter中需要特定设置才能显示动画) policies = generate_policy_evolution(grid_size=5, n_iterations=15) anim = create_policy_animation(policies, grid_size=5, interval=300) # 保存为GIF(需要pillow库) # anim.save('policy_evolution.gif', writer='pillow', fps=3) # 在Jupyter中显示 from IPython.display import HTML HTML(anim.to_jshtml()) 5. 高级可视化:Q值与价值函数 5.1 Q值表面图 对于连续或高维状态空间,我们可以用3D表面图表示Q值函数。 def plot_q_surface(q_table, grid_size=5, action='right'): """ 绘制Q值表面图(3D) 参数: - q_table: Q值表对象 - grid_size: 网格大小 - action: 要绘制的动作 """ fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(111, projection='3d') # 创建网格 X = np.arange(0, grid_size, 1) Y = np.arange(0, grid_size, 1) X, Y = np.meshgrid(X, Y) Z = np.zeros_like(X, dtype=float) # 填充Q值 for i in range(grid_size): for j in range(grid_size): state = (i, j) Z[j, i] = q_table.get(GridWorldState(i, j), action) # 绘制表面 surf = ax.plot_surface(X, Y, Z, cmap=cm.viridis, linewidth=0, antialiased=True, alpha=0.8) # 添加等高线 ax.contour(X, Y, Z, zdir='z', offset=Z.min() - 1, cmap=cm.viridis, alpha=0.5) # 设置标签 ax.set_xlabel('X coordinate') ax.set_ylabel('Y coordinate') ax.set_zlabel(f'Q-value for {action}') ax.set_title(f'Q-Value Surface: {action}', fontsize=16) # 添加颜色条 fig.colorbar(surf, ax=ax, shrink=0.5, aspect=5, label='Q-Value') # 调整视角 ax.view_init(elev=30, azim=45) return fig, ax # 示例:创建Q值表并绘制 q_table = QTable(states=[], actions=['up', 'down', 'left', 'right']) # 填充一些示例数据 for x in range(5): for y in range(5): state = GridWorldState(x, y) for action in ['up', 'down', 'left', 'right']: # 模拟Q值:越接近目标,Q值越高 distance = (4 - x) + (4 - y) base_q = 10 * np.exp(-distance * 0.3) noise = np.random.normal(0, 0.5) q_table.set(state, action, base_q + noise) # 绘制右动作的Q值表面 fig, ax = plot_q_surface(q_table, grid_size=5, action='right') plt.show() 5.2 价值函数等高线图 等高线图是展示价值函数梯度的优秀方式。 def plot_value_contour(v_function, grid_size=5, title="Value Function Contour"): """ 绘制价值函数等高线图 参数: - v_function: 状态价值函数字典 - grid_size: 网格大小 - title: 图表标题 """ fig, ax = plt.subplots(figsize=(10, 8)) # 创建网格数据 X = np.arange(0, grid_size, 1) Y = np.arange(0, grid_size, 1) X, Y = np.meshgrid(X, Y) Z = np.zeros_like(X, dtype=float) for i in range(grid_size): for j in range(grid_size): Z[j, i] = v_function.get((i, j), 0) # 绘制等高线 contour = ax.contourf(X, Y, Z, levels=20, cmap='viridis', alpha=0.8) contour_lines = ax.contour(X, Y, Z, levels=10, colors='black', linewidths=0.5) # 添加标签 ax.clabel(contour_lines, inline=True, fontsize=8, fmt='%.1f') # 标记终端状态 ax.plot(grid_size-1, grid_size-1, 'rs', markersize=15, label='Terminal') # 添加颜色条 fig.colorbar(contour, ax=ax, label='Value') ax.set_title(title, fontsize=16) ax.set_xlabel('X coordinate') ax.set_ylabel('Y coordinate') ax.legend() ax.grid(True, alpha=0.3) return fig, ax # 执行可视化 fig, ax = plot_value_contour(v_function, grid_size=5) plt.show() 6. 实战案例:完整游戏表示论可视化系统 6.1 综合可视化仪表板 将所有可视化整合到一个仪表板中。 def create_game_representation_dashboard(v_function, policy, q_table, monitor, grid_size=5): """ 创建游戏表示论综合可视化仪表板 参数: - v_function: 状态价值函数 - policy: 策略 - q_table: Q值表 - monitor: 训练监控器 - grid_size: 网格大小 """ fig = plt.figure(figsize=(20, 16)) # 创建子图布局 gs = fig.add_gridspec(4, 4, hspace=0.3, wspace=0.3) # 1. 状态价值函数热力图 (左上) ax1 = fig.add_subplot(gs[0, 0]) value_matrix = np.zeros((grid_size, grid_size)) for (x, y), value in v_function.items(): value_matrix[y, x] = value im1 = ax1.imshow(value_matrix, cmap='viridis') ax1.set_title('State Value', fontsize=10) ax1.set_xticks([]) ax1.set_yticks([]) plt.colorbar(im1, ax=ax1, fraction=0.046, pad=0.04) # 2. 策略箭头图 (右上) ax2 = fig.add_subplot(gs[0, 1]) for i in range(grid_size + 1): ax2.axhline(i, color='gray', alpha=0.2) ax2.axvline(i, color='gray', alpha=0.2) action_vectors = {'up': (0, 0.4), 'down': (0, -0.4), 'left': (-0.4, 0), 'right': (0.4, 0)} for state, action_probs in policy.items(): x, y = state best_action = max(action_probs, key=action_probs.get) prob = action_probs[best_action] if prob > 0.3:
dx, dy = action_vectors[best_action]
ax2.annotate(”, xy=(x + dx, y + dy), xytext=(x, y),
arrowprops=dict(arrowstyle=’->’, color=’darkblue’, lw=2))
ax2.set_title(‘Policy Arrows’, fontsize=10)
ax2.set_xticks([])
ax2.set_yticks([])
ax2.set_aspect(‘equal’)
ax2.set_xlim(-0.5, grid_size – 0.5)
ax2.set_ylim(-0.5, grid_size – 0.5)

# 3. Q值分布直方图 (左中)
ax3 = fig.add_subplot(gs[1, 0])
if monitor.q_values:
ax3.hist(monitor.q_values, bins=20, color=’purple’, alpha=0.7, edgecolor=’black’)
ax3.set_title(‘Q-Value Dist’, fontsize=10)
ax3.set_xlabel(‘Q’, fontsize=8)
ax3.set_ylabel(‘Freq’, fontsize=8)
ax3.grid(True, alpha=0.2)

# 4. 训练奖励曲线 (右中)
ax4 = fig.add_subplot(gs[1, 1])
if monitor.episode_rewards:
episodes = monitor.episode_numbers
ax4.plot(episodes, monitor.episode_rewards, alpha=0.4, color=’blue’)
if len(monitor.episode_rewards) >= 50:
moving_avg = np.convolve(monitor.episode_rewards, np.ones(50)/50, mode=’valid’)
ax4.plot(episodes[49:], moving_avg, color=’blue’, linewidth=2)
ax4.set_title(‘Rewards’, fontsize=10)
ax4.set_xlabel(‘Episode’, fontsize=8)
ax4.set_ylabel(‘Reward’, fontsize=8)
ax4.grid(True, alpha=0.2)

# 5. 动作概率热力图 (第二行)
ax5 = fig.add_subplot(gs[2, :2])
prob_matrix = np.zeros((grid_size, grid_size))
for x in range(grid_size):
for y in range(grid_size):
state = (x, y)
if state in policy:
prob_matrix[y, x] = policy[state].get(‘right’, 0) # 显示右动作概率
im5 = ax5.imshow(prob_matrix, cmap=’Blues’, vmin=0, vmax=1)
ax5.set_title(‘P(right|s)’, fontsize=10)
ax5.set_xticks([])
ax5.set_yticks([])
plt.colorbar(im5, ax=ax5, fraction=0.046, pad=0.04)

# 6. 状态转移图 (第二行右)
ax6 = fig.add_subplot(gs[2, 2:])
for i in range(grid_size + 1):
ax6.axhline(i, color=’gray’, alpha=0.2)
ax6.axvline(i, color=’gray’, alpha=0.2)
for x in range(grid_size):
for y in range(grid_size):
ax6.plot(x, y, ‘o’, markersize=5, color=’gray’)
# 简单转移箭头示例
ax6.annotate(”, xy=(1, 1), xytext=(0, 1), arrowprops=dict(arrowstyle=’->’, color=’green’))
ax6.annotate(”, xy=(2, 1), xytext=(1, 1), arrowprops=dict(arrowstyle=’->’, color=’green’))
ax6.set_title(‘State Transitions’, fontsize=10)
ax6.set_xticks([])
ax6.set_yticks([])
ax6.set_aspect(‘equal’)
ax6.set_xlim(-0.5, grid_size – 0.5)
ax6.set_ylim(-0.5, grid_size – 0.5)

# 7. 损失函数曲线 (第三行)
ax7 = fig.add_subplot(gs[3, :])
if monitor.losses:
ax7.plot(monitor.losses, color=’red’, linewidth=1.5)
ax7.set_title(‘Training Loss’, fontsize=12)
ax7.set_xlabel(‘Step’)
ax7.set_ylabel(‘Loss (log scale)’)
ax7.set_yscale(‘log’)
ax7.grid(True, alpha=0.3)

# 主标题
fig.suptitle(‘Game Representation Theory Dashboard’, fontsize=20, y=0.995)

return fig

# 生成完整仪表板
monitor = TrainingMonitor()
simulate_training(monitor, n_episodes=300)
fig = create_game_representation_dashboard(v_function, policy, q_table, monitor, grid_size=5)
plt.show()
7. 最佳实践与优化技巧
7.1 性能优化
对于大规模状态空间,使用以下技巧:
def optimize_visualization_large_state_space(state_values, grid_size=100):
“””
优化大规模状态空间的可视化

技巧:
1. 采样显示:只显示部分状态点
2. 使用rasterized=True加速渲染
3. 降低分辨率
“””
fig, ax = plt.subplots(figsize=(12, 8))

# 采样:每5个点显示1个
sample_rate = 5
sampled_states = []
sampled_values = []

for (x, y), value in state_values.items():
if x % sample_rate == 0 and y % sample_rate == 0:
sampled_states.append((x, y))
sampled_values.append(value)

# 转换为矩阵
max_x = max(s[0] for s in sampled_states) + 1
max_y = max(s[1] for s in sampled_states) + 1
value_matrix = np.zeros((max_y, max_x))

for (x, y), value in zip(sampled_states, sampled_values):
value_matrix[y, x] = value

# 使用rasterized加速
im = ax.imshow(value_matrix, cmap=’viridis’, rasterized=True)

# 添加颜色条
plt.colorbar(im, ax=ax, label=’Value’)

ax.set_title(‘Large State Space Visualization (Sampled)’, fontsize=14)
ax.set_xlabel(‘State X’)
ax.set_ylabel(‘State Y’)

return fig, ax

# 示例:模拟大规模状态空间
large_state_values = {}
for x in range(0, 100, 5):
for y in range(0, 100, 5):
large_state_values[(x, y)] = np.sin(x * 0.1) * np.cos(y * 0.1)

fig, ax = optimize_visualization_large_state_space(large_state_values, grid_size=100)
plt.show()
7.2 交互式可视化
使用Matplotlib的事件处理创建交互式图表。
class InteractiveStateVisualizer:
“””交互式状态可视化器”””
def __init__(self, v_function, policy, grid_size=5):
self.v_function = v_function
self.policy = policy
self.grid_size = grid_size
self.fig, self.ax = plt.subplots(figsize=(10, 8))
self.selected_state = None
self.setup_plot()
self.connect_events()

def setup_plot(self):
“””初始化绘图”””
# 绘制基础网格
for i in range(self.grid_size + 1):
self.ax.axhline(i, color=’gray’, alpha=0.3)
self.ax.axvline(i, color=’gray’, alpha=0.3)

# 绘制状态点
for x in range(self.grid_size):
for y in range(self.grid_size):
self.ax.plot(x, y, ‘o’, markersize=10, color=’lightblue’, picker=True)

# 标记终端状态
self.ax.add_patch(Rectangle((self.grid_size-1, self.grid_size-1), 1, 1,
fill=False, edgecolor=’red’, linewidth=3))

self.ax.set_title(‘Click on a state to see details’, fontsize=14)
self.ax.set_aspect(‘equal’)
self.ax.set_xlim(-1, self.grid_size)
self.ax.set_ylim(-1, self.grid_size)

# 添加信息文本框
self.info_text = self.ax.text(0.02, 0.98, ”, transform=self.ax.transAxes,
fontsize=10, verticalalignment=’top’,
bbox=dict(boxstyle=’round’, facecolor=’wheat’, alpha=0.8))

def connect_events(self):
“””连接事件”””
self.fig.canvas.mpl_connect(‘pick_event’, self.on_pick)

def on_pick(self, event):
“””处理点击事件”””
if event.artist.get_picker() is not False:
# 获取点击的点
ind = event.ind[0]
x, y = event.artist.get_xdata()[ind], event.artist.get_ydata()[ind]
state = (int(x), int(y))

# 更新选中状态
self.selected_state = state

# 获取状态信息
value = self.v_function.get(state, 0)
action_probs = self.policy.get(state, {})

# 构建信息文本
info = f”State: {state}\nValue: {value:.3f}\n\nActions:\n”
for action, prob in action_probs.items():
info += f” {action}: {prob:.3f}\n”

# 更新文本框
self.info_text.set_text(info)

# 高亮选中状态
self.ax.plot(x, y, ‘o’, markersize=15, color=’yellow’, alpha=0.7)

# 重新绘制
self.fig.canvas.draw()

# 使用示例(在Jupyter中运行)
# visualizer = InteractiveStateVisualizer(v_function, policy, grid_size=5)
# plt.show()
8. 总结
本文详细介绍了使用Matplotlib绘制游戏内表示论的多种可视化方法,从基础的状态空间、策略可视化,到高级的3D表面图和交互式仪表板。通过这些可视化技术,开发者可以:
直观理解游戏机制
:通过热力图、箭头图等快速把握状态价值和策略分布
监控训练过程
:实时跟踪学习曲线、损失函数等关键指标
调试和优化
:识别策略中的问题区域或训练中的异常模式
教学和演示
:将抽象的数学概念转化为直观的视觉表示
关键要点
:
使用
imshow
绘制热力图适合离散状态空间
箭头图能清晰展示策略方向
3D表面图适合展示连续或高维Q值函数
动画和交互式图表能提供动态洞察
仪表板整合多种视图,提供全面分析
通过组合这些技术,你可以创建强大的可视化工具,显著提升对游戏表示论的理解和开发效率。