concept CartPole in category deep learning

This is an excerpt from Manning's book Deep Reinforcement Learning in Action.
To be concrete, let’s say the current state is S5 (the state at time step 5). We input that into the policy network and it returns Pθ(A|s5) = [0.25,0.75]. We sample from this distribution and take action a = 1 (the second element in the action array), and after this the pole falls over and the episode has ended. The total duration of the episode was T = 5. For each of these 5 time steps, we took an action according to Pθ(A|st) and we stored the specific probabilities of the actions that were actually taken, Pθ(a|st), in an array, which might look like [0.5, 0.3, 0.25, 0.5, 0.75]. We simply multiply these probabilities by the discounted rewards (explained in the next section), take the sum, multiply it by –1, and call that our overall loss for this episode. Unlike Gridworld, in CartPole the last action is the one that loses the episode; we discount it the most since we want to penalize the worst move the most. In Gridworld we would do the opposite and discount the first action in the episode most, since it would be the least responsible for winning or losing.
Let’s see how this evolution strategy works in a simple reinforcement learning example. We’re going to use an evolutionary process to optimize an agent to play CartPole, the environment we introduced in chapter 4 where the agent is rewarded for keeping the pole upright (figure 6.7).
Putting it all together, we can train a population of agents to play CartPole in just a handful of generations. You should experiment with the hyperparameters of mutation rate, population size, and number of generations.
Listing 6.13. Training the models
num_generations = 25 #1 population_size = 500 #2 mutation_rate = 0.01 pop_fit = [] pop = spawn_population(N=population_size,size=407) #3 for i in range(num_generations): pop, avg_fit = evaluate_population(pop) #4 pop_fit.append(avg_fit) pop = next_generation(pop, mut_rate=mutation_rate,tournament_size=0.2) #5The first generation begins with a population of random parameter vectors, but by chance some of these will be better than the others, and we preferentially select these to mate and produce offspring for the next generation. To maintain genetic diversity, we allow each individual to be mutated slightly. This process repeats until we have individuals who are exceptionally good at playing CartPole. You can see in figure 6.9 that the score steadily increases each generation of evolution.