bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
First visit Monte Carlo on FrozenLake

Iterative policy evaluation on FrozenLake computed the value function of a policy on FrozenLake with iterative policy evaluation, which needs the transition probabilities of the environment. Monte Carlo methods need no model. They estimate the value of a state from the returns that follow it in episodes the agent plays. This example estimates the value function of a random policy on the 4x4 FrozenLake from Gymnasium with first visit Monte Carlo.

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. It is made with its default options, so the lake is slippery.

First visit Monte Carlo

In every training episode the solver plays an episode, a trajectory of at most max_steps = 200 steps, and walks through it. The first time it meets a state \(s\) in the trajectory, it computes the return \(G\) from that step to the end of the trajectory and moves the value of the state towards it,

\[V(s) \leftarrow V(s) + \alpha \left[ G - V(s) \right] . \]

Later visits to the same state in the same trajectory are skipped; that is what makes it first visit. Every visit Monte Carlo would update the value at each of them.

FirstVisitMCSolver takes three types from the example:

  • TrajectoryGenerator plays a trajectory with bitrl::envs::create_trajectory, picking every action with RandomActionSelector, which draws one of the four actions uniformly.
  • InverseDecayLRScheduler decays the learning rate from the solver's initial value, 0.5, as \(\alpha_k = 0.5 / (1 + k / 100)\) in episode \(k\), but not below 0.001.
  • DiscountGenerator gives the discount of each step of the trajectory. It returns \(1^k = 1\) for every step, so the rewards are not discounted.

The example runs 10000 training episodes itself, as RLSerialAgentTrainer would, so that it can write the value function every 200 episodes to sweeps.csv.

What it writes

At the end the example writes the value of each state to first_visit_mc_frozen_lake.csv in the directory it runs from. It estimates the same quantity as Iterative policy evaluation on FrozenLake, the value function of the uniform random policy, so the two can be compared. With a constant \(\alpha = 0.5\) the estimates would follow the latest returns and stay noisy; with the decaying rate they average more of them and settle.

The value estimates every 200 episodes, with the greedy actions of the estimates.

After 10000 episodes the start has an estimate of 0.017 and the cell left of the goal 0.49, against the true values of 0.014 and 0.44 that Iterative policy evaluation on FrozenLake computes: estimates from sampled returns, close but not exact. The GIF is made with

python examples/tools/value_gif.py sweeps.csv --slippery --step episode --out first_visit_monte_carlo.gif

The driver code

