CartpoleとDoomを使用したポリシーグラデーションの概要

この記事は、Tensorflowを使用した深層強化学習コースの一部です。こちらのシラバスを確認してください。

Q学習とディープQ学習に関する最後の2つの記事では、値ベースの強化学習アルゴリズムを使用しました。状態を指定して実行するアクションを選択するために、Q値が最も高いアクションを実行します(各状態で得られる予想される最大の将来の報酬)。結果として、価値ベースの学習では、ポリシーはこれらのアクション値の見積もりの​​ためにのみ存在します。

今日は、ポリシー勾配と呼ばれるポリシーベースの強化学習手法を学習します。

2つのエージェントを実装します。最初は、バーのバランスを保つことを学びます。

2つ目は、ヘルスを収集することにより、Doomの敵対的な環境で生き残ることを学ぶエージェントです。

ポリシーベースの方法では、状態とアクションが与えられた場合に期待される報酬の合計を示す値関数を学習する代わりに、状態をアクションにマップするポリシー関数を直接学習します(値関数を使用せずにアクションを選択します)。

これは、値関数を気にせずに、ポリシー関数πを直接最適化しようとすることを意味します。πを直接パラメーター化します(値関数のないアクションを選択します)。

もちろん、value関数を使用してポリシーパラメータを最適化できます。ただし、値関数はアクションの選択には使用されません。

この記事では、次のことを学びます。

  • ポリシー勾配とは何ですか、およびその長所と短所
  • Tensorflowで実装する方法。

ポリシーベースの方法を使用する理由

2種類のポリシー

ポリシーは、決定論的または確率論的のいずれかです。

決定論的ポリシーは、状態をアクションにマップするポリシーです。状態を指定すると、関数は実行するアクションを返します。

決定論的ポリシーは、決定論的環境で使用されます。これらは、実行されたアクションが結果を決定する環境です。不確実性はありません。たとえば、チェスをしてポーンをA2からA3に移動すると、ポーンは確実にA3に移動します。

一方、確率的ポリシーは、アクション全体の確率分布を出力します。

これは、アクションa(たとえば左)を確実に実行する代わりに、別のアクション(この場合は南に移動する30%)を実行する可能性があることを意味します。

確率論的ポリシーは、環境が不確実な場合に使用されます。このプロセスを部分観測マルコフ決定過程(POMDP)と呼びます。

ほとんどの場合、この2番目のタイプのポリシーを使用します。

利点

しかし、ディープQラーニングは本当に素晴らしいです!なぜポリシーベースの強化学習手法を使用するのですか?

ポリシーグラデーションを使用することには、3つの主な利点があります。

収束

1つは、ポリシーベースの方法の方が収束特性が優れていることです。

値ベースの方法の問題は、トレーニング中に大きな変動が発生する可能性があることです。これは、アクションの選択が、推定アクション値の任意の小さな変化に対して劇的に変化する可能性があるためです。

一方、ポリシー勾配では、勾配に従って最適なパラメーターを見つけるだけです。各ステップでポリシーがスムーズに更新されます。

勾配に従って最適なパラメーターを見つけるため、極大値(最悪の場合)または大域的最大値(最良の場合)に収束することが保証されます。

ポリシーの勾配は、高次元のアクション空間でより効果的です

2番目の利点は、高次元のアクションスペースで、または連続アクションを使用する場合に、ポリシーの勾配がより効果的であることです。

ディープQ学習の問題は、現在の状態が与えられた場合、各タイムステップで、予測によって可能なアクションごとにスコア(予想される最大の将来の報酬)が割り当てられることです。

しかし、行動の可能性が無限にあるとしたらどうでしょうか。

たとえば、自動運転車の場合、各状態で(ほぼ)無限のアクションを選択できます(ホイールを15°、17.2°、19,4°、ホーンなどで回す)。可能なアクションごとにQ値を出力する必要があります。

On the other hand, in policy-based methods, you just adjust the parameters directly: thanks to that you’ll start to understand what the maximum will be, rather than computing (estimating) the maximum directly at every step.

Policy gradients can learn stochastic policies

A third advantage is that policy gradient can learn a stochastic policy, while value functions can’t. This has two consequences.

One of these is that we don’t need to implement an exploration/exploitation trade off. A stochastic policy allows our agent to explore the state space without always taking the same action. This is because it outputs a probability distribution over actions. As a consequence, it handles the exploration/exploitation trade off without hard coding it.

