The Cross-Entropy Method
local graph
Chapter 4 — The Cross-Entropy Method
Section titled “Chapter 4 — The Cross-Entropy Method”In the last chapter, you learned about PyTorch. In this chapter, we will wrap up Part 1 of this book and you will become familiar with one of the reinforcement learning (RL) methods: cross-entropy.
Despite the fact that it is much less famous than other tools in the RL practitioner’s toolbox, such as deep Q-network (DQN) or advantage actor-critic (A2C), the cross-entropy method has its own strengths. Firstly, the cross-entropy method is really simple, which makes it an easy method to follow. For example, its implementation on PyTorch is less than 100 lines of code.
Secondly, the method has good convergence. In simple environments that don’t require you to learn complex, multistep policies and that have short episodes with frequent rewards, the cross-entropy method usually works very well. Of course, lots of practical problems don’t fall into this category, but sometimes they do. In such cases, the cross-entropy method (on its own or as part of a larger system) can be the perfect fit.
In this chapter, we will cover:
- The practical side of the cross-entropy method
- How the cross-entropy method works in two environments in Gym (the familiar CartPole and the grid world of FrozenLake)
- The theoretical background of the cross-entropy method. This section is optional and requires a bit of knowledge of probability and statistics, but if you want to understand why the method works, then you can delve into it.
The taxonomy of RL methods
Section titled “The taxonomy of RL methods”The cross-entropy method in practice
Section titled “The cross-entropy method in practice”The explanation of the cross-entropy method can be split into two unequal parts: practical and theoretical. The practical part is intuitive in nature, while the theoretical explanation of why the cross-entropy method works and what happens, is more sophisticated.
You may remember that the central and trickiest thing in RL is the agent, which tries to accumulate as much total reward as possible by communicating with the environment. In practice, we follow a common machine learning (ML) approach and replace all of the complications of the agent with some kind of nonlinear trainable function, which maps the agent’s input (observations from the environment) to some output. The details of the output that this function produces may depend on a particular method or a family of methods (such as value-based or policy-based methods), as described in the previous section. As our cross-entropy method is policy-based, our nonlinear function (neural network (NN)) produces the policy, which basically says for every observation which action the agent should take. In research papers, policy is denoted as π(a|s), where a are actions and s is the current state. This is illustrated in the following diagram:

Figure 4.1: A high-level approach to policy-based RL
In practice, the policy is usually represented as a probability distribution over actions, which makes it very similar to a classification problem, with the number of classes being equal to the number of actions we can carry out.
This abstraction makes our agent very simple: it needs to pass an observation from the environment to the NN, get a probability distribution over actions, and perform random sampling using the probability distribution to get an action to carry out. This random sampling adds randomness to our agent, which is a good thing because at the beginning of the training, when our weights are random, the agent behaves randomly. As soon as the agent gets an action to issue, it fires the action to the environment and obtains the next observation and reward for the last action. Then the loop continues, as shown in Figure 4.1.
During the agent’s lifetime, its experience is presented as episodes. Every episode is a sequence of observations that the agent has got from the environment, actions it has issued, and rewards for these actions. Imagine that our agent has played several such episodes. For every episode, we can calculate the total reward that the agent has claimed. It can be discounted or not discounted; for simplicity, let’s assume a discount factor of γ = 1, which just means an undiscounted sum of all local rewards for every episode. This total reward shows how good this episode was for the agent. It is illustrated in Figure 4.2, which contains four episodes (note that different episodes have different values for o i, a i, and r i):

