|
bitsim
Model, simulate, estimate and control robots in C++
|
Before an agent can improve a policy, it has to know how good the policy is. This example computes the value function of a policy on the 4x4 FrozenLake from Gymnasium. It is the first half of policy iteration, which Policy iteration on FrozenLake completes, and value iteration in Value iteration on FrozenLake builds on the same update.
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. The example makes the environment with its default options, so the lake is slippery: an action moves the agent in the intended direction only some of the time.
The value \(V_{\pi}(s)\) of a state is the return the agent expects from it when it follows the policy \(\pi\). It satisfies 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] . \]
Iterative policy evaluation starts from \(V = 0\) and sweeps over the states, replacing \(V(s)\) with the right hand side, until a sweep changes no value by more than a tolerance. It needs the transition probabilities and rewards \(p(s', r | s, \alpha)\), which FrozenLake provides.
The policy is a UniformDiscretePolicy, which picks each of the four actions with probability 1/4. IterativePolicyEvalutationSolver uses \(\gamma = 1\) and a tolerance of \(10^{-8}\). The example runs the sweeps itself, at most 10000 of them, rather than with RLSerialAgentTrainer, so that it can write the value function after every sweep to sweeps.csv. It stops once a sweep changes no value by more than the tolerance, after 57 sweeps.
The example writes the value of each state to iterative_policy_evaluation_frozen_lake.csv in the directory it runs from. plot.py draws it on the grid of the lake:
|
|---|
| Figure 1: The value of each state under the uniform random policy. |
The holes and the goal have a value of 0, because the episode ends there. The only reward is 1, for reaching the goal, so with \(\gamma = 1\) the value of a state is the probability that the random policy gets from it to the goal before it falls into a hole. From the start, in the top left corner, that is only about 1.4%. The state to the left of the goal has the largest value, 0.44.
|
|---|
| Figure 2: The value function sweep by sweep. The arrows are the greedy actions of the values. |
The values spread back from the goal one cell per sweep, and most of the 57 sweeps only refine them. examples/tools/value_gif.py draws sweeps.csv, with the arrows from FrozenLake's own transition model: