Path: blob/master/examples/rl/ipynb/ppo_cartpole.ipynb
3508 views
Proximal Policy Optimization
Author: Ilias Chrysovergis
Date created: 2021/06/24
Last modified: 2024/03/12
Description: Implementation of a Proximal Policy Optimization agent for the CartPole-v1 environment.
Introduction
This code example solves the CartPole-v1 environment using a Proximal Policy Optimization (PPO) agent.
CartPole-v1
A pole is attached by an un-actuated joint to a cart, which moves along a frictionless track. The system is controlled by applying a force of +1 or -1 to the cart. The pendulum starts upright, and the goal is to prevent it from falling over. A reward of +1 is provided for every timestep that the pole remains upright. The episode ends when the pole is more than 15 degrees from vertical, or the cart moves more than 2.4 units from the center. After 200 steps the episode ends. Thus, the highest return we can get is equal to 200.
Proximal Policy Optimization
PPO is a policy gradient method and can be used for environments with either discrete or continuous action spaces. It trains a stochastic policy in an on-policy way. Also, it utilizes the actor critic method. The actor maps the observation to an action and the critic gives an expectation of the rewards of the agent for the observation given. Firstly, it collects a set of trajectories for each epoch by sampling from the latest version of the stochastic policy. Then, the rewards-to-go and the advantage estimates are computed in order to update the policy and fit the value function. The policy is updated via a stochastic gradient ascent optimizer, while the value function is fitted via some gradient descent algorithm. This procedure is applied for many epochs until the environment is solved.
Note
This code example uses Keras and Tensorflow v2. It is based on the PPO Original Paper, the OpenAI's Spinning Up docs for PPO, and the OpenAI's Spinning Up implementation of PPO using Tensorflow v1.
Libraries
For this example the following libraries are used:
numpy
for n-dimensional arraystensorflow
andkeras
for building the deep RL PPO agentgymnasium
for getting everything we need about the environmentscipy.signal
for calculating the discounted cumulative sums of vectors
Functions and class
Hyperparameters
Initializations
Train
Visualizations
Before training:
After 8 epochs of training:
After 20 epochs of training: