stable-baselines3 by davila7/claude-code-templates
npx skills add https://github.com/davila7/claude-code-templates --skill stable-baselines3Stable Baselines3 (SB3) 是一个基于 PyTorch 的库,提供了强化学习算法的可靠实现。本技能提供了使用 SB3 统一 API 训练 RL 智能体、创建自定义环境、实现回调以及优化训练工作流的全面指导。
基本训练模式:
import gymnasium as gym
from stable_baselines3 import PPO
# 创建环境
env = gym.make("CartPole-v1")
# 初始化智能体
model = PPO("MlpPolicy", env, verbose=1)
# 训练智能体
model.learn(total_timesteps=10000)
# 保存模型
model.save("ppo_cartpole")
# 加载模型(无需预先实例化)
model = PPO.load("ppo_cartpole", env=env)
重要说明:
total_timesteps 是一个下限值;由于批次收集,实际训练可能超过此值model.load() 作为静态方法,而非在现有实例上调用算法选择: 使用 references/algorithms.md 获取详细的算法特性和选择指导。快速参考:
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
有关包含最佳实践的完整训练模板,请参阅 scripts/train_rl_agent.py。
要求: 自定义环境必须继承自 gymnasium.Env 并实现:
__init__(): 定义 action_space 和 observation_spacereset(seed, options): 返回初始观察和信息字典step(action): 返回观察、奖励、终止标志、截断标志和信息render(): 可视化(可选)close(): 清理资源关键约束:
np.uint8 类型,范围在 [0, 255] 内normalize_images=Falsestart!=0 的 Discrete 或 MultiDiscrete 空间验证:
from stable_baselines3.common.env_checker import check_env
check_env(env, warn=True)
有关完整的自定义环境模板,请参阅 scripts/custom_env_template.py;有关全面指导,请参阅 references/custom_environments.md。
目的: 向量化环境并行运行多个环境实例,加速训练并启用某些包装器(帧堆叠、归一化)。
类型:
快速设置:
from stable_baselines3.common.env_util import make_vec_env
# 创建 4 个并行环境
env = make_vec_env("CartPole-v1", n_envs=4, vec_env_cls=SubprocVecEnv)
model = PPO("MlpPolicy", env, verbose=1)
model.learn(total_timesteps=25000)
离策略优化: 当对离策略算法(SAC、TD3、DQN)使用多个环境时,设置 gradient_steps=-1 以在每个环境步骤执行一次梯度更新,从而平衡挂钟时间和样本效率。
API 差异:
reset() 仅返回观察(信息可通过 vec_env.reset_infos 获取)step() 返回 4 元组:(obs, rewards, dones, infos),而非 5 元组infos[env_idx]["terminal_observation"] 获取有关包装器和高级用法的详细信息,请参阅 references/vectorized_envs.md。
目的: 回调功能允许监控指标、保存检查点、实现早停和自定义训练逻辑,而无需修改核心算法。
常用回调:
自定义回调结构:
from stable_baselines3.common.callbacks import BaseCallback
class CustomCallback(BaseCallback):
def _on_training_start(self):
# 在第一次 rollout 之前调用
pass
def _on_step(self):
# 在每个环境步骤之后调用
# 返回 False 以停止训练
return True
def _on_rollout_end(self):
# 在 rollout 结束时调用
pass
可用属性:
self.model: RL 算法实例self.num_timesteps: 总环境步数self.training_env: 训练环境链式回调:
from stable_baselines3.common.callbacks import CallbackList
callback = CallbackList([eval_callback, checkpoint_callback, custom_callback])
model.learn(total_timesteps=10000, callback=callback)
有关完整的回调文档,请参阅 references/callbacks.md。
保存和加载:
# 保存模型
model.save("model_name")
# 保存归一化统计信息(如果使用 VecNormalize)
vec_env.save("vec_normalize.pkl")
# 加载模型
model = PPO.load("model_name", env=env)
# 加载归一化统计信息
vec_env = VecNormalize.load("vec_normalize.pkl", vec_env)
参数访问:
# 获取参数
params = model.get_parameters()
# 设置参数
model.set_parameters(params)
# 访问 PyTorch 状态字典
state_dict = model.policy.state_dict()
评估:
from stable_baselines3.common.evaluation import evaluate_policy
mean_reward, std_reward = evaluate_policy(
model,
env,
n_eval_episodes=10,
deterministic=True
)
视频录制:
from stable_baselines3.common.vec_env import VecVideoRecorder
# 用视频录制器包装环境
env = VecVideoRecorder(
env,
"videos/",
record_video_trigger=lambda x: x % 2000 == 0,
video_length=200
)
有关完整的评估和录制模板,请参阅 scripts/evaluate_agent.py。
学习率调度:
def linear_schedule(initial_value):
def func(progress_remaining):
# progress_remaining 从 1 到 0
return progress_remaining * initial_value
return func
model = PPO("MlpPolicy", env, learning_rate=linear_schedule(0.001))
多输入策略(字典观察):
model = PPO("MultiInputPolicy", env, verbose=1)
当观察是字典时使用(例如,结合图像和传感器数据)。
事后经验回放:
from stable_baselines3 import SAC, HerReplayBuffer
model = SAC(
"MultiInputPolicy",
env,
replay_buffer_class=HerReplayBuffer,
replay_buffer_kwargs=dict(
n_sampled_goal=4,
goal_selection_strategy="future",
),
)
TensorBoard 集成:
model = PPO("MlpPolicy", env, tensorboard_log="./tensorboard/")
model.learn(total_timesteps=10000)
启动新的 RL 项目:
references/algorithms.md 获取选择指导scripts/custom_env_template.pycheck_env()scripts/train_rl_agent.py 作为起始模板scripts/evaluate_agent.py 进行评估常见问题:
buffer_size 或使用更少的并行环境stable_baselines3:uv pip install stable-baselines3[extra]train_rl_agent.py: 包含最佳实践的完整训练脚本模板evaluate_agent.py: 智能体评估和视频录制模板custom_env_template.py: 自定义 Gym 环境模板algorithms.md: 详细的算法比较和选择指南custom_environments.md: 全面的自定义环境创建指南callbacks.md: 完整的回调系统参考vectorized_envs.md: 向量化环境用法和包装器# 基本安装
uv pip install stable-baselines3
# 包含额外依赖项(Tensorboard 等)
uv pip install stable-baselines3[extra]
每周安装量
138
代码仓库
GitHub 星标数
22.6K
首次出现
2026年1月21日
安全审计
安装于
claude-code117
opencode112
gemini-cli106
cursor106
antigravity97
codex93
Stable Baselines3 (SB3) is a PyTorch-based library providing reliable implementations of reinforcement learning algorithms. This skill provides comprehensive guidance for training RL agents, creating custom environments, implementing callbacks, and optimizing training workflows using SB3's unified API.
Basic Training Pattern:
import gymnasium as gym
from stable_baselines3 import PPO
# Create environment
env = gym.make("CartPole-v1")
# Initialize agent
model = PPO("MlpPolicy", env, verbose=1)
# Train the agent
model.learn(total_timesteps=10000)
# Save the model
model.save("ppo_cartpole")
# Load the model (without prior instantiation)
model = PPO.load("ppo_cartpole", env=env)
Important Notes:
total_timesteps is a lower bound; actual training may exceed this due to batch collectionmodel.load() as a static method, not on an existing instanceAlgorithm Selection: Use references/algorithms.md for detailed algorithm characteristics and selection guidance. Quick reference:
See scripts/train_rl_agent.py for a complete training template with best practices.
Requirements: Custom environments must inherit from gymnasium.Env and implement:
__init__(): Define action_space and observation_spacereset(seed, options): Return initial observation and info dictstep(action): Return observation, reward, terminated, truncated, inforender(): Visualization (optional)close(): Cleanup resourcesKey Constraints:
np.uint8 in range [0, 255]normalize_images=False in policy_kwargs if pre-normalizedDiscrete or MultiDiscrete spaces with start!=0Validation:
from stable_baselines3.common.env_checker import check_env
check_env(env, warn=True)
See scripts/custom_env_template.py for a complete custom environment template and references/custom_environments.md for comprehensive guidance.
Purpose: Vectorized environments run multiple environment instances in parallel, accelerating training and enabling certain wrappers (frame-stacking, normalization).
Types:
Quick Setup:
from stable_baselines3.common.env_util import make_vec_env
# Create 4 parallel environments
env = make_vec_env("CartPole-v1", n_envs=4, vec_env_cls=SubprocVecEnv)
model = PPO("MlpPolicy", env, verbose=1)
model.learn(total_timesteps=25000)
Off-Policy Optimization: When using multiple environments with off-policy algorithms (SAC, TD3, DQN), set gradient_steps=-1 to perform one gradient update per environment step, balancing wall-clock time and sample efficiency.
API Differences:
reset() returns only observations (info available in vec_env.reset_infos)step() returns 4-tuple: (obs, rewards, dones, infos) not 5-tupleinfos[env_idx]["terminal_observation"]See references/vectorized_envs.md for detailed information on wrappers and advanced usage.
Purpose: Callbacks enable monitoring metrics, saving checkpoints, implementing early stopping, and custom training logic without modifying core algorithms.
Common Callbacks:
Custom Callback Structure:
from stable_baselines3.common.callbacks import BaseCallback
class CustomCallback(BaseCallback):
def _on_training_start(self):
# Called before first rollout
pass
def _on_step(self):
# Called after each environment step
# Return False to stop training
return True
def _on_rollout_end(self):
# Called at end of rollout
pass
Available Attributes:
self.model: The RL algorithm instanceself.num_timesteps: Total environment stepsself.training_env: The training environmentChaining Callbacks:
from stable_baselines3.common.callbacks import CallbackList
callback = CallbackList([eval_callback, checkpoint_callback, custom_callback])
model.learn(total_timesteps=10000, callback=callback)
See references/callbacks.md for comprehensive callback documentation.
Saving and Loading:
# Save model
model.save("model_name")
# Save normalization statistics (if using VecNormalize)
vec_env.save("vec_normalize.pkl")
# Load model
model = PPO.load("model_name", env=env)
# Load normalization statistics
vec_env = VecNormalize.load("vec_normalize.pkl", vec_env)
Parameter Access:
# Get parameters
params = model.get_parameters()
# Set parameters
model.set_parameters(params)
# Access PyTorch state dict
state_dict = model.policy.state_dict()
Evaluation:
from stable_baselines3.common.evaluation import evaluate_policy
mean_reward, std_reward = evaluate_policy(
model,
env,
n_eval_episodes=10,
deterministic=True
)
Video Recording:
from stable_baselines3.common.vec_env import VecVideoRecorder
# Wrap environment with video recorder
env = VecVideoRecorder(
env,
"videos/",
record_video_trigger=lambda x: x % 2000 == 0,
video_length=200
)
See scripts/evaluate_agent.py for a complete evaluation and recording template.
Learning Rate Schedules:
def linear_schedule(initial_value):
def func(progress_remaining):
# progress_remaining goes from 1 to 0
return progress_remaining * initial_value
return func
model = PPO("MlpPolicy", env, learning_rate=linear_schedule(0.001))
Multi-Input Policies (Dict Observations):
model = PPO("MultiInputPolicy", env, verbose=1)
Use when observations are dictionaries (e.g., combining images with sensor data).
Hindsight Experience Replay:
from stable_baselines3 import SAC, HerReplayBuffer
model = SAC(
"MultiInputPolicy",
env,
replay_buffer_class=HerReplayBuffer,
replay_buffer_kwargs=dict(
n_sampled_goal=4,
goal_selection_strategy="future",
),
)
TensorBoard Integration:
model = PPO("MlpPolicy", env, tensorboard_log="./tensorboard/")
model.learn(total_timesteps=10000)
Starting a New RL Project:
references/algorithms.md for selection guidancescripts/custom_env_template.py if neededcheck_env() before trainingscripts/train_rl_agent.py as starting templatescripts/evaluate_agent.py for assessmentCommon Issues:
buffer_size for off-policy algorithms or use fewer parallel environmentsstable_baselines3 is installed: uv pip install stable-baselines3[extra]train_rl_agent.py: Complete training script template with best practicesevaluate_agent.py: Agent evaluation and video recording templatecustom_env_template.py: Custom Gym environment templatealgorithms.md: Detailed algorithm comparison and selection guidecustom_environments.md: Comprehensive custom environment creation guidecallbacks.md: Complete callback system referencevectorized_envs.md: Vectorized environment usage and wrappers# Basic installation
uv pip install stable-baselines3
# With extra dependencies (Tensorboard, etc.)
uv pip install stable-baselines3[extra]
Weekly Installs
138
Repository
GitHub Stars
22.6K
First Seen
Jan 21, 2026
Security Audits
Gen Agent Trust HubWarnSocketPassSnykPass
Installed on
claude-code117
opencode112
gemini-cli106
cursor106
antigravity97
codex93
AI Elements:基于shadcn/ui的AI原生应用组件库,快速构建对话界面
62,200 周安装