Artificial Intelligence

Snake with Policy Gradients Deep Reinforcement Learning

Policy gradients deep reinforcement learning applied to a snake game

Vincent Mueller
August 23, 20218 min read
GIF by author
GIF by author

Introduction

Policy Gradient Methods are used to achieve state of the art results in the research field of deep reinforcement learning. In this Post I will go into the simplest of policy gradients methods, the "REINFORCE" algorithm, and will show how you how well it performs in the task of learning to play the game of snake. I will present the following topics:

  • A gentle introduction into my setup and the terminology

  • Explanation of how the REINFORCE algorithm works

  • Results of the algorithm playing snake

  • Python code of the snake game and the REINFORCE algorithm

Concepts

State

The state 𝑠(𝑑) is the state of an agent at a timepoint 𝑑. In our case, the state of our snake contains information about:

  • The direction of the apple relative to the snake in one-hot encoding

  • The direction the snake is currently moving in one-hot encoding

  • If there is an obstacle directly (a wall or the body of the snake) above the snakes head (0 or 1) (directly means with distance of 1)

  • If there is an obstacle directly below the snakes head (0 or 1)

  • If there is an obstacle directly to the left of the snakes head (0 or 1)

  • If there is an obstacle directly to the right of the snakes head (0 or 1)

In one-hot encoding we express integers as vectors of binaries. We have four directions: up (0), down (1) , left (2) and right (3). The same directions in one-hot encoding:

  • [1,0,0,0] for up

  • [0,1,0,0] for down

  • [0,0,1,0] for left

  • [0,0,0,1] for right

We use one-hot encoding because we use a neural network for estimating the policy function and it's and advantage for training when the input is scaled between 0 and 1.

The whole state is organised in a column vector. For example: The apple is above the snake and the snake is moving down. There is the tail of the snake directly to the left of the snake. The state vector s(t) would look like this:

Image by author
Image by author

Note that with this state vector, the snake only perceives obstacles to the left, right, above and below. It does not perceive obstacles diagonal to it's position.

Actions

There are four possible actions for the snake:

  • Move up

  • Move down

  • Move Left

  • Move Right

This implies that the snake can also move into its own tail:

If the snake would move up in this situation, it would die. (Image by author)
If the snake would move up in this situation, it would die. (Image by author)

Reward

A reward is given in the following way:

  • Eating an apple: +100

  • Dying: -10

  • Moving closer to the apple: +1

  • Moving away from the apple: -1

Policy

The policy is denoted by πœ‹. It outputs the probability of an action for our snake agent given the state 𝑠(𝑑) and the parameters πœƒ. In our case, the parameters are the weights of a vanilla deep neural network. To choose an action we sample from a discrete probability distribution using the probabilities given by πœ‹. It means that we never have a deterministic policy and choose suboptimal actions with a certain probability. This also ensures sufficient exploration of the agent. The learning process should decrease the probability of bad actions and increase the probability of wanted actions.

How the policy could look like after 100 training episodes
How the policy could look like after 100 training episodes

Return

The goal of the agent is to maximize the total rewards it receives during an episode. An episode is simply one game. At each timestep 𝑑 we want to maximize the expected total reward in the future. At first this can be a little confusing. Why not adjusting our policy to maximize the reward our snake would have achieved in the past? Let's look at it this way: If we are at a particular timestep, we should perform the action, that puts us in the position of receiving the most reward in the future.

The policy is updated at the end of an episode. This is when the snake dies. For each timestep, we know what the reward the snake received in the next timesteps was. So we can define the return 𝐺. It is a discounted or undiscounted sum of the future rewards. In our case, we choose to introduce the discount factor 𝛾, because reward in the distant future comes with uncertainty. In vanilla policy gradients, 𝛾 is usually 0.99. A 𝛾 of 1 would mean, that it would be undiscounted and a lower gamma would mean that our agent becomes more focused on immediate reward.

The return function (Image by author)
The return function (Image by author)

Timestep 𝑇 is the last timestep of the episode. In our case this would mean the timestep where the snake dies.

Loss

We use gradient descent to train our neural network/policy function. The Loss can be calculated in the following way:

Loss function of our neural network (Image by author)
Loss function of our neural network (Image by author)

