返回技能列表

stable-baselines3

K-Dense-AI
更新于 Today
26,534
2,743
26,534
在 GitHub 上查看
设计wordaiapidesign

关于

Stable Baselines3 provides production-ready RL algorithms (like PPO and DQN) with a scikit-learn-like API for single-agent training in Gymnasium environments. It's ideal for standard experiments and quick prototyping. For advanced needs like parallel training or multi-agent systems, use pufferlib instead.

快速安装

Claude Code

推荐
主要方式
npx skills add K-Dense-AI/claude-scientific-skills -a claude-code
插件命令备选方式
/plugin add https://github.com/K-Dense-AI/claude-scientific-skills
Git 克隆备选方式
git clone https://github.com/K-Dense-AI/claude-scientific-skills.git ~/.claude/skills/stable-baselines3

在 Claude Code 中复制并粘贴此命令以安装该技能

技能文档

Stable Baselines3

Overview

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.

Current upstream: SB3 2.8.0 (April 2026). Docs: stable-baselines3.readthedocs.io.

Installation

Tested against stable-baselines3 2.8.0. Requires Python 3.10+ (3.9 dropped in 2.8.0) and PyTorch >= 2.3.

# Basic installation
uv pip install "stable-baselines3>=2.8"

# With extra dependencies (TensorBoard, ale-py for Atari, etc.)
uv pip install "stable-baselines3[extra]>=2.8"

On zsh, quote brackets: uv pip install 'stable-baselines3[extra]>=2.8'.

For MuJoCo continuous-control benchmarks:

uv pip install "gymnasium[mujoco]"

Check your version:

import stable_baselines3
print(stable_baselines3.__version__)

Related Projects

  • SB3-Contrib: experimental algorithms (MaskablePPO, CrossQ, QR-DQN, RecurrentPPO) — separate sb3-contrib package
  • RL Baselines3 Zoo: pre-trained agents, hyperparameters, training scripts
  • SBX: SB3 + JAX implementations for users who prefer JAX over PyTorch

Core Capabilities

1. Training RL Agents

Basic Training Pattern:

import gymnasium as gym
from stable_baselines3 import PPO

# Create environment
env = gym.make("CartPole-v1")

# Initialize agent (device="cpu" is often faster for MlpPolicy on small envs)
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 collection
  • Use model.load() as a static method, not on an existing instance
  • The replay buffer is NOT saved with the model to save space

Algorithm Selection: Use references/algorithms.md for detailed algorithm characteristics and selection guidance. Quick reference:

  • PPO/A2C: General-purpose, supports all action space types, good for multiprocessing
  • SAC/TD3: Continuous control, off-policy, sample-efficient
  • DQN: Discrete actions, off-policy
  • HER: Goal-conditioned tasks

See scripts/train_rl_agent.py for a complete training template with best practices.

2. Custom Environments

Requirements: Custom environments must inherit from gymnasium.Env and implement:

  • __init__(): Define action_space and observation_space
  • reset(seed, options): Return initial observation and info dict
  • step(action): Return observation, reward, terminated, truncated, info
  • render(): Visualization (optional)
  • close(): Cleanup resources

Key Constraints:

  • Image observations must be np.uint8 in range [0, 255]
  • Use channel-first format when possible (channels, height, width)
  • SB3 normalizes images automatically by dividing by 255
  • Set normalize_images=False in policy_kwargs if pre-normalized
  • SB3 does NOT support Discrete or MultiDiscrete spaces with start!=0

Validation:

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.

3. Vectorized Environments

Purpose: Vectorized environments run multiple environment instances in parallel, accelerating training and enabling certain wrappers (frame-stacking, normalization).

Types:

  • DummyVecEnv: Sequential execution on current process (for lightweight environments)
  • SubprocVecEnv: Parallel execution across processes (for compute-heavy environments)

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-tuple
  • Environments auto-reset after episodes
  • Terminal observations available via infos[env_idx]["terminal_observation"]