We also get rid of the problem of perceptual aliasing. Perceptual aliasing is when we have two states that seem to be (or actually are) the same, but need different actions.

Let’s take an example. We have a intelligent vacuum cleaner, and its goal is to suck the dust and avoid killing the hamsters.

Our vacuum cleaner can only perceive where the walls are.

The problem: the two red cases are aliased states, because the agent perceives an upper and lower wall for each two.

Under a deterministic policy, the policy will be either moving right when in red state or moving left. Either case will cause our agent to get stuck and never suck the dust.

Under a value-based RL algorithm, we learn a quasi-deterministic policy (“epsilon greedy strategy”). As a consequence, our agent can spend a lot of time before finding the dust.

On the other hand, an optimal stochastic policy will randomly move left or right in grey states. As a consequence it will not be stuck and will reach the goal state with high probability.

Disadvantages

Naturally, Policy gradients have one big disadvantage. A lot of the time, they converge on a local maximum rather than on the global optimum.

Instead of Deep Q-Learning, which always tries to reach the maximum, policy gradients converge slower, step by step. They can take longer to train.

However, we’ll see there are solutions to this problem.

Policy Search

We have our policy π that has a parameter θ. This π outputs a probability distribution of actions.

Awesome! But how do we know if our policy is good?

Remember that policy can be seen as an optimization problem. We must find the best parameters (θ) to maximize a score function, J(θ).

There are two steps:

  • Measure the quality of a π (policy) with a policy score function J(θ)
  • Use policy gradient ascent to find the best parameter θ that improves our π.

The main idea here is that J(θ) will tell us how good our π is. Policy gradient ascent will help us to find the best policy parameters to maximize the sample of good actions.

First Step: the Policy Score function J(θ)

To measure how good our policy is, we use a function called the objective function (or Policy Score Function) that calculates the expected reward of policy.

Three methods work equally well for optimizing policies. The choice depends only on the environment and the objectives you have.

First, in an episodic environment, we can use the start value. Calculate the mean of the return from the first time step (G1). This is the cumulative discounted reward for the entire episode.

The idea is simple. If I always start in some state s1, what’s the total reward I’ll get from that start state until the end?

We want to find the policy that maximizes G1, because it will be the optimal policy. This is due to the reward hypothesis explained in the first article.

For instance, in Breakout, I play a new game, but I lost the ball after 20 bricks destroyed (end of the game). New episodes always begin at the same state.

I calculate the score using J1(θ). Hitting 20 bricks is good, but I want to improve the score. To do that, I’ll need to improve the probability distributions of my actions by tuning the parameters. This happens in step 2.

In a continuous environment, we can use the average value, because we can’t rely on a specific start state.

Each state value is now weighted (because some happen more than others) by the probability of the occurrence of the respected state.

Third, we can use the average reward per time step. The idea here is that we want to get the most reward per time step.

Second step: Policy gradient ascent

We have a Policy score function that tells us how good our policy is. Now, we want to find a parameter θ that maximizes this score function. Maximizing the score function means finding the optimal policy.

To maximize the score function J(θ), we need to do gradient ascent on policy parameters.

Gradient ascent is the inverse of gradient descent. Remember that gradient always points to the steepest change.

In gradient descent, we take the direction of the steepest decrease in the function. In gradient ascent we take the direction of the steepest increase of the function.

Why gradient ascent and not gradient descent? Because we use gradient descent when we have an error function that we want to minimize.

But, the score function is not an error function! It’s a score function, and because we want to maximize the score, we need gradient ascent.

The idea is to find the gradient to the current policy π that updates the parameters in the direction of the greatest increase, and iterate.

Okay, now let’s implement that mathematically. This part is a bit hard, but it’s fundamental to understand how we arrive at our gradient formula.

We want to find the best parameters θ*, that maximize the score:

Our score function can be defined as:

Which is the total summation of expected reward given policy.

Now, because we want to do gradient ascent, we need to differentiate our score function J(θ).

Our score function J(θ) can be also defined as:

We wrote the function in this way to show the problem we face here.

We know that policy parameters change how actions are chosen, and as a consequence, what rewards we get and which states we will see and how often.

So, it can be challenging to find the changes of policy in a way that ensures improvement. This is because the performance depends on action selections and the distribution of states in which those selections are made.

