-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualizer.py
More file actions
69 lines (55 loc) · 2.12 KB
/
Copy pathvisualizer.py
File metadata and controls
69 lines (55 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import matplotlib.pyplot as plt
import numpy as np
from pathlib import Path
class RLVisualizer:
def __init__(self, title):
self.rewards = []
self.avg_rewards = []
self.q_values = []
self.avg_q_values = []
self.fig, self.ax = plt.subplots(figsize=(10, 5))
self.ax_q = None
self.title = title
plt.ion()
def add_data(self, reward, avg_q=None):
"""添加新数据并计算滑动平均"""
self.rewards.append(reward)
window = min(len(self.rewards), 50)
self.avg_rewards.append(float(np.mean(self.rewards[-window:])))
self.q_values.append(np.nan if avg_q is None else float(avg_q))
recent_q = np.array(self.q_values[-window:], dtype=float)
self.avg_q_values.append(float(np.nanmean(recent_q)) if np.isfinite(recent_q).any() else np.nan)
def draw(self):
"""刷新画布"""
self.ax.clear()
self.ax.scatter(
range(len(self.rewards)),
self.rewards,
color="blue",
alpha=0.3,
s=12,
label="Episode Reward",
)
self.ax.plot(self.avg_rewards, color="red", linewidth=2, label="Reward MA (50)")
self.ax.set_title(self.title)
self.ax.set_xlabel("Episode")
self.ax.set_ylabel("Reward")
self.ax.grid(True, linestyle="--", alpha=0.6)
handles, labels = self.ax.get_legend_handles_labels()
if np.isfinite(np.array(self.q_values, dtype=float)).any():
if self.ax_q is None:
self.ax_q = self.ax.twinx()
self.ax_q.clear()
self.ax_q.plot(self.avg_q_values, color="green", linewidth=2, label="Avg Q MA (50)")
self.ax_q.set_ylabel("Q")
h2, l2 = self.ax_q.get_legend_handles_labels()
handles += h2
labels += l2
self.ax.legend(handles, labels, loc="best")
plt.pause(0.01)
def save(self, filename):
"""保存最终图像"""
plt.ioff()
filepath = Path("outputs") / filename
self.fig.savefig(filepath)
print(f"图表已保存至: {filepath}")