bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
Expected SARSA on CliffWorld

This example trains an agent on CliffWalking from Gymnasium with expected SARSA. It has the same settings as SARSA on CliffWorld, which uses SARSA, so the two can be compared. The environment is CliffWorld, and it 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.

Expected SARSA

The agent walks on a 4 x 12 grid from the bottom left corner to the bottom right one. The cells between them along the bottom are a cliff: stepping onto it costs 100 and sends the agent back to the start. Every other step costs 1.

SARSA moves the value of the action it took towards the reward plus the value of the action it takes next,

\[Q(s_t, \alpha_t) \leftarrow Q(s_t, \alpha_t) + \eta \left[ r_{t+1} + \gamma Q(s_{t+1}, \alpha_{t+1}) - Q(s_t, \alpha_t) \right] . \]

The next action is random some of the time, so the target is noisy. Expected SARSA replaces the value of that one action by the value the policy expects at the next state, every action weighed with the probability the policy takes it:

\[Q(s_t, \alpha_t) \leftarrow Q(s_t, \alpha_t) + \eta \left[ r_{t+1} + \gamma \sum_{\alpha} \pi(\alpha | s_{t+1}) Q(s_{t+1}, \alpha) - Q(s_t, \alpha_t) \right] . \]

For the \(\epsilon\)-greedy policy the agent follows, with \(n\) actions, \(\pi(\alpha | s)\) is \(\epsilon / n\) for every action, plus \(1 - \epsilon\) for the greedy one, so the expected value is \(\epsilon\) times the mean of the values at \(s_{t+1}\) plus \(1 - \epsilon\) times the largest. ExpectedSarsaSolver computes it with the same greedy action as the policy, the first of the largest values, and asks the policy for its \(\epsilon\) every time, so a decaying \(\epsilon\) works too. After the step that ends an episode the target is the reward alone.

The target no longer depends on which action happens to come next, so the updates vary less than SARSA's, and expected SARSA can learn with a larger learning rate. With \(\epsilon = 0\) the policy is greedy, the expected value is the largest value, and expected SARSA is Q-learning.

Like SARSA, expected SARSA learns the value of the policy it follows, which explores. A random step taken from next to the cliff falls off it, so both learn to keep away from the cliff, while Q-learning, which learns the value of the greedy policy, takes the shortest path along its edge. The unit test test_td_cliff shows this on a 3 x 5 cliff walk: for every one of five seeds SARSA and expected SARSA go by the top row, and Q-learning along the edge.

Settings and what it writes

The policy is \(\epsilon\)-greedy with a constant \(\epsilon = 0.1\). The solver uses \(\gamma = 1\) and \(\eta = 0.5\), and RLSerialAgentTrainer runs 2000 episodes of at most 100 steps. In the directory it runs from, the example writes

File What
expected_sarsa_cliff_walking_v1.csv the value of every state and action, a column per action
reward_per_itr.csv the total reward of every training episode
policy.csv the greedy policy, the action to take in each state

The learned policy

The greedy policy Expected SARSA learned, played in Gymnasium: return -15.

The greedy policy of the table keeps one row away from the cliff and takes 15 steps, between SARSA and Q-learning. Like SARSA it values the policy it follows, but it averages over the actions that policy may take instead of following the one it took, which makes its estimates vary less. The example saves it to policy.csv; examples/tools/episode_gif.py plays it to make the GIF:

python examples/tools/episode_gif.py --env CliffWalking-v1 --policy policy.csv --out expected_sarsa.gif

The driver code

// Expected SARSA on Gymnasium's CliffWalking, with the same settings as
// example 15's SARSA so that the two can be compared
#include <any>
#include <iostream>
#include <string>
#include <tuple>
#include <unordered_map>
namespace example_26
{
const std::string SERVER_URL = "http://0.0.0.0:8001/api";
const std::string SOLUTION_FILE = "expected_sarsa_cliff_walking_v1.csv";
const std::string REWARD_PER_ITR = "reward_per_itr.csv";
const std::string POLICY = "policy.csv";
typedef ExpectedSarsaSolver<env_type, EpsilonGreedyPolicy> solver_type;
} // namespace example_26
int main()
{
using namespace example_26;
BITRL_LOG_INFO << "Starting agent training";
try
{
RESTRLEnvClient server(SERVER_URL, true);
env_type env(server);
BITRL_LOG_INFO << "Creating environment...";
std::unordered_map<std::string, std::any> options;
std::unordered_map<std::string, std::any> reset_options;
env.make("v1", options, reset_options);
env.reset();
BITRL_LOG_INFO << "Number of states=" << env.n_states();
BITRL_LOG_INFO << "Number of actions=" << env.n_actions();
// an epsilon-greedy policy with a constant epsilon, seeded with the
// number of actions, as in example 15
EpsilonGreedyPolicy policy(0.1, env.n_actions(), EpsilonDecayOption::NONE);
config.gamma = 1.0;
config.eta = 0.5;
config.path = SOLUTION_FILE;
solver_type solver(config, policy);
RLSerialTrainerConfig trainer_config = {10, 2000, 1.0e-8};
RLSerialAgentTrainer<env_type, solver_type> trainer(trainer_config, solver);
auto info = trainer.train(env);
BITRL_LOG_INFO << "Training info..." << info;
// the reward of every training episode
csv_writer.open();
csv_writer.write_column_names({"epoch", "reward"});
uint_t epoch = 0;
for (auto val : trainer.episodes_total_rewards())
{
csv_writer.write_row(std::tuple<uint_t, real_t>{epoch++, val});
}
csv_writer.close();
solver.build_policy().save(POLICY);
BITRL_LOG_INFO << "Finished agent training";
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
return 1;
}
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
The CliffWorld class.
Definition cliff_world_env.h:59
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
Tabular expected SARSA, see Sutton and Barto, Reinforcement Learning: An Introduction,...
Definition expected_sarsa.h:95
The EpsilonGreedyPolicy class.
Definition epsilon_greedy_policy.h:38
The CSVWriter class. Handles writing into CSV file format.
Definition csv_file_writer.h:22
int main()
Definition discounted_returns.cpp:19
EpsilonDecayOption
The EpsilonDecayOption enum. Enumerate various decaying options.
Definition epsilon_greedy_policy.h:27
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
Definition expected_sarsa.cpp:19
ExpectedSarsaSolver< env_type, EpsilonGreedyPolicy > solver_type
Definition expected_sarsa.cpp:37
const std::string SERVER_URL
Definition expected_sarsa.cpp:21
const std::string SOLUTION_FILE
Definition expected_sarsa.cpp:22
bitrl::envs::gymnasium::CliffWorld env_type
Definition expected_sarsa.cpp:36
const std::string REWARD_PER_ITR
Definition expected_sarsa.cpp:23
const std::string POLICY
Definition expected_sarsa.cpp:24
info
Definition play.py:49
The RLSerialTrainerConfig struct. Configuration struct for the serial RL agent trainer.
Definition rl_serial_agent_trainer.h:29
The configuration of ExpectedSarsaSolver.
Definition expected_sarsa.h:27
std::string path
Where to save the table when training ends; nothing is saved if it is not set.
Definition expected_sarsa.h:57
uint_t max_num_iterations_per_episode
The most steps an episode can take.
Definition expected_sarsa.h:51
real_t eta
The learning rate.
Definition expected_sarsa.h:46
real_t gamma
The discount factor.
Definition expected_sarsa.h:41