Both of these are affected by policy parameters. The effect of policy parameters on the actions is simple to find, but how do we find the effect of policy on the state distribution? The function of the environment is unknown.

As a consequence, we face a problem: how do we estimate the ∇ (gradient) with respect to policy θ, when the gradient depends on the unknown effect of policy changes on the state distribution?

The solution will be to use the Policy Gradient Theorem. This provides an analytic expression for the gradient ∇ of J(θ) (performance) with respect to policy θ that does not involve the differentiation of the state distribution.

So let’s calculate:

Remember, we’re in a situation of stochastic policy. This means that our policy outputs a probability distribution π(τ ; θ). It outputs the probability of taking these series of steps (s0, a0, r0…), given our current parameters θ.

But, differentiating a probability function is hard, unless we can transform it into a logarithm. This makes it much simpler to differentiate.

Here we’ll use the likelihood ratio trick that replaces the resulting fraction into log probability.

Now let’s convert the summation back to an expectation:

As you can see, we only need to compute the derivative of the log policy function.

Now that we’ve done that, and it was a lot, we can conclude about policy gradients:

This Policy gradient is telling us how we should shift the policy distribution through changing parameters θ if we want to achieve an higher score.

R(tau) is like a scalar value score:

  • If R(tau) is high, it means that on average we took actions that lead to high rewards. We want to push the probabilities of the actions seen (increase the probability of taking these actions).
  • On the other hand, if R(tau) is low, we want to push down the probabilities of the actions seen.

This policy gradient causes the parameters to move most in the direction that favors actions that has the highest return.

Monte Carlo Policy Gradients

In our notebook, we’ll use this approach to design the policy gradient algorithm. We use Monte Carlo because our tasks can be divided into episodes.

Initialize θfor each episode τ = S0, A0, R1, S1, …, ST: for t <-- 1 to T-1: Δθ = α ∇theta(log π(St, At, θ)) Gt θ = θ + Δθ
For each episode: At each time step within that episode: Compute the log probabilities produced by our policy function. Multiply it by the score function. Update the weights

But we face a problem with this algorithm. Because we only calculate R at the end of the episode, we average all actions. Even if some of the actions taken were very bad, if our score is quite high, we will average all the actions as good.

So to have a correct policy, we need a lot of samples… which results in slow learning.

How to improve our Model?

We’ll see in the next articles some improvements:

  • Actor Critic: a hybrid between value-based algorithms and policy-based algorithms.
  • Proximal Policy Gradients:以前のポリシーからの逸脱が比較的小さいままであることを保証します。

CartpoleとDoomで実装しましょう

Doomの再生を学習するTensorflowを使用してPolicyGradientエージェントを実装するビデオを作成しました?? デスマッチ環境で。

Deep Reinforcement LearningCourseリポジトリのノートブックに直接アクセスできます。

カートポール:

運命:

それで全部です!Doom環境で生き残ることを学ぶエージェントを作成しました。驚くばかり!

コードの各部分を自分で実装することを忘れないでください。私があなたに与えたコードを修正しようとすることは本当に重要です。エポックの追加、アーキテクチャの変更、学習率の変更、よりハードな環境の使用などを試してください。楽しんで!

次の記事では、ディープQ学習の最後の改善点について説明します。

  • 固定Q値
  • 優先体験リプレイ
  • ダブルDQN
  • Dueling Networks

If you liked my article, please click the ? below as many time as you liked the article so other people will see this here on Medium. And don’t forget to follow me!

If you have any thoughts, comments, questions, feel free to comment below or send me an email: [email protected], or tweet me @ThomasSimonini.

Keep Learning, Stay awesome!

Deep Reinforcement Learning Course with Tensorflow ?️

? Syllabus

? Video version

Part 1: An introduction to Reinforcement Learning

Part 2: Diving deeper into Reinforcement Learning with Q-Learning

Part 3: An introduction to Deep Q-Learning: let’s play Doom

Part 3+: Improvements in Deep Q Learning: Dueling Double DQN, Prioritized Experience Replay, and fixed Q-targets

Part 4: An introduction to Policy Gradients with Doom and Cartpole

Part 5: An intro to Advantage Actor Critic methods: let’s play Sonic the Hedgehog!

Part 6: Proximal Policy Optimization (PPO) with Sonic the Hedgehog 2 and 3

Part 7: Curiosity-Driven Learning made easy Part I