环境配置:
python: 3.12.8
ray: 2.40.0
实践代码及注释:
import ray
from ray.rllib.algorithms.ppo import PPOConfig
from ray import train, tune
import torch
ray.init()
config = PPOConfig()
config = config.training(lr=tune.grid_search([0.01, 0.001]))
config = config.environment(env="CartPole-v1")
## episode_reward_mean 提示找不到, 应该改成了 episode_return_mean
# tune_config = tune.TuneConfig(metric="env_runners/episode_return_mean", mode="max") # "env_runners/episode_return_mean"
tuner = tune.Tuner(
"PPO", ## 这里放的是 tune.trainable的class, 是个agent类或策略类。
run_config = train.RunConfig(
stop = {'env_runners/episode_return_mean':10, ## episode_reward_mean 和 episode_return_mean 都会报错
"training_iteration":3}, ## 多个停止条件之间是或的关系, 是一个字典。
checkpoint_config = train.CheckpointConfig(checkpoint_at_end=True), ## 用于设置保存哪个checkpoint.
storage_path = "F:/codes/RLlib_study/ray_results",
),
param_space=config, ## 这里定义了参数搜索调优空间,是一个PPOConfig对象
# tune_config=tune_config
)
## Tuner.fit() 默认创建一个log文件夹,通常位于 “~/ray-results”, windows下位于 “C:/用户/xxx/ray_results”
## 这个文件夹位置可以通过上面的 tune.Tuner.run_config.storage_path的设置而改变
results = tuner.fit() ## tuner 返回一个ResultGrid对象,该对象允许进一步分析训练结果并检索经过训练的智能体的checkpoint。
## 获取最佳结果
best_result = results.get_best_result(metric="env_runners/episode_return_mean", mode="max")
## 以 "episode_reward_mean" 为选择指标, 从results里面选择checkpoint, 选择模式是“max”,
## 在一些旧版本的ray中, metric可以被设置为“episode_reward_mean”,
## 不知道从哪一个版本开始,“episode_reward_mean” 不被识别, 变成了 "env_runners/episode_return_mean"。
## 更多的可选指标,可以去 “~/ray-results” 或 自定义的 storage_path 中的 result.json中去找key
## 得到的 best_result 不直接是 checkpoint, 需要通过以下方式保存。
## 获取最佳结果里面的 checkpoint
best_checkpoint = best_result.checkpoint
## 保存checkpoint 到本地
if best_checkpoint:
with best_checkpoint.as_directory() as checkpoint_dir:
print(f"Checkpoint directory:{checkpoint_dir}")
1346



被折叠的 条评论
为什么被折叠?