See references/vectorized_envs.md for detailed information on wrappers and advanced usage.

4. Callbacks for Monitoring and Control

Purpose: Callbacks enable monitoring metrics, saving checkpoints, implementing early stopping, and custom training logic without modifying core algorithms.

Common Callbacks:

  • EvalCallback: Evaluate periodically and save best model
  • CheckpointCallback: Save model checkpoints at intervals
  • StopTrainingOnRewardThreshold: Stop when target reward reached
  • ProgressBarCallback: Display training progress with timing

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 instance
  • self.num_timesteps: Total environment steps
  • self.training_env: The training environment

Chaining 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.

5. Model Persistence and Inspection

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()

6. Evaluation and Recording

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.

7. Advanced Features

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)

Workflow Guidance

Starting a New RL Project:

  1. Define the problem: Identify observation space, action space, and reward structure
  2. Choose algorithm: Use references/algorithms.md for selection guidance
  3. Create/adapt environment: Use scripts/custom_env_template.py if needed
  4. Validate environment: Always run check_env() before training
  5. Set up training: Use scripts/train_rl_agent.py as starting template
  6. Add monitoring: Implement callbacks for evaluation and checkpointing
  7. Optimize performance: Consider vectorized environments for speed
  8. Evaluate and iterate: Use scripts/evaluate_agent.py for assessment

Common Issues:

  • Memory errors: Reduce buffer_size for off-policy algorithms or use fewer parallel environments
  • Slow training: Consider SubprocVecEnv for parallel environments
  • Unstable training: Try different algorithms, tune hyperparameters, or check reward scaling
  • Import errors: Ensure stable_baselines3 is installed: uv pip install 'stable-baselines3[extra]>=2.8'

Resources

scripts/

  • train_rl_agent.py: Complete training script template with best practices
  • evaluate_agent.py: Agent evaluation and video recording template
  • custom_env_template.py: Custom Gym environment template

references/

  • algorithms.md: Detailed algorithm comparison and selection guide
  • custom_environments.md: Comprehensive custom environment creation guide
  • callbacks.md: Complete callback system reference
  • vectorized_envs.md: Vectorized environment usage and wrappers

GitHub 仓库

K-Dense-AI/claude-scientific-skills
路径: skills/stable-baselines3
0
agent-skillsai-scientistbioinformaticschemoinformaticsclaudeclaude-skills

相关推荐技能

executing-plans

设计

该Skill用于当开发者提供完整实施计划时,以受控批次方式执行代码实现。它会先审阅计划并提出疑问,然后分批次执行任务(默认每批3个任务),并在批次间暂停等待审查。关键特性包括分批次执行、内置检查点和架构师审查机制,确保复杂系统实现的可控性。

查看技能

requesting-code-review

设计

该Skill可在完成任务、实现主要功能或合并代码前自动调度代码审查子代理,确保实现符合需求和计划。它支持通过指定git SHA范围进行精准的代码变更审查,帮助开发者在关键节点及时发现潜在问题。核心原则是"早审查、勤审查",适用于开发流程的各个关键阶段。

查看技能

connect-mcp-server

设计

这个Skill指导开发者如何将MCP服务器连接到Claude Code,支持HTTP、stdio和SSE三种传输协议。它涵盖了从安装配置到认证安全的完整流程,适用于集成GitHub、Notion、数据库等外部服务。当开发者需要添加集成、配置外部工具或提及MCP相关功能时,这个Skill能提供实用的操作指南。

查看技能

web-cli-teleport

设计

该Skill帮助开发者根据任务特性选择Claude Code的Web或CLI界面,并指导如何在两种环境间无缝迁移会话。它能分析任务复杂度、迭代需求等要素,推荐最优工作界面和工作流。关键特性包括会话状态管理、环境切换指导和上下文优化建议。

查看技能