🛠️ Stable Baselines3
強化学習の主要なアルゴリズム(
📺 まず動画で見る(YouTube)
▶ 【衝撃】最強のAIエージェント「Claude Code」の最新機能・使い方・プログラミングをAIで効率化する超実践術を解説! ↗
※ jpskill.com 編集部が参考用に選んだ動画です。動画の内容と Skill の挙動は厳密には一致しないことがあります。
📜 元の英語説明(参考)
Production-ready reinforcement learning algorithms (PPO, SAC, DQN, TD3, DDPG, A2C) with scikit-learn-like API. Use for standard RL experiments, quick prototyping, and well-documented algorithm implementations. Best for single-agent RL with Gymnasium environments. For high-performance parallel training, multi-agent systems, or custom vectorized environments, use pufferlib instead.
🇯🇵 日本人クリエイター向け解説
強化学習の主要なアルゴリズム(
※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。
下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o stable-baselines3.zip https://jpskill.com/download/4245.zip && unzip -o stable-baselines3.zip && rm stable-baselines3.zip
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/4245.zip -OutFile "$d\stable-baselines3.zip"; Expand-Archive "$d\stable-baselines3.zip" -DestinationPath $d -Force; ri "$d\stable-baselines3.zip"
完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。
💾 手動でダウンロードしたい(コマンドが難しい人向け)
- 1. 下の青いボタンを押して
stable-baselines3.zipをダウンロード - 2. ZIPファイルをダブルクリックで解凍 →
stable-baselines3フォルダができる - 3. そのフォルダを
C:\Users\あなたの名前\.claude\skills\(Win)または~/.claude/skills/(Mac)へ移動 - 4. Claude Code を再起動
⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。
🎯 このSkillでできること
下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。
📦 インストール方法 (3ステップ)
- 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
- 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
- 3. 展開してできたフォルダを、ホームフォルダの
.claude/skills/に置く- · macOS / Linux:
~/.claude/skills/ - · Windows:
%USERPROFILE%\.claude\skills\
- · macOS / Linux:
Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。
詳しい使い方ガイドを見る →- 最終更新
- 2026-05-17
- 取得日時
- 2026-05-18
- 同梱ファイル
- 8
💬 こう話しかけるだけ — サンプルプロンプト
- › Stable Baselines3 を使って、最小構成のサンプルコードを示して
- › Stable Baselines3 の主な使い方と注意点を教えて
- › Stable Baselines3 を既存プロジェクトに組み込む方法を教えて
これをClaude Code に貼るだけで、このSkillが自動発動します。
📖 Skill本文(日本語訳)
※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。
Stable Baselines3
概要
Stable Baselines3 (SB3) は、強化学習アルゴリズムの信頼性の高い実装を提供する PyTorch ベースのライブラリです。このスキルは、SB3 の統一された API を使用して、RL エージェントのトレーニング、カスタム環境の作成、コールバックの実装、およびトレーニングワークフローの最適化に関する包括的なガイダンスを提供します。
主要な機能
1. RL エージェントのトレーニング
基本的なトレーニングパターン:
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)
重要な注意事項:
total_timestepsは下限値です。実際のトレーニングはバッチ収集によりこれを超える場合があります。model.load()は既存のインスタンスに対してではなく、静的メソッドとして使用してください。- リプレイバッファはスペースを節約するため、モデルと一緒に保存されません。
アルゴリズムの選択:
詳細なアルゴリズムの特性と選択のガイダンスについては、references/algorithms.md を参照してください。クイックリファレンス:
- PPO/A2C: 汎用、すべてのアクションスペースタイプをサポート、マルチプロセッシングに適しています。
- SAC/TD3: 連続制御、オフポリシー、サンプル効率が良いです。
- DQN: 離散アクション、オフポリシーです。
- HER: 目標条件付きタスクです。
ベストプラクティスを含む完全なトレーニングテンプレートについては、scripts/train_rl_agent.py を参照してください。
2. カスタム環境
要件:
カスタム環境は gymnasium.Env を継承し、以下を実装する必要があります。
__init__():action_spaceとobservation_spaceを定義します。reset(seed, options): 初期観測と情報辞書を返します。step(action): 観測、報酬、terminated、truncated、情報を返します。render(): 視覚化(オプション)close(): リソースをクリーンアップします。
主な制約:
- 画像観測は
np.uint8で、範囲は [0, 255] である必要があります。 - 可能な場合はチャネルファースト形式(チャネル、高さ、幅)を使用してください。
- SB3 は画像を自動的に 255 で割って正規化します。
- 事前に正規化されている場合は、
policy_kwargsでnormalize_images=Falseを設定してください。 - SB3 は
start!=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 を参照してください。
3. ベクトル化環境
目的: ベクトル化環境は複数の環境インスタンスを並行して実行し、トレーニングを高速化し、特定のラッパー(フレームスタッキング、正規化)を可能にします。
種類:
- DummyVecEnv: 現在のプロセスでシーケンシャルに実行(軽量環境向け)
- SubprocVecEnv: プロセス間で並行して実行(計算負荷の高い環境向け)
クイックセットアップ:
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)
オフポリシー最適化:
オフポリシーアルゴリズム(SAC、TD3、DQN)で複数の環境を使用する場合、gradient_steps=-1 を設定して、環境ステップごとに1回の勾配更新を実行し、実時間とサンプル効率のバランスを取ります。
API の違い:
reset()は観測のみを返します(情報はvec_env.reset_infosで利用可能)。step()は4タプル(obs, rewards, dones, infos)を返し、5タプルではありません。- 環境はエピソード後に自動的にリセットされます。
- 終端観測は
infos[env_idx]["terminal_observation"]を介して利用可能です。
ラッパーと高度な使用法に関する詳細情報については、references/vectorized_envs.md を参照してください。
4. 監視と制御のためのコールバック
目的: コールバックは、コアアルゴリズムを変更することなく、メトリクスの監視、チェックポイントの保存、早期停止の実装、およびカスタムトレーニングロジックを可能にします。
一般的なコールバック:
- EvalCallback: 定期的に評価し、最適なモデルを保存します。
- CheckpointCallback: 一定間隔でモデルのチェックポイントを保存します。
- StopTrainingOnRewardThreshold: 目標報酬に達したときに停止します。
- ProgressBarCallback: タイミング付きでトレーニングの進行状況を表示します。
カスタムコールバックの構造:
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
利用可能な属性:
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 を参照してください。
5. モデルの永続化と検査
保存と読み込み:
# 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)
パラメータへのアクセス:
# Get parameters
params = model.get_parameters()
# Set parameters
model.set_parameters(params)
# Access PyTorch state dict
state_dict = model.policy.state_dict()
6. 評価と記録
評価:
from stable_baselines3.common.evaluation import evaluate_policy
mean_reward, std_reward = evaluate_policy(
model,
env,
n_eval_episodes=10,
deterministic=True
)
ビデオ録画:
f 📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開
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_timestepsis 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_spacereset(seed, options): Return initial observation and info dictstep(action): Return observation, reward, terminated, truncated, inforender(): Visualization (optional)close(): Cleanup resources
Key Constraints:
- Image observations must be
np.uint8in range [0, 255] - Use channel-first format when possible (channels, height, width)
- SB3 normalizes images automatically by dividing by 255
- Set
normalize_images=Falsein policy_kwargs if pre-normalized - SB3 does NOT support
DiscreteorMultiDiscretespaces withstart!=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 invec_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 instanceself.num_timesteps: Total environment stepsself.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:
- Define the problem: Identify observation space, action space, and reward structure
- Choose algorithm: Use
references/algorithms.mdfor selection guidance - Create/adapt environment: Use
scripts/custom_env_template.pyif needed - Validate environment: Always run
check_env()before training - Set up training: Use
scripts/train_rl_agent.pyas starting template - Add monitoring: Implement callbacks for evaluation and checkpointing
- Optimize performance: Consider vectorized environments for speed
- Evaluate and iterate: Use
scripts/evaluate_agent.pyfor assessment
Common Issues:
- Memory errors: Reduce
buffer_sizefor 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_baselines3is installed:uv pip install stable-baselines3[extra]
Resources
scripts/
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 template
references/
algorithms.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
Installation
# Basic installation
uv pip install stable-baselines3
# With extra dependencies (Tensorboard, etc.)
uv pip install stable-baselines3[extra] 同梱ファイル
※ ZIPに含まれるファイル一覧。`SKILL.md` 本体に加え、参考資料・サンプル・スクリプトが入っている場合があります。
- 📄 SKILL.md (9,507 bytes)
- 📎 references/algorithms.md (10,038 bytes)
- 📎 references/callbacks.md (15,631 bytes)
- 📎 references/custom_environments.md (13,729 bytes)
- 📎 references/vectorized_envs.md (14,789 bytes)
- 📎 scripts/custom_env_template.py (9,350 bytes)
- 📎 scripts/evaluate_agent.py (7,335 bytes)
- 📎 scripts/train_rl_agent.py (5,123 bytes)