본문으로 건너뛰기
Skillpedia
머신러닝33k · #9031

stable-baselines3

하는 일

이 스킬은 에이전트가 PyTorch 기반의 검증된 강화학습 알고리즘 라이브러리 Stable Baselines3를 사용하도록 안내합니다. 알고리즘을 처음부터 구현하지 않고 에이전트를 학습시키려는 개발자와 연구자를 위한 스킬입니다.

사용하는 경우

  • ✓PPO, SAC, DQN 같은 표준 알고리즘으로 에이전트를 학습시키고 싶을 때.
  • ✓에이전트가 학습할 사용자 정의 Gym 환경을 만들어야 할 때.
  • ✓학습 실행을 모니터링하거나 제어하기 위해 콜백을 추가하고 싶을 때.

스킬 링크

https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/scientific/stable-baselines3/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/scientific/stable-baselines3/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“제 사용자 정의 Gym 환경에서 PPO 에이전트를 10만 스텝 동안 학습하고, 저장한 뒤 나중에 불러오는 방법을 알려 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

에이전트는 환경을 만들고, 알고리즘을 고르고, 설정한 스텝 수만큼 학습 함수를 호출합니다. 그다음 학습된 모델을 나중에 쓸 수 있도록 저장합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

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.

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
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_s
자주 묻는 질문

어떤 알고리즘이 포함되나요?

스킬은 PPO, A2C, SAC, TD3, DDPG, DQN, HER를 다룹니다.

어떤 알고리즘을 골라야 하나요?

스킬은 PPO와 A2C는 범용이고, SAC와 TD3는 연속 제어에 적합하다고 설명합니다.

모델과 함께 재생 버퍼도 저장되나요?

아닙니다. 파일 크기를 줄이기 위해 재생 버퍼는 저장되지 않는다고 스킬은 설명합니다.

상세 정보

작성자의 원본 설명

Use this skill for reinforcement learning tasks including training RL agents (PPO, SAC, DQN, TD3, DDPG, A2C, etc.), creating custom Gym environments, implementing callbacks for monitoring and control, using vectorized environments for parallel training, and integrating with deep RL workflows. This skill should be used when users request RL algorithm implementation, agent training, environment design, or RL experimentation.

repo: davila7/claude-code-templates

인기도

GitHub 스타
33k
순위
#9031
라이선스
MIT
업데이트
2026. 11. 2.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