Train a small policy and keep the experiment reproducible

Use a simple environment to practice training, saving, and evaluating a policy.

Guided walkthrough·Intermediate·5 min read

Run a trained policy in your browser

A PPO neural network chooses left or right from the cart position, velocity, pole angle and angular velocity. Each step runs the model weights in your browser. Compare it with random actions from the same initial state. The policy was trained beforehand; it does not learn during this replay.

Ready. The model downloads when you run the exercise.

Trained PPO policy

Return: 0 / 500

Last action: waiting

Random actions

Return: 0 / 500

Last action: waiting

Try several seeds. Every simulated step earns 1 reward, including the failure step. An episode ends when the cart crosses ±2.4 m, the pole tilts past ±12°, or it reaches the 500-step time limit. One successful episode does not establish reliability across starting conditions.

Model and training evidence

The 20 KB actor was trained with Stable Baselines3 PPO for 51,200 CartPole-v1 steps using seed 7. It scored a mean return of 500 on 20 held-out Gymnasium seeds; random actions averaged 21.4. Browser resets use a different seeded generator, so compare policies within the same browser run. The first run also downloads the WASM runtime.

Requirements and learning goals

Before you start

  • Python environment
  • Observation-action-reward lesson

You will be able to

  • Train a PPO policy
  • Save experiment details
  • Compare against a random baseline

A chooses an action from the current observation. Here it learns to push a cart left or right to keep a pole balanced. PPO, or Proximal Policy Optimization, updates the policy using from repeated attempts. This small problem lets you practice training and evaluation before spending compute on a robot.

You will save a trained policy and compare it with random actions on the same starting conditions.

First, press Run policy comparison in the browser exercise above. A pretrained PPO actor runs real neural-network inference on each observation, alongside random actions from the same start. Change the seed and repeat. This replay does not update the weights. Our yzma fork includes the training script, checkpoint, model and evaluation report. That bundled policy trained for 51,200 steps; the walkthrough below trains your own policy with a smaller budget.

The Write Python tab has two examples. Train a Q-table learns a separate five-cell reaching task in your browser. Run the trained PPO model calls await predict(observation) on the same PPO actor as the guided view. Python controls the simulation loop and plots the pole angle. Change the seed, or set flip_action = True to see what happens when you reverse the model's chosen force.

After the small learner works, check its input contract against the robot simulator interfaces. A Gymnasium environment is not automatically a deployable robot app.

Prepare the environment

Use Python 3.11 or 3.12 on a laptop or desktop. No robot or GPU is needed. In a macOS or Linux terminal:

mkdir cartpole-experiment
cd cartpole-experiment
python3 -m venv .venv
source .venv/bin/activate
python -m pip install gymnasium==1.4.0 stable-baselines3==2.9.2
python -m pip freeze > requirements-resolved.txt

On Windows, create the environment with py -m venv .venv and activate it with .venv\Scripts\Activate.ps1 in PowerShell. The remaining Python commands are the same.

Keep requirements-resolved.txt with your scripts and checkpoint.

Train and save

Create train.py:

import json
import time
from pathlib import Path
 
import gymnasium as gym
from stable_baselines3 import PPO
 
settings = {"environment": "CartPole-v1", "seed": 7, "budget": 20_000}
env = gym.make(settings["environment"])
started = time.perf_counter()
model = PPO("MlpPolicy", env, seed=settings["seed"], device="cpu", verbose=1)
model.learn(total_timesteps=settings["budget"])
model.save("cartpole-seed7")
settings["actual_timesteps"] = model.num_timesteps
settings["training_seconds"] = time.perf_counter() - started
Path("training.json").write_text(json.dumps(settings, indent=2))
env.close()

Run python train.py. Training prints progress and produces cartpole-seed7.zip and training.json. The actual step count can exceed the requested budget because PPO collects complete rollout batches. Runtime varies by computer.

Checkpoint 1 of 2

training.json shows actual_timesteps slightly above the budget of 20,000. What is the most likely explanation?

Commit to an answer. Every choice explains itself.

Evaluate in a new process

Create evaluate.py:

import json
from pathlib import Path
from statistics import mean, pstdev
 
import gymnasium as gym
from stable_baselines3 import PPO
 
model = PPO.load("cartpole-seed7", device="cpu")
seeds = list(range(1000, 1020))
report = {"evaluation_seeds": seeds}
 
for policy in ("random", "trained"):
    env = gym.make("CartPole-v1")
    returns = []
    for seed in seeds:
        observation, _ = env.reset(seed=seed)
        env.action_space.seed(seed)
        total = 0.0
        while True:
            if policy == "random":
                action = env.action_space.sample()
            else:
                action, _ = model.predict(observation, deterministic=True)
                action = int(action)
            observation, reward, terminated, truncated, _ = env.step(action)
            total += float(reward)
            if terminated or truncated:
                break
        returns.append(total)
    env.close()
    report[policy] = {
        "returns": returns,
        "mean": mean(returns),
        "standard_deviation": pstdev(returns),
    }
 
Path("evaluation.json").write_text(json.dumps(report, indent=2))
print(json.dumps(report, indent=2))

Run python evaluate.py. This checks that the saved model works in a fresh process.

Check the expected results

Open evaluation.json. Each policy should have 20 returns, a mean, and a standard deviation. Both policies start from the same list of reset seeds. Their trajectories diverge because their actions differ.

Return is the sum of rewards in an episode. Here a larger return means the pole stayed balanced longer. Compare all 20 results, including failures, rather than keeping only the best run. You are done when you can reload the checkpoint and explain whether it beat random actions on these seeds.

Checkpoint 2 of 2

A teammate evaluates the random policy on seeds 1000 to 1019 and the trained policy on seeds 2000 to 2019. The trained mean is higher. What is the weakness in that comparison?

Commit to an answer. Every choice explains itself.

Troubleshooting and next experiment

If imports fail, activate the environment. If the model is missing, run evaluation beside cartpole-seed7.zip.

Optional extension: train with another seed and checkpoint filename, keeping evaluation seeds fixed. Compare variation across models. CartPole performance does not establish robot performance.

Reference: Stable Baselines3 PPO.

Can you do each of these?

  • Train a PPO policy
  • Save experiment details
  • Compare against a random baseline

0 of 2 checkpoints solved. Try checkpoint 1

Previous: Test a policy with imperfect sensors
All lessons in this topic
  1. 1. Define observations, actions, and rewards
  2. 2. Test a policy with imperfect sensors
  3. 3. Train a small policy and keep the experiment reproducible
  4. 4. Learn from demonstrations without copying hidden state
  5. 5. Evaluate and replay a policy as a complete system
  6. 6. Measure the simulation-to-hardware gap

Ask Wendy

Answers about Wendy and WendyOS

What would you like to know?

Ask about devices, development, and deployment.

Check linked docs for technical details.