Figure 4.2: Example episodes with their observations, actions, and rewards
Every cell represents the agent’s step in the episode. Due to randomness in the environment and the way that the agent selects actions to take, some episodes will be better than others. The core of the cross-entropy method is to throw away bad episodes and train on better ones. So, the steps of the method are as follows:
- Play N episodes using our current model and environment.
- Calculate the total reward for every episode and decide on a reward boundary. Usually, we use a percentile of all rewards, such as the 50th or 70th.
- Throw away all episodes with a reward below the boundary.
- Train on the remaining ”elite” episodes (with rewards higher than the boundary) using observations as the input and issued actions as the desired output.
- Repeat from step 1 until we become satisfied with the result.
So, that’s the cross-entropy method’s description. With the preceding procedure, our NN learns how to repeat actions, which leads to a larger reward, constantly moving the boundary higher and higher. Despite the simplicity of this method, it works well in basic environments, it’s easy to implement, and it’s quite robust against changing hyperparameters, which makes it an ideal baseline method to try. Let’s now apply it to our CartPole environment.
The cross-entropy method on CartPole
Section titled “The cross-entropy method on CartPole”The whole code for this example is in Chapter04/01_cartpole.py. Here, I will show only the most important parts. Our model’s core is a one-hidden-layer NN, with rectified linear unit (ReLU) and 128 hidden neurons (which is absolutely arbitrary; you can try to increase or decrease this constant – we’ve left this as an exercise for you). Other hyperparameters are also set almost randomly and aren’t tuned, as the method is robust and converges very quickly. We define constants at the top of the file:
import typing as ttimport torchimport torch.nn as nnimport torch.optim as optim
HIDDEN_SIZE = 128BATCH_SIZE = 16PERCENTILE = 70As shown in the preceding code, the constants include the count of neurons in the hidden layer, the count of episodes we play on every iteration (16), and the percentile of each episode’s total rewards that we use for elite episode filtering. We will take the 70th percentile, which means that we will keep the top 30% of episodes sorted by reward.
There is nothing special about our NN; it takes a single observation from the environment as an input vector and outputs a number for every action we can perform:
class Net(nn.Module): def __init__(self, obs_size: int, hidden_size: int, n_actions: int): super(Net, self).__init__() self.net = nn.Sequential( nn.Linear(obs_size, hidden_size), nn.ReLU(), nn.Linear(hidden_size, n_actions) )
def forward(self, x: torch.Tensor): return self.net(x)The output from the NN is a probability distribution over actions, so a straightforward way to proceed would be to include softmax nonlinearity after the last layer. However, in the code, we don’t apply softmax to increase the numerical stability of the training process. Rather than calculating softmax (which uses exponentiation) and then calculating cross-entropy loss (which uses a logarithm of probabilities), we will use the nn.CrossEntropyLoss PyTorch class later, which combines softmax and cross-entropy into a single, more numerically stable expression. CrossEntropyLoss requires raw, unnormalized values from the NN (also called logits). The downside of this is that we need to remember to apply softmax every time we need to get probabilities from our NN’s output.
Next, we will define two helper dataclasses:
@dataclassclass EpisodeStep: observation: np.ndarray action: int
@dataclassclass Episode: reward: float steps: tt.List[EpisodeStep]The purpose of these dataclasses is as follows:
- EpisodeStep: This will be used to represent one single step that our agent made in the episode, and it stores the observation from the environment and what action the agent performed. We will use episode steps from elite episodes as training data.
- Episode: This is a single episode stored as a total undiscounted reward and a collection of EpisodeStep.
Let’s look at a function that generates batches with episodes:
def iterate_batches(env: gym.Env, net: Net, batch_size: int) -> tt.Generator[tt.List[Episode], None, None]: batch = [] episode_reward = 0.0 episode_steps = [] obs, _ = env.reset() sm = nn.Softmax(dim=1)The preceding function accepts the environment (the Env class instance from the Gym library), our NN, and the count of episodes it should generate on every iteration. The batch variable will be used to accumulate our batch (which is a list of Episode instances). We also declare a reward counter for the current episode and its list of steps (the EpisodeStep objects). Then we reset our environment to obtain the first observation and create a softmax layer, which will be used to convert the NN’s output to a probability distribution of actions. That’s our preparations complete, so we are ready to start the environment loop:
while True: obs_v = torch.tensor(obs, dtype=torch.float32) act_probs_v = sm(net(obs_v.unsqueeze(0))) act_probs = act_probs_v.data.numpy()[0]At every iteration, we convert our current observation to a PyTorch tensor and pass it to the NN to obtain action probabilities. There are several things to note here:
- All nn.Module instances in PyTorch expect a batch of data items, and the same is true for our NN, so we convert our observation (which is a vector of four numbers in CartPole) into a tensor of size 1 × 4 (to achieve this, we call the unsqueeze(0) function on our tensor, which adds an extra dimension at the zero position of the shape).
- As we haven’t used nonlinearity at the output of our NN, it outputs raw action scores, which we need to feed through the softmax function.
- Both our NN and the softmax layer return tensors that track gradients, so we need to unpack this by accessing the tensor.data field and then converting the tensor into a NumPy array. This array will have the same two-dimensional structure as the input, with the batch dimension on axis 0, so we need to get the first batch element to obtain a one-dimensional vector of action probabilities.
Now that we have the probability distribution of actions, we can use it to obtain the actual action for the current step:
action = np.random.choice(len(act_probs), p=act_probs)next_obs, reward, is_done, is_trunc, _ = env.step(action)Here, we sample the distribution using NumPy’s function random.choice(). After this, we will pass this action to the environment to get our next observation, our reward, the indication of the episode ending, and the truncation flag. The last value returned by the step() function is extra information from the environment and is discarded.
The reward is added to the current episode’s total reward, and our list of episode steps is also extended with an (observation, action) pair:
episode_reward += float(reward)step = EpisodeStep(observation=obs, action=action)episode_steps.append(step)Note that we save the observation that was used to choose the action, but not the observation returned by the environment as a result of the action. These are the tiny, but important, details that you need to keep in mind.
The continuation of the code handles the situation when the current episode is over (in the case of CartPole, the episode ends when the stick has fallen down, despite our efforts, or when the time limit of the environment has been reached):
if is_done or is_trunc: e = Episode(reward=episode_reward, steps=episode_steps) batch.append(e) episode_reward = 0.0 episode_steps = [] next_obs, _ = env.reset() if len(batch) == batch_size: yield batch batch = []We append the finalized episode to the batch, saving the total reward (as the episode has been completed and we have accumulated all the rewards) and steps we have taken. Then we reset our total reward accumulator and clean the list of steps. After that, we reset our environment to start over.
If our batch has reached the desired count of episodes, we return it to the caller for processing using yield. Our function is a generator, so every time the yield operator is executed, the control is transferred to the outer iteration loop and then continues after the yield line. If you are not familiar with Python’s generator functions, refer to the Python documentation: https://wiki.python.org/moin/Generators. After processing, we will clean up the batch.
The last, but very important, step in our loop is to assign an observation obtained from the environment to our current observation variable:
obs = next_obsAfter that, everything repeats infinitely – we pass the observation to the NN, sample the action to perform, ask the environment to process the action, and remember the result of this processing.
One very important fact to understand in this function’s logic is that the training of our NN and the generation of our episodes are performed at the same time. They are not completely in parallel, but every time our loop accumulates enough episodes (16), it passes control to this function caller, which is supposed to train the NN using gradient descent. So, when yield is returned, the NN will have different, slightly better (we hope) behavior. As you should remember from the beginning of the chapter, the cross-entropy method is from the on-policy class, so using fresh training data is important for the method to work properly.
Since training and data gathering happen in the same thread, proper synchronization isn’t necessary. However, you should be aware of the frequent jumps between training the NN and using it. Okay; now we need to define yet another function, and then we will be ready to switch to the training loop:
def filter_batch(batch: tt.List[Episode], percentile: float) -> \ tt.Tuple[torch.FloatTensor, torch.LongTensor, float, float]: rewards = list(map(lambda s: s.reward, batch)) reward_bound = float(np.percentile(rewards, percentile)) reward_mean = float(np.mean(rewards))This function is at the core of the cross-entropy method – from the given batch of episodes and percentile value, it calculates a boundary reward, which is used to filter elite episodes to train on. To obtain the boundary reward, we will use NumPy’s percentile function, which, from the list of values and the desired percentile, calculates the percentile’s value. Then, we will calculate the mean reward, which is used only for monitoring.
Next, we will filter off our episodes:
train_obs: tt.List[np.ndarray] = []train_act: tt.List[int] = []for episode in batch: if episode.reward < reward_bound: continue train_obs.extend(map(lambda step: step.observation, episode.steps)) train_act.extend(map(lambda step: step.action, episode.steps))For every episode in the batch, we will check that the episode has a higher total reward than our boundary and, if it has, we will populate lists of observations and actions that we will train on.
The following is the final step of the function:
train_obs_v = torch.FloatTensor(np.vstack(train_obs))train_act_v = torch.LongTensor(train_act)return train_obs_v, train_act_v, reward_bound, reward_meanHere, we will convert our observations and actions from elite episodes into tensors, and return a tuple of four: observations, actions, the boundary of reward, and the mean reward. The last two values are not used in the training; we will write them into TensorBoard to check the performance of our agent.
Now, the final chunk of code that glues everything together, and mostly consists of the training loop, is as follows:
if __name__ == "__main__": env = gym.make("CartPole-v1") assert env.observation_space.shape is not None obs_size = env.observation_space.shape[0] assert isinstance(env.action_space, gym.spaces.Discrete) n_actions = int(env.action_space.n)
net = Net(obs_size, HIDDEN_SIZE, n_actions) print(net) objective = nn.CrossEntropyLoss() optimizer = optim.Adam(params=net.parameters(), lr=0.01) writer = SummaryWriter(comment="-cartpole")In the beginning, we create all the required objects: the environment, our NN, the objective function, the optimizer, and the summary writer for TensorBoard.
In the training loop, we iterate our batches (a list of Episode objects):
for iter_no, batch in enumerate(iterate_batches(env, net, BATCH_SIZE)): obs_v, acts_v, reward_b, reward_m = filter_batch(batch, PERCENTILE) optimizer.zero_grad() action_scores_v = net(obs_v) loss_v = objective(action_scores_v, acts_v) loss_v.backward() optimizer.step()We perform filtering of the elite episodes using the filter_batch function. The result is tensors of observations and taken actions, the reward boundary used for filtering, and the mean reward. After that, we zero the gradients of our NN and pass observations to the NN, obtaining its action scores. These scores are passed to the objective function, which will calculate the cross-entropy between the NN output and the actions that the agent took. The idea of this is to reinforce our NN to carry out those elite actions that have led to good rewards. Then, we calculate gradients on the loss and ask the optimizer to adjust our NN.
The rest of the loop is mostly the monitoring of progress:
print("%d: loss=%.3f, reward_mean=%.1f, rw_bound=%.1f" % ( iter_no, loss_v.item(), reward_m, reward_b))writer.add_scalar("loss", loss_v.item(), iter_no)writer.add_scalar("reward_bound", reward_b, iter_no)writer.add_scalar("reward_mean", reward_m, iter_no)On the console, we show the iteration number, the loss, the mean reward of the batch, and the reward boundary. We also write the same values to TensorBoard to get a nice chart of the agent’s learning performance.
The last check in the loop is the comparison of the mean rewards of our batch episodes:
if reward_m > 475: print("Solved!") breakwriter.close()When the mean reward becomes greater than 475, we stop our training. Why 475? In Gym, the CartPole-v1 environment is considered to be solved when the mean reward for the last 100 episodes is greater than 475. However, our method converges so quickly that 100 episodes are usually what we need. The properly trained agent can balance the stick for an infinitely long period of time (obtaining any amount of score), but the length of an episode in CartPole-v1 is limited to 500 steps (if you look in https://github.com/Farama-Foundation/Gymnasium/blob/main/gymnasium/envs/\_\_init\_\_.py (gymnasium/envs/__init__.py) where all the environments are registered, v1 of Cartpole has max_episode_steps=500). With all this in mind, we will stop training after the mean reward in the batch is greater than 475, which is a good indication that our agent knows how to balance the stick like a pro.
That’s it. So, let’s start our first RL training!
Chapter04$ ./01_cartpole.pyNet( (net): Sequential( (0): Linear(in_features=4, out_features=128, bias=True) (1): ReLU() (2): Linear(in_features=128, out_features=2, bias=True) ))0: loss=0.683, reward_mean=25.2, rw_bound=24.01: loss=0.669, reward_mean=34.3, rw_bound=39.02: loss=0.648, reward_mean=37.6, rw_bound=40.03: loss=0.647, reward_mean=41.9, rw_bound=43.04: loss=0.634, reward_mean=41.2, rw_bound=50.0....38: loss=0.537, reward_mean=431.8, rw_bound=500.039: loss=0.529, reward_mean=450.1, rw_bound=500.040: loss=0.533, reward_mean=456.4, rw_bound=500.041: loss=0.526, reward_mean=422.0, rw_bound=500.042: loss=0.531, reward_mean=436.8, rw_bound=500.043: loss=0.526, reward_mean=475.5, rw_bound=500.0Solved!It usually doesn’t take the agent more than 50 batches to solve the problem. My experiments show something from 30 to 60 episodes, which is a really good learning performance (remember, we need to play only 16 episodes for every batch). TensorBoard shows that our agent is consistently making progress, pushing the upper boundary at almost every batch (there are some periods of rolling down, but most of the time it improves):

Figure 4.3: Mean reward (left) and loss (right) during the training
Figure 4.4: The reward boundary during the training
To monitor the training process, you can tweak the environment creation by setting the rendering mode in the CartPole environment and adding a RecordVideo wrapper:
env = gym.make("CartPole-v1", render_mode="rgb_array")env = gym.wrappers.RecordVideo(env, video_folder="video")During the training, it will create a video directory with a bunch of MP4 movies inside, allowing you to compare the progress of agent training:
Chapter04$ ./01_cartpole.pyNet( (net): Sequential( (0): Linear(in_features=4, out_features=128, bias=True) (1): ReLU() (2): Linear(in_features=128, out_features=2, bias=True) ))Moviepy - Building video Chapter04/video/rl-video-episode-0.mp4.Moviepy - Writing video Chapter04/video/rl-video-episode-0.mp4Moviepy - Done !Moviepy - video ready Chapter04/video/rl-video-episode-0.mp4Moviepy - Building video Chapter04/video/rl-video-episode-1.mp4.Moviepy - Writing video Chapter04/video/rl-video-episode-1.mp4...The MP4 movies might look like the following:

Figure 4.5: CartPole episode movie
Let’s now pause for a bit and think about what’s just happened. Our NN has learned how to play the environment purely from observations and rewards, without any interpretation of observed values. The environment could easily not be a cart with a stick; it could be, say, a warehouse model with product quantities as an observation and money earned as the reward. Our implementation doesn’t depend on environment-related details. This is the beauty of the RL model and, in the next section, we will look at how exactly the same method can be applied to a different environment from the Gym collection.
The cross-entropy method on FrozenLake
Section titled “The cross-entropy method on FrozenLake”The next environment that we will try to solve using the cross-entropy method is FrozenLake. Its world is from the so-called grid world category, when your agent lives in a grid of size 4 × 4 and can move in four directions: up, down, left, and right. The agent always starts at the top left, and its goal is to reach the bottom-right cell of the grid. There are holes in the fixed cells of the grid and if you get into those holes, the episode ends and your reward is zero. If the agent reaches the destination cell, then it obtains a reward of 1.0 and the episode ends.
To make life more complicated, the world is slippery (it’s a frozen lake after all), so the agent’s actions do not always turn out as expected – there is a 33% chance that it will slip to the right or to the left. If you want the agent to move left, for example, there is a 33% probability that it will, indeed, move left, a 33% chance that it will end up in the cell above, and a 33% chance that it will end up in the cell below. As you will see at the end of the section, this makes progress difficult.

Figure 4.6: The FrozenLake environment rendered in human mode
Let’s look at how this environment is represented in the Gym API:
>>> e = gym.make("FrozenLake-v1", render_mode="ansi")>>> e.observation_spaceDiscrete(16)>>> e.action_spaceDiscrete(4)>>> e.reset()(0, {’prob’: 1})>>> print(e.render())
SFFFFHFHFFFHHFFGOur observation space is discrete, which means that it’s just a number from 0 to 15 inclusive. Obviously, this number is our current position in the grid. The action space is also discrete, but it can be from zero to three. Although the action space is similar to CartPole, the observation space is represented in a different way. To minimize the required changes in our implementation, we can apply the traditional one-hot encoding of discrete inputs, which means that the input to our network will have 16 float numbers and zero everywhere, except the index that we will encode (representing our current position on the grid).
As this transformation only affects the observation of the environment, it could be implemented as an ObservationWrapper, as we discussed in Chapter 2. Let’s call it DiscreteOneHotWrapper:
class DiscreteOneHotWrapper(gym.ObservationWrapper): def __init__(self, env: gym.Env): super(DiscreteOneHotWrapper, self).__init__(env) assert isinstance(env.observation_space, gym.spaces.Discrete) shape = (env.observation_space.n, ) self.observation_space = gym.spaces.Box(0.0, 1.0, shape, dtype=np.float32)
def observation(self, observation): res = np.copy(self.observation_space.low) res[observation] = 1.0 return resWith that wrapper applied to the environment, both the observation space and action space are 100% compatible with our CartPole solution (source code Chapter04/02_frozenlake_naive.py). However, by launching it, we can see that our training process doesn’t improve the score over time:

Figure 4.7: Mean reward (left) and loss (right) on the FrozenLake environment

Figure 4.8: The reward boundary during the training (boring 0.0 all the time)
To understand what’s going on, we need to look deeper at the reward structure of both environments. In CartPole, every step of the environment gives us the reward 1.0, until the moment that the pole falls. So, the longer our agent balanced the pole, the more reward it obtained. Due to randomness in our agent’s behavior, different episodes were of different lengths, which gave us a pretty normal distribution of the episodes’ rewards. After choosing a reward boundary, we rejected less successful episodes and learned how to repeat better ones (by training on successful episodes’ data). This is shown in the following diagram:

Figure 4.9: Distribution of the reward in the CartPole environment
In the FrozenLake environment, episodes and their rewards look different. We get the reward of 1.0 only when we reach the goal, and this reward says nothing about how good each episode was. Was it quick and efficient, or did we make four rounds on the lake before we randomly stepped into the final cell? We don’t know; it’s just a 1.0 reward and that’s it. The distribution of rewards for our episodes is also problematic. There are only two kinds of episodes possible, with zero reward (failed) and one reward (successful), and failed episodes will obviously dominate at the beginning of the training, when the agent acts randomly. So, our percentile selection of elite episodes is totally wrong and gives us bad examples to train on. This is the reason for our training failure.

Figure 4.10: Reward distribution of the FrozenLake environment
This example shows us the limitations of the cross-entropy method:
- For training, our episodes have to be finite (in general, they could be infinite) and, preferably, short
- The total reward for the episodes should have enough variability to separate good episodes from bad ones
- It is beneficial to have an intermediate reward during the episode instead of having the reward at the end of the episode
Later in the book, you will become familiar with other methods that address these limitations. For now, if you are curious about how FrozenLake can be solved using the cross-entropy method, here is a list of tweaks of the code that you need to make (the full example is in Chapter04/03_frozenlake_tweaked.py):
- Larger batches of played episodes: In CartPole, it was sufficient to have 16 episodes on every iteration, but FrozenLake requires at least 100 just to get some successful episodes.
- Discount factor applied to the reward: To make the total reward for an episode depend on its length, and to add variety in episodes, we can use a discounted total reward with the discount factor γ = 0.9 or 0.95. In this case, the reward for short episodes will be higher than the reward for long ones. This increases variability in reward distribution, which helps to avoid situations like the one shown in Figure 4.10.
- Keeping elite episodes for a longer time: In the CartPole training, we sampled episodes from the environment, trained on the best ones, and threw them away. In FrozenLake, a successful episode is a much rarer animal, so we need to keep them for several iterations to train on them.
- Decreasing the learning rate: This will give our NN time to average more training samples, as a smaller learning rate decreases the effect of new data on the model.
- Much longer training time: Due to the sparsity of successful episodes and the random outcome of our actions, it’s much harder for our NN to get an idea of the best behavior to perform in any particular situation. To reach 50% successful episodes, about 5,000 training iterations are required.
To incorporate all these into our code, we need to change the filter_batch function to calculate the discounted reward and return elite episodes for us to keep:
def filter_batch(batch: tt.List[Episode], percentile: float) -> \ tt.Tuple[tt.List[Episode], tt.List[np.ndarray], tt.List[int], float]: reward_fun = lambda s: s.reward * (GAMMA ** len(s.steps)) disc_rewards = list(map(reward_fun, batch)) reward_bound = np.percentile(disc_rewards, percentile)
train_obs: tt.List[np.ndarray] = [] train_act: tt.List[int] = [] elite_batch: tt.List[Episode] = []
for example, discounted_reward in zip(batch, disc_rewards): if discounted_reward > reward_bound: train_obs.extend(map(lambda step: step.observation, example.steps)) train_act.extend(map(lambda step: step.action, example.steps)) elite_batch.append(example)
return elite_batch, train_obs, train_act, reward_boundThen, in the training loop, we will store previous elite episodes to pass them to the preceding function on the next training iteration:
full_batch = []for iter_no, batch in enumerate(iterate_batches(env, net, BATCH_SIZE)): reward_mean = float(np.mean(list(map(lambda s: s.reward, batch)))) full_batch, obs, acts, reward_bound = filter_batch(full_batch + batch, PERCENTILE) if not full_batch: continue obs_v = torch.FloatTensor(obs) acts_v = torch.LongTensor(acts) full_batch = full_batch[-500:]The rest of the code is the same, except that the learning rate decreased 10 times and the BATCH_SIZE was set to 100. After a period of patient waiting (the new version takes about 50 minutes to finish 10,000 iterations), you can see that the training of the model stopped improving at around 55% of solved episodes:

Figure 4.11: Mean reward (left) and loss (right) of the tweaked version

Figure 4.12: The reward boundary of the tweaked version
There are ways to address this (by applying entropy loss regularization, for example), but those techniques will be discussed in upcoming chapters.
The final point to note here is the effect of slipperiness in the FrozenLake environment. Each of our actions, with 33% probability, is replaced with the 90 ∘ rotated action (the up action, for instance, will succeed with a 0.33 probability, and there will be a 0.33 chance that it will be replaced with the left action and a 0.33 chance with the right action).
The nonslippery version is in Chapter04/04_frozenlake_nonslippery.py, and the only difference is in the environment creation:
env = DiscreteOneHotWrapper(gym.make("FrozenLake-v1", is_slippery=False))The effect is dramatic! The nonslippery version of the environment can be solved in 120-140 batch iterations, which is 100 times faster than the noisy environment:
Chapter04$ ./04_frozenlake_nonslippery.py2: loss=1.436, rw_mean=0.010, rw_bound=0.000, batch=13: loss=1.410, rw_mean=0.010, rw_bound=0.000, batch=24: loss=1.391, rw_mean=0.050, rw_bound=0.000, batch=75: loss=1.379, rw_mean=0.020, rw_bound=0.000, batch=96: loss=1.375, rw_mean=0.010, rw_bound=0.000, batch=107: loss=1.367, rw_mean=0.040, rw_bound=0.000, batch=148: loss=1.361, rw_mean=0.000, rw_bound=0.000, batch=149: loss=1.356, rw_mean=0.010, rw_bound=0.000, batch=15...134: loss=0.308, rw_mean=0.730, rw_bound=0.478, batch=93136: loss=0.440, rw_mean=0.710, rw_bound=0.304, batch=70137: loss=0.298, rw_mean=0.720, rw_bound=0.478, batch=106139: loss=0.337, rw_mean=0.790, rw_bound=0.430, batch=65140: loss=0.295, rw_mean=0.720, rw_bound=0.478, batch=99142: loss=0.433, rw_mean=0.670, rw_bound=0.000, batch=67143: loss=0.287, rw_mean=0.820, rw_bound=0.478, batch=114Solved!This is also evident from the following graphs:

Figure 4.13: Mean reward (left) and loss (right) of the nonslippery version

Figure 4.14: The reward boundary of the nonslippery version
The theoretical background of the cross-entropy method
Section titled “The theoretical background of the cross-entropy method”This section is optional and is included for readers who want to understand why the method works. If you wish, you can refer to the original paper by Kroese, titled Cross-entropy method, [Kro+11].
The basis of the cross-entropy method lies in the importance sampling theorem, which states this:
![π (a |s) = P[At = a|St = s]](https://static.packt-cdn.com/products/9781835882702/graphics/Images/eq4.png)
In our RL case, H(x) is a reward value obtained by some policy x, and p(x) is a distribution of all possible policies. We don’t want to maximize our reward by searching all possible policies; instead, we want to find a way to approximate p(x)H(x) by q(x), iteratively minimizing the distance between them. The distance between two probability distributions is calculated by Kullback-Leibler (KL) divergence, which is as follows:
![π (a |s) = P[At = a|St = s]](https://static.packt-cdn.com/products/9781835882702/graphics/Images/eq6.png)
The first term in KL is called entropy and it doesn’t depend on p 2 (x), so it could be omitted during the minimization. The second term is called cross-entropy, which is a very common optimization objective in deep learning.
Combining both formulas, we can get an iterative algorithm, which starts with q 0 (x) = p(x) and on every step improves. This is an approximation of p(x)H(x) with an update:
![π (a |s) = P[At = a|St = s]](https://static.packt-cdn.com/products/9781835882702/graphics/Images/eq78.png)
This is a generic cross-entropy method that can be significantly simplified in our RL case. We replace our H(x) with an indicator function, which is 1 when the reward for the episode is above the threshold and 0 when the reward is below. Our policy update will look like this:
![π (a |s) = P[At = a|St = s]](https://static.packt-cdn.com/products/9781835882702/graphics/Images/eq79.png)
Strictly speaking, the preceding formula misses the normalization term, but it still works in practice without it. So, the method is quite clear: we sample episodes using our current policy (starting with some random initial policy) and minimize the negative log likelihood of the most successful samples and our policy.
If you are interested, refer to the book written by Reuven Rubinstein and Dirk P. Kroese [RK04] that is dedicated to this method. A shorter description can be found in the Cross-entropy method paper ([Kro+11]).
Summary
Section titled “Summary”In this chapter, you became familiar with the cross-entropy method, which is simple but quite powerful, despite its limitations. We applied it to a CartPole environment (with huge success) and to FrozenLake (with much more modest success). In addition, we discussed the taxonomy of RL methods, which will be referenced many times during the rest of the book, as different approaches to RL problems have different properties, which influences their applicability.
This chapter ends the introductory part of the book. In the next part, we will switch to a more systematic study of RL methods and discuss the value-based family of methods. In upcoming chapters, we will explore more complex, but more powerful, tools of deep RL.