{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "id": "step-0",
   "metadata": {},
   "source": [
    "# Stable-Baselines3 PPO \u00b7 CartPole\n",
    "\n",
    "Learn from interactions in a simulated environment. This small example runs on CPU and does not require a GPU. [Stable-Baselines3](https://stable-baselines3.readthedocs.io/)\n",
    "\n",
    "Run cells in order. Package and weight downloads use instance time and disk. Export outputs before releasing the instance."
   ]
  },
  {
   "cell_type": "code",
   "id": "step-1",
   "metadata": {},
   "source": [
    "import sys, subprocess\n",
    "subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", 'stable-baselines3==2.7.1'])"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "id": "step-2",
   "metadata": {},
   "source": [
    "import gymnasium as gym\n",
    "from stable_baselines3 import PPO\n",
    "from stable_baselines3.common.evaluation import evaluate_policy\n",
    "env = gym.make(\"CartPole-v1\")\n",
    "model = PPO(\"MlpPolicy\", env, device=\"cpu\", seed=7, n_steps=128, verbose=0)\n",
    "model.learn(total_timesteps=2048)\n",
    "model.save(\"cartpole-ppo\")\n",
    "policy = PPO.load(\"cartpole-ppo\", device=\"cpu\")\n",
    "test = gym.make(\"CartPole-v1\")\n",
    "test.reset(seed=8)\n",
    "mean, std = evaluate_policy(policy, test, n_eval_episodes=5)\n",
    "print(\"Mean episode return and standard deviation:\", mean, std)\n",
    "env.close()\n",
    "test.close()"
   ],
   "outputs": [],
   "execution_count": null
  }
 ]
}