The loss is pretty intuitive. We want to maximise the probability of taking actions with a high return 𝐺. We have a minus in front of the loss, this means that we do gradient ascent. When we do gradient descent on the policy with respect to this loss, it means we increase the probability output at a timestep, if there is a high return at this timestep. The log here comes from the fact that it is easier to take partial derivatives with respect to a sum, than with respect to a multiplication and the log converts products into sums. But the log does not change the mean of the equation.

Gradient ascent

The weights get updated in the following way. It is the same algorithm used like for updating neural network weights, but it is gradient ascent instead of descent. The following formula is obtained by taking the partial derivatives of the Loss function with respect to the weights of our neural network. In practice, we use a autograd framework like tensorflow or pytorch and therefore only need to know the loss function.

Image by author
Image by author

Here, πœ† is the learning rate of the network.

Pseudocode

The full algorithm is shown in the pseudocode below. We can see that the weights of the neural network are updated after each episode

The final REINFORCE algorithm (Image by author)
The final REINFORCE algorithm (Image by author)

Results

10 episodes

The agent has not yet realised how to play the game.

GIF by author
GIF by author

100 episodes

The agent has learned to play the game, but there is still some probability that the agent takes a suboptimal action and ends up killing itself.

GIF by author
GIF by author

552 episodes

The agent plays the game pretty well and achieves a very high score.

GIF by author
GIF by author

1000 episodes

The agent has managed to beat the previous highscore. But the variance in the scores is very high.

GIF by author
GIF by author

In this GIF, the snake kills itself by enclosing itself in its tail in a way, that it hardly can avoid, because it does not perceive its tail, diagonal to the heads position.

The trap that is not visible to the snake in the actual setting (Image by author)
The trap that is not visible to the snake in the actual setting (Image by author)

This problem could be overcome, if we would an input feature for diagonal variables in our state vector.

2852 episodes

After 2852 episodes, The agent achieved its highest score for the entire training of 9000 episodes. The following GIF shows us the hardest problem to tackle in the game of snake. When the snake gets very long it can enclose itself with it's large body in a big loop, that it cannot escape.

GIF by author
GIF by author

Overall learning curve

The following plot shows the score of the snake (in apples eaten) against the number of past episodes/games. Pleas note, that the variance in performance of the snake was so high, that I had to smooth the curve with a moving average of 4 in order to properly see the trend.

Snake score (in apples eaten) against episodes (Image by author)
Snake score (in apples eaten) against episodes (Image by author)

We can see, that the performance increase of the snake is very fast in the beginning of the training, but then starts to converge to an average of around 25. This limit is due to the fact that the snake receives incomplete information.

Conclusion and outlook

With the simple REINFORCE algorithm, our agent could achieve a very high average score of about 25 and a highscore of 51, which is not bad, especially compared with results achieved by Q learning. But the following issues still remain to be solved:

  1. Snake is not aware of obstacle diagonal to its head and therefore traps itself in its tail.

  2. The snake is not aware of the rest of its tail and therefore traps itself in large loops of its own tail.

Both of these issues can be solved by giving the snake more spatial information. The first issue can be solved simply by giving the snake access to the obstacle 1 pixel diagonal to its head. The second issue can be addressed by giving the snake the whole playfield as input and replacing the vanilla deep neural network with a convolutional neural network (CNN).

Giving the snake snake more information comes with a caveat however. We need more training time to get the snake to the same average score. And we even risk, that the snake is not able to learn at all, because convergence to good score is not guaranteed when using neural networks a approximation for our policy function.

References

Sutton and Barto, "Reinforcement learning"

Youtube: David Silver, "Lecture 7: Policy Gradient Methods"

Icalems blog, "Sutton & Barto summary chap 13 - Policy Gradient Methods"

Code

Snake

Algorithm

Backpropagation in Neural Networks

Einstein index notation

Want to connect and support me?

Linkedin https://www.linkedin.com/in/vincent-m%C3%BCller-6b3542214/ Facebook https://www.facebook.com/profile.php?id=100072095823739 Twitter https://twitter.com/Vincent02770108 Medium https://medium.com/@Vincent.Mueller Become medium member and support me (part of your membership fees go directly to me) https://medium.com/@Vincent.Mueller/membership

Related Articles