AnonymousAuthorEE33's picture
reinforcement_learning: replace with unified-shape pools (6 cells x 100 checkpoints), full registry, configs, prompts
7d3c387
Raw History Blame Contribute Delete
1.83 kB
"""把观测维补齐到 RL_OBS_DIM、动作空间声明成 RL_N_ACT。
不设这两个环境变量时什么都不做, 所以对现有脚本零影响。
目的: 让 Acrobot(obs6/act3) 和 LunarLander(obs8/act4) 训出逐字节同形的网络。"""
import os
_OBS = os.environ.get("RL_OBS_DIM"); _ACT = os.environ.get("RL_N_ACT")
if _OBS and _ACT:
_OBS, _ACT = int(_OBS), int(_ACT)
import numpy as np, gymnasium as gym
class _Unify(gym.Wrapper):
def __init__(self, env):
super().__init__(env)
self.n_valid = int(env.action_space.n)
sp = env.observation_space
self._pad = _OBS - int(sp.shape[0])
assert self._pad >= 0, f"RL_OBS_DIM={_OBS} 小于真实观测维 {sp.shape[0]}"
z = np.zeros(self._pad, dtype=np.float32)
self.observation_space = gym.spaces.Box(
low=np.concatenate([sp.low.astype(np.float32), z - np.inf if False else z]),
high=np.concatenate([sp.high.astype(np.float32), z]),
dtype=np.float32)
self.action_space = gym.spaces.Discrete(_ACT)
def _o(self, o):
return np.concatenate([np.asarray(o, dtype=np.float32),
np.zeros(self._pad, dtype=np.float32)])
def reset(self, **kw):
o, i = self.env.reset(**kw); return self._o(o), i
def step(self, a):
a = int(a)
if a >= self.n_valid: # 掩码生效时不该发生; 留个安全网并计数
a = self.n_valid - 1
_Unify.n_clipped += 1
o, r, te, tr, i = self.env.step(a); return self._o(o), r, te, tr, i
_Unify.n_clipped = 0
_orig = gym.make
def _make(env_id, *a, **kw):
return _Unify(_orig(env_id, *a, **kw))
gym.make = _make