How Do I Train an RL Agent from Scratch? A First-Timer's Recipe
The loop, in 30 seconds
Reinforcement learning is one loop, repeated millions of times. The environment hands the agent an observation. The agent picks an action. The environment returns a reward and a new observation. The agent's policy — the thing being trained — is just the rule that maps observations to actions, and training is the slow process of bending that rule toward actions that earn more reward.
Two consequences follow from that simplicity, and they explain almost everything that goes wrong later. First, the reward function is the only instruction the agent ever receives — if the reward says the wrong thing, the agent will learn the wrong thing, perfectly. Second, everything else — the algorithm, the network, the hyperparameters — is scaffolding around this loop. When a first agent fails, the loop is usually where the bug lives, not the scaffolding.
Step 1 — Pick one environment (and make it boring)
Your first environment should be boring on purpose. CartPole-v1 is the right answer for almost everyone: a four-number observation (position, velocity, angle, angular velocity), two actions (push left, push right), and a reward of +1 for every step the pole stays up. It solves in minutes, and when it doesn't solve, there are only a few things that could be wrong — which is exactly what you want while learning.
After CartPole, the honest ladder is LunarLander-v3 (continuous control, a reward you can actually shape badly — good practice), then either pixels (Atari) or a physics body (MuJoCo locomotion). The full order, with what each step teaches, is in our start-here guide — and the classic-control category in the directory is where to browse the alternatives.
Step 2 — Pick one algorithm: PPO
PPO (Proximal Policy Optimization) is the default first algorithm for a reason: it is stable, forgiving about hyperparameters, and works on discrete and continuous actions alike. Nearly every tutorial, baseline, and library example uses it, which means when something goes wrong you are one search away from someone who had the same failure.
- PPO — the default. Start here. Its defaults in Stable-Baselines3 (learning rate 3e-4, discount 0.99) are sane; don't tune them on run one.
- DQN — the classic value-based algorithm, and a good second step if your actions are discrete and you want to understand Q-learning. It is fussier about exploration and replay buffers.
- SAC — the usual pick for continuous control, like robot arms, once you outgrow PPO on a physics task.
Do not start with the newest algorithm from the newest paper. The newest algorithm has three tutorials and one of them is wrong; PPO has a thousand, and the library implementations have been debugged by years of users.
Step 3 — Write the training loop (it's shorter than you think)
Install the two libraries, then let them carry the loop. Stable-Baselines3 hides the rollout, the advantage computation, and the updates behind one call — which is fine for a first agent. Learn the loop by reading its code later; don't write your own buggy one first.
pip install gymnasium stable-baselines3
import gymnasium as gym
from stable_baselines3 import PPO
env = gym.make("CartPole-v1")
model = PPO("MlpPolicy", env, verbose=1)
model.learn(total_timesteps=50_000)
model.save("ppo_cartpole")
That is the whole training script. The verbose=1 flag prints progress as it goes — watch the mean episode reward climb from the random-policy level (around 20 steps) toward the 500-step ceiling. If it stalls below 100 for thousands of steps, stop and read the debugging section below instead of letting it run.
Step 4 — Evaluate on a fresh environment
Training reward lies. It mixes in exploration noise, early random episodes, and the agent's own learning curve. Honest evaluation means a separate environment, a deterministic policy, and an average over many episodes:
eval_env = gym.make("CartPole-v1")
obs, _ = eval_env.reset()
total, episodes = 0, 0
for _ in range(10_000):
action, _ = model.predict(obs, deterministic=True)
obs, reward, terminated, truncated, _ = eval_env.step(action)
total += reward
if terminated or truncated:
episodes += 1
obs, _ = eval_env.reset()
print(f"mean reward: {total / episodes:.1f} over {episodes} episodes")
Three rules here. First, never evaluate on the environment you trained on — a fresh gym.make is the whole point. Second, compare against a random policy first: if random scores nearly as well as trained, the environment is too easy or the reward is broken, and you have learned nothing. Third, know the "solved" threshold before you celebrate: CartPole counts as solved at an average of 475 over 100 episodes, not at one lucky 500.
Step 5 — Debug the five failures that stop first agents
When a first agent doesn't learn, it is almost always one of these. Check them in order, one at a time — changing five things at once teaches you nothing.
- The reward says nothing. Sparse rewards — zero for hundreds of steps, then a single +1 — give the agent no gradient to climb. Pick a denser environment first, or shape the reward carefully (and then check the shaping didn't teach the wrong thing).
- The observations are unreadable. A network fed pixels alongside a velocity of 10,000 will ignore the velocity. Normalize observations, or use a VecNormalize wrapper — unnormalized inputs are the single most common silent bug.
- Episodes never end, or end wrong. Gymnasium separates terminated (the task ended) from truncated (the time limit ran out), and treating a timeout as a failure corrupts the value estimates. Check your time limits.
- The learning rate is off. The default 3e-4 is a fine starting point. A rate ten times too high thrashes; ten times too low looks like "not learning" for hours. Change it by factors of three, not ten.
- You fooled yourself in evaluation. Same seed, same environment, one lucky episode. Change seeds, run twenty episodes, and distrust any result you can't reproduce.
What hardware do you actually need?
CartPole and LunarLander train in minutes on any laptop CPU — the network is tiny and the environment is cheap to step. A GPU starts to matter when observations are pixels: Atari from frames, or robotics from camera images, where a GPU can cut hours to tens of minutes. A free Colab GPU is enough for that stage. The rule is simple: don't buy hardware for your first agent. The bottleneck on run one is your debugging, not your FLOPS.
The mistakes everyone makes once
A short list, so you can make them faster and move on. Reward shaping that teaches the wrong thing is the classic: a LunarLander agent rewarded for staying airborne learns to hover forever instead of landing — the reward was satisfied, the task was not. Training on the evaluation environment flatters the policy and hides overfitting. Changing five hyperparameters at once means you never learn which one mattered. Judging by one seed means you measured luck. And skipping the random baseline means you don't know whether your agent learned anything at all — a trained agent that barely beats random has a reward problem, not an algorithm problem.
How to try it yourself
An afternoon, a laptop, no GPU required:
- Run the CartPole recipe above, then try LunarLander-v3 with the same code — change one line, the environment name, and watch what breaks.
- Browse the classic-control environments in the directory for your second and third runs, and the Atari suite for your first pixel-observation run.
- Read OpenAI's Spinning Up (in our learn track) for the theory behind PPO once the code runs — it lands much better after you've seen the loop work.
- When the reward starts to matter more than the algorithm, read the reward model guide and the RLVR guide: the field's last four years have been a slow move from learned judges toward rewards you can verify.
- When you're ready to understand the algorithm itself, the GRPO guide explains what PPO's successor changed — group-relative advantages, no critic — and why.
Frequently asked questions
What is the simplest way to train an RL agent from scratch?
Install Gymnasium and Stable-Baselines3, make CartPole-v1, and run PPO on it. That is about 20 lines of code, a few minutes on a laptop CPU, and a solved pole by the end of it. The recipe is: pick one environment, pick one algorithm (PPO), train, then evaluate on a fresh copy of the environment — not the one you trained on.
Which algorithm should I start with?
PPO. It is stable, forgiving about hyperparameters, and works on both discrete and continuous action spaces, which is why nearly every tutorial and baseline uses it. DQN is the classic choice if your actions are discrete and you want to understand value-based learning; SAC is the usual pick for continuous control like robot arms. Do not start with the newest paper's algorithm — start with the one that has a thousand tutorials.
How long does it take to train an RL agent?
It depends entirely on the environment. CartPole solves in a few minutes on a laptop CPU. LunarLander takes tens of minutes. An Atari game from pixels can take hours on a GPU and days on a CPU, and a humanoid in MuJoCo longer still. The honest answer for a first agent: an afternoon, most of it spent debugging, not waiting on training.
Do I need a GPU to train an RL agent?
Not for your first agent. Classic control environments like CartPole and LunarLander train in minutes on any laptop CPU. A GPU starts to matter when observations are pixels — Atari, robotics from camera images — where it can cut hours to tens of minutes. A free Colab GPU is enough for that stage; do not buy hardware for your first agent.
Why is my RL agent not learning?
Usually for a boring reason, not an algorithmic one. The five usual suspects: the reward is uninformative or sparse; observations are unnormalized and on wildly different scales; episodes never end or the time limit is wrong; the learning rate is far off the default; or you evaluated on the training environment and fooled yourself. Check those before you touch the algorithm — and always compare against a random policy first, so you know what 'learning' would even look like.
What do you think?
What was the first agent you trained — and what finally made it click? Or what is yours stuck on right now? Tell us the environment and the symptom; the best debugging stories get featured in a future briefing.
The lab notebook is rlenvlab's blog — guides and the daily RL Briefing on the environments ecosystem. More from the lab notebook →