当然如果你有报错显示为gymnasium.error.NameNotFound: Environment mymerge doesn't exist这个问题,也可以参看这个博文应该会有帮助
第一步
找到highway-env所在文件夹,我的highway版本呢是1.8.2有区别于之前的版本,在conda环境下,我的路径在C:\Users\HP\.conda\envs\highway_env\Lib\site-packages\highway_env\envs
第二步
我们要创建一个新的环境,最简单的就是用一个已有的模板来套
这里我们选择intersection,复制intersection_env.py,在envs文件下(即当前文件夹下)创建一个自己的环境文件,命名为Myintersection_env.py
第三步
在Myintersection_env.py中修改类名
class myIntersectionEnv(AbstractEnv): -> class IntersectionEnv(AbstractEnv):
第四步
在envs的上级目录中,即C:\Users\HP\.conda\envs\highway_env\Lib\site-packages\highway_env有一个_init_.py文件,点开,加上我们新的环境:
# new intersection_env.py
register(
id='myintersection-v0',
entry_point='highway_env.envs:myIntersectionEnv',
)
其中这个myIntersectionEnv就是我们定义的抽象类的类名
第五步
在C:\Users\HP\.conda\envs\highway_env\Lib\site-packages\highway_env\envs路径下有一个_init_.py文件,加上
from highway_env.envs.myIntersection_env import *
第六步
跑自己的代码:
train.py
import gymnasium as gym
import highway_env
from stable_baselines3 import A2C
# Create environment
env = gym.make("myintersection-v0")
model = A2C("MlpPolicy",
env,
tensorboard_log="./logs",
verbose=1)
model.learn(total_timesteps=25000)
model.save("a2c_intersection")
test.py
import gymnasium as gym
from stable_baselines3 import A2C
# Create environment
env = gym.make("myintersection-v0", render_mode="rgb_array")
# load model
model = A2C.load("a2c_intersection", env=env)
episodes = 10
for eq in range(episodes):
obs, info = env.reset()
done = truncated = False
rewards = 0
actions = []
while not (done or truncated):
action, _state = model.predict(obs, deterministic=True)
obs, reward, done, truncated, info = env.step(action)
action = action.item()
actions.append(action)
env.render()
rewards += reward
print('actions: {}'.format(actions))
print('rewards: {}'.format(rewards))