bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
Policy iteration on FrozenLake

This example solves the 4x4 FrozenLake environment from Gymnasium with policy iteration. The environment runs on the bitrl-rest-api server, which the example talks to over HTTP at http://0.0.0.0:8001/api, so start the server first.

Policy iteration is a dynamic programming method: it needs a model of the environment, the transition probabilities and rewards, which FrozenLake provides. Starting from a policy, it repeats two steps until the policy stops changing:

  • Policy evaluation. Compute the state value function \(V_{\pi}\) of the current policy \(\pi\) by sweeping over the states with the Bellman expectation equation \(V_{\pi}(s) = \sum_{\alpha} \pi(\alpha | s) \sum_{s', r} p(s', r | s, \alpha) \left[ r + \gamma V_{\pi}(s') \right]\).
  • Policy improvement. Make the policy greedy with respect to \(V_{\pi}\): in each state, pick the action with the largest expected return.

The example starts from a UniformDiscretePolicy, which picks every action with the same probability. PolicyIterationSolver uses \(\gamma = 1\) and runs 15 sweeps of policy evaluation, with a tolerance of \(10^{-8}\), in every iteration. The example runs the iterations itself, at most 100 of them, rather than with RLSerialAgentTrainer, so that it can write the value function after every iteration to sweeps.csv, and stops once policy improvement leaves the policy unchanged, after 4 iterations. The environment is made with its default options, so the lake is slippery: an action moves the agent in the intended direction only some of the time. The state value function is then saved to policy_iteration_frozen_lake_v0.csv.

plot.py draws the state value function on the 4x4 grid. It reads policy_iteration.csv, so rename the file the example writes or pass its name to main.

The results

The value function and the greedy policy after every iteration.

The greedy actions after the last iteration are optimal in every state: they are the actions of the largest value under the optimal value function, which value iteration on the same slippery lake gives. The values are not the optimal ones, 0.63 at the start where the optimal value is 0.82, because 15 sweeps of evaluation per iteration do not evaluate a policy fully; they are enough to rank the actions. The GIF is made with

python examples/tools/value_gif.py sweeps.csv --slippery --step iteration --out policy_iteration.gif

The driver code

#include <fstream>
#include <iostream>
#include <vector>
namespace rl_example_7
{
const std::string SERVER_URL = "http://0.0.0.0:8001/api";
const std::string SOLUTION_FILE = "policy_iteration_frozen_lake_v0.csv";
typedef FrozenLake<4> env_type;
} // namespace rl_example_7
int main()
{
BITRL_LOG_INFO << "Starting agent training";
using namespace rl_example_7;
RESTRLEnvClient server(SERVER_URL, true);
// create the environment
FrozenLake<4> env(server);
std::unordered_map<std::string, std::any> options;
std::unordered_map<std::string, std::any> reset_options;
BITRL_LOG_INFO << "Creating environment...";
env.make("v1", options, reset_options);
env.reset();
BITRL_LOG_INFO << "Done...";
UniformDiscretePolicy policy(env.n_states(), env.n_actions());
config.gamma = 1.0;
config.n_policy_eval_steps = 15;
config.tolerance = 1.0e-8;
solver_type solver(config, env.n_actions(), policy);
// output message frequence, number of episodes, tolerance
// the sweeps, as RLSerialAgentTrainer would run them, keeping the value
// function after every one in sweeps.csv, which examples/tools/value_gif.py
// draws
std::ofstream sweeps("sweeps.csv");
std::vector<real_t> reward;
solver.actions_before_training_begins(env);
for (uint_t sweep = 0; sweep < 100; ++sweep)
{
const auto sweep_info = solver.on_training_episode(env, sweep);
reward.push_back(sweep_info.episode_reward);
const auto values = solver.value_function();
sweeps << sweep;
for (Eigen::Index s = 0; s < values.size(); ++s)
{
sweeps << "," << values[s];
}
sweeps << "\n";
if (sweep_info.stop_training)
{
break;
}
}
solver.actions_after_training_ends(env);
BITRL_LOG_INFO << "Done after " << reward.size() << " sweeps";
BITRL_LOG_INFO << "Saving solution to " << SOLUTION_FILE;
// save the value function into a csv file
solver.save(SOLUTION_FILE);
BITRL_LOG_INFO << "Finished agent training";
return 0;
}
bitrl's logging: the logger of bitsim, bitsim/utils/logger.h, with bitrl's messages going to the logg...
#define BITRL_LOG_INFO
Definition bitrl_log.h:36
Definition frozen_lake_env.h:104
Utility class to facilitate HTTP requests between the environments REST API and C++ drivers.
Definition rest_rl_env_client.h:28
Definition rl_serial_agent_trainer.h:41
The policy iteration class.
Definition policy_iteration.h:35
The UniformDiscretePolicy class.
Definition uniform_discrete_policy.h:20
int main()
Definition discounted_returns.cpp:19
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
reward
Definition play.py:49
Definition policy_iteration.cpp:14
const std::string SOLUTION_FILE
Definition policy_iteration.cpp:17
const std::string SERVER_URL
Definition policy_iteration.cpp:16
FrozenLake< 4 > env_type
Definition policy_iteration.cpp:29
The RLSerialTrainerConfig struct. Configuration struct for the serial RL agent trainer.
Definition rl_serial_agent_trainer.h:29
The PolicyIterationConfig struct.
Definition policy_iteration.h:23
real_t tolerance
Definition policy_iteration.h:26
real_t gamma
Definition policy_iteration.h:25
uint_t n_policy_eval_steps
Definition policy_iteration.h:24