Uvod u gradijente politika s Cartpole i Doom

Ovaj je članak dio Tečaja učenja dubokog pojačanja s Tensorflowom? ️. Provjerite nastavni plan ovdje.

U posljednja dva članka o Q-učenju i dubokom Q učenju radili smo s algoritmima za učvršćivanje koji se temelje na vrijednostima. Da bismo odabrali akciju koju ćemo poduzeti u određenoj državi, poduzimamo akciju s najvišom Q-vrijednošću (maksimalno očekivanu buduću nagradu koju ću dobiti u svakoj državi). Kao posljedica toga, u učenju temeljenom na vrijednosti postoji politika samo zbog tih procjena vrijednosti akcije.

Danas ćemo naučiti tehniku ​​učenja potkrepljenja zasnovanu na politikama nazvanu Gradienti politike.

Implementirat ćemo dva agenta. Prvi će naučiti održavati letvicu u ravnoteži.

Drugi će biti agent koji nauči preživjeti u neprijateljskom okruženju Dooma skupljajući zdravlje.

U metodama koje se temelje na politikama, umjesto da naučimo funkciju vrijednosti koja nam govori koji je očekivani zbroj nagrada s obzirom na stanje i radnju, mi izravno učimo funkciju politike koja preslikava stanje u akciju (odaberite radnje bez upotrebe funkcije vrijednosti).

To znači da izravno pokušavamo optimizirati svoju funkciju politike π bez brige o vrijednosnoj funkciji. Izravno ćemo parameterizirati π (odabrati radnju bez funkcije vrijednosti).

Svakako, možemo koristiti funkciju vrijednosti za optimizaciju parametara politike. Ali funkcija vrijednosti neće se koristiti za odabir radnje.

U ovom ćete članku naučiti:

  • Što je gradijent politike, te njegove prednosti i nedostaci
  • Kako to implementirati u Tensorflow.

Zašto koristiti metode temeljene na pravilima?

Dvije vrste politike

Politika može biti ili deterministička ili stohastička.

Deterministička politika je politika koja preslikava stanje u akcije. Dajete mu stanje i funkcija vraća radnju koju treba poduzeti.

Determinističke politike koriste se u determinističkim okruženjima. To su okruženja u kojima poduzete radnje određuju ishod. Nema neizvjesnosti. Na primjer, kada igrate šah i premjestite svog pijuna iz A2 u A3, sigurni ste da će se vaš pijun pomaknuti u A3.

S druge strane, stohastička politika daje raspodjelu vjerojatnosti na akcije.

To znači da umjesto da budu sigurni od poduzimanja akcije (na primjer lijevo), postoji vjerojatnost da ćemo uzeti neku drugu (u ovom slučaju 30% da uzmemo jug).

Stohastička se politika koristi kada je okoliš neizvjestan. Taj postupak nazivamo djelomično uočljivim Markovim postupkom odlučivanja (POMDP).

Većinu vremena koristit ćemo ovu drugu vrstu pravila.

Prednosti

Ali duboko Q učenje je stvarno sjajno! Zašto koristiti metode učenja potkrepljenja utemeljene na politikama?

Tri su glavne prednosti korištenja gradijenata politike.

Konvergencija

Kao prvo, metode utemeljene na politikama imaju bolja svojstva konvergencije.

Problem metoda koje se temelje na vrijednosti jest taj što mogu imati velike oscilacije tijekom treninga. To je zato što se izbor radnje može dramatično promijeniti za proizvoljno malu promjenu procijenjenih vrijednosti radnje.

S druge strane, s gradijentom politike, samo slijedimo gradijent kako bismo pronašli najbolje parametre. U svakom koraku vidimo glatko ažuriranje naših pravila.

Budući da slijedimo gradijent kako bismo pronašli najbolje parametre, zajamčeno ćemo konvergirati na lokalnom maksimumu (najgori slučaj) ili globalnom maksimumu (najbolji slučaj).

Gradijenti politike učinkovitiji su u visokodimenzionalnim akcijskim prostorima

Druga prednost je ta što su gradijenti politike učinkovitiji u prostorima radnji visokih dimenzija ili pri korištenju kontinuiranih radnji.

Problem dubokog Q-učenja je taj što njihova predviđanja dodjeljuju rezultat (maksimalnu očekivanu buduću nagradu) za svaku moguću radnju, u svakom vremenskom koraku, s obzirom na trenutno stanje.

Ali što ako imamo beskonačnu mogućnost djelovanja?

Na primjer, sa samovozećim automobilom, u svakom stanju možete imati (gotovo) beskonačan izbor radnji (okretanje kotača na 15 °, 17,2 °, 19,4 °, trub…). Trebat ćemo iznijeti Q-vrijednost za svaku moguću radnju!

S druge strane, u metodama koje se temelje na pravilima, parametre samo izravno prilagodite: zahvaljujući tome počet ćete razumjeti koliki će biti maksimum, umjesto da izravno računate (procjenjujete) maksimum na svakom koraku.

Gradijenti politike mogu naučiti stohastičke politike

Treća prednost je ta što gradijent politike može naučiti stohastičku politiku, dok funkcije vrijednosti ne mogu. To ima dvije posljedice.

Jedna od njih je da ne trebamo provoditi kompromis istraživanja i eksploatacije. Stohastička politika omogućava našem agentu da istražuje državni prostor bez poduzimanja uvijek istih radnji. To je zato što daje distribuciju vjerojatnosti po radnjama. Kao posljedica toga, on rješava kompromis istraživanja i eksploatacije bez da ga teško kodira.

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.
  • Proksimalni gradijenti politike: osigurava da odstupanje od prethodne politike ostane relativno malo.

Primijenimo ga s Cartpole i Doom

Napravili smo video u kojem s Tensorflowom implementiramo agent Gradient politike koji uči igrati Doom ?? u okružju Deathmatcha.

Možete izravno pristupiti bilježnicama u repo tečaju učenja dubokog pojačanja.

Cartpole:

Doom:

To je sve! Upravo ste stvorili agenta koji uči preživjeti u Doom okruženju. Super!

Ne zaboravite sami implementirati svaki dio koda. Zaista je važno pokušati izmijeniti kod koji sam vam dao. Pokušajte dodati epohe, promijeniti arhitekturu, promijeniti brzinu učenja, koristiti teže okruženje ... i tako dalje. Zabavi se!

U sljedećem članku raspravit ću o posljednjim poboljšanjima dubokog Q-učenja:

  • Fiksne Q-vrijednosti
  • Ponovno određivanje prioriteta iskustva
  • Dvostruki 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