#include <fstream>
#include <iostream>
#include <random>
namespace example_22
{
const std::string SERVER_URL = "http://0.0.0.0:8001/api";
const uint_t SEED = 42;
struct RandomActionSelector
{
template <typename StateType>
FrozenLake<4>::action_type operator()(const StateType state) const;
};
// One generator for the whole run. A generator made in every call would
// start from the same seed each time and always pick the same action.
std::mt19937 generator(SEED);
template <typename StateType>
{
// FrozenLake has 4 actions, 0 to 3
std::uniform_int_distribution<> action_dist(0, 3);
return action_dist(generator);
}
{
std::vector<FrozenLake<4>::time_step_type> operator()(FrozenLake<4> &, uint_t max_steps);
};
std::vector<FrozenLake<4>::time_step_type> TrajectoryGenerator::operator()(FrozenLake<4> &env,
uint_t max_steps)
{
RandomActionSelector action_selector;
return bitrl::envs::create_trajectory(env, action_selector, max_steps);
}
{
template <typename TrajectoryType>
std::vector<real_t> operator()(const TrajectoryType &, uint_t max_steps);
};
template <typename TrajectoryType>
std::vector<real_t> DiscountGenerator::operator()(const TrajectoryType &, uint_t max_steps)
{
return bitrl::maths::logspace(0.0, static_cast<real_t>(max_steps), max_steps, 1.0);
}
// alpha / (1 + episode / 100), from the solver's initial 0.5: a constant learning rate
// would keep the estimates moving with every return
} // namespace example_22
int main()
{
using namespace example_22;
RESTRLEnvClient server(SERVER_URL, true);
// create the environment
FrozenLake<4> env(server);
std::cout << "Environment URL: " << env.get_url() << std::endl;
std::unordered_map<std::string, std::any> options;
std::unordered_map<std::string, std::any> reset_options;
std::cout << "Creating the environment..." << std::endl;
env.make("v1", options, reset_options);
env.reset();
std::cout << "Done..." << std::endl;
config.max_steps = 200;
trajectory_generator_type trajectory_generator;
discount_generator_type discount_generator;
solver_type solver(config, trajectory_generator, lr_scheduler, discount_generator);
// the episodes, as RLSerialAgentTrainer would run them, keeping the value
// function every 200 episodes in sweeps.csv, which
// examples/tools/value_gif.py draws
const uint_t N_EPISODES = 10000;
std::ofstream sweeps("sweeps.csv");
solver.actions_before_training_begins(env);
for (uint_t episode = 0; episode < N_EPISODES; ++episode)
{
const auto info = solver.on_training_episode(env, episode);
solver.actions_after_episode_ends(env, episode, info);
if ((episode + 1) % 200 == 0)
{
const auto values = solver.value_function();
// the episode, from 0, as the sweeps of the other examples
sweeps << episode;
for (Eigen::Index s = 0; s < values.size(); ++s)
{
sweeps << "," << values[s];
}
sweeps << "\n";
}
}
solver.actions_after_training_ends(env);
// the value of each state under the random policy
solver.save("first_visit_mc_frozen_lake.csv");
return 0;
}
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
Definition first_visit_mc.h:47
The EpsilonGreedyPolicy class.
Definition epsilon_greedy_policy.h:38
base_type::action_type action_type
The type of the action to be undertaken in the environment.
Definition frozen_lake_env.h:146
int main()
Definition discounted_returns.cpp:19
std::vector< typename EnvType::time_step_type > create_trajectory(EnvType &env, ActionSelector &action_selector, uint_t max_steps)
Definition envs_utils.h:27
std::vector< real_t > logspace(real_t start, real_t end, uint_t num, real_t base=10.0)
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
Definition first_visit_monte_carlo.cpp:17
FirstVisitMCSolverConfig solver_config_type
Definition first_visit_monte_carlo.cpp:82
DiscountGenerator discount_generator_type
Definition first_visit_monte_carlo.cpp:83
std::mt19937 generator(SEED)
InverseDecayLRScheduler learning_rate_scheduler_type
Definition first_visit_monte_carlo.cpp:81
FrozenLake< 4 > env_type
Definition first_visit_monte_carlo.cpp:77
TrajectoryGenerator trajectory_generator_type
Definition first_visit_monte_carlo.cpp:78
const uint_t SEED
Definition first_visit_monte_carlo.cpp:31
const std::string SERVER_URL
Definition first_visit_monte_carlo.cpp:30
FirstVisitMCSolver< env_type, trajectory_generator_type, learning_rate_scheduler_type, discount_generator_type > solver_type
Definition first_visit_monte_carlo.cpp:86
info
Definition play.py:49
env
Definition play.py:33
list values
Definition plot_losses.py:13
uint_t N_EPISODES
Definition multi_armed_bandits.cpp:34
struct InverseDecayLRScheduler. Decays the learning rate it was given with the episodes,...
Definition learning_rate_scheduler.h:32
The RLSerialTrainerConfig struct. Configuration struct for the serial RL agent trainer.
Definition rl_serial_agent_trainer.h:29
uint_t max_steps
Definition first_visit_mc.h:36
Definition first_visit_monte_carlo.cpp:65
std::vector< real_t > operator()(const TrajectoryType &, uint_t max_steps)
Definition first_visit_monte_carlo.cpp:72
FrozenLake< 4 >::action_type operator()(const StateType state) const
Definition first_visit_monte_carlo.cpp:44
Definition first_visit_monte_carlo.cpp:52
std::vector< FrozenLake< 4 >::time_step_type > operator()(FrozenLake< 4 > &, uint_t max_steps)
Definition first_visit_monte_carlo.cpp:56