GitHub

@@ -25,7 +25,7 @@ The Q-learning algorithm combines ideas from

25252626

* a recursive version of least squares known as [temporal difference learning](https://en.wikipedia.org/wiki/Temporal_difference_learning).

272728-

This lecture applies a Q-learning algorithm to the situation faced by a McCall worker.

28+

This lecture applies a Q-learning algorithm to the situation faced by a McCall worker.

29293030

This lecture also considers the case where a McCall worker is given an option to quit the current job.

3131

@@ -82,7 +82,7 @@ import matplotlib.pyplot as plt

8282

rng = np.random.default_rng(123)

8383

```

848485-

## Review of McCall Model

85+

## Review of McCall model

86868787

We begin by reviewing the McCall model described in {doc}`this quantecon lecture <mccall_model>`.

8888

@@ -239,10 +239,10 @@ We'll use this value function as a benchmark later after we have done some Q-lea

239239

print(valfunc_VFI)

240240

```

241241242-

## Implied Quality Function $Q$

242+

## Implied quality function $Q$

243243244244245-

A **quality function** $Q$ map state-action pairs into optimal values.

245+

A **quality function** $Q$ maps state-action pairs into optimal values.

246246247247

They are tightly linked to optimal value functions.

248248

@@ -275,7 +275,7 @@ Q\left(w,\text{reject}\right) & =c+\beta\int\max_{\text{accept, reject}}\left\{

275275

$$ (eq:impliedq)

276276277277278-

Note that the first equation of system {eq}`eq:impliedq` presumes that after the agent has accepted an offer, he will not have the objection to reject that same offer in the future.

278+

Note that the first equation of system {eq}`eq:impliedq` presumes that after the agent has accepted an offer, he will not have the option to reject that same offer in the future.

279279280280

These equations are aligned with the Bellman equation for the worker's optimal value function that we studied in {doc}`this quantecon lecture <mccall_model>`.

281281

@@ -313,7 +313,7 @@ $$

313313314314

+++

315315316-

## From Probabilities to Samples

316+

## From probabilities to samples

317317318318

We noted above that the optimal Q function for our McCall worker satisfies the Bellman equations

319319

@@ -326,7 +326,7 @@ $$ (eq:probtosample1)

326326327327

Notice the integral over $F(w')$ on the second line.

328328329-

Erasing the integral sign sets the stage for an illegitmate argument that can get us started thinking about Q-learning.

329+

Erasing the integral sign sets the stage for an illegitimate argument that can get us started thinking about Q-learning.

330330331331

Thus, construct a difference equation system that keeps the first equation of {eq}`eq:probtosample1`

332332

but replaces the second by removing integration over $F (w')$:

@@ -370,7 +370,7 @@ to objects in equation system {eq}`eq:old105`.

370370371371

This informal argument takes us to the threshold of Q-learning.

372372373-

## Q-Learning

373+

## Q-learning

374374375375

Let's first describe a $Q$-learning algorithm precisely.

376376

@@ -456,7 +456,7 @@ pseudo-code for our McCall worker to do Q-learning:

456456457457

4. Update the state associated with the chosen action and compute $\widetilde{TD}$ according to {eq}`eq:old4` and update $\widetilde{Q}$ according to {eq}`eq:old3`.

458458459-

5. Either draw a new state $w'$ if required or else take existing wage if and update the Q-table again according to {eq}`eq:old3`.

459+

5. Either draw a new state $w'$ if required or else take the existing wage and update the Q-table again according to {eq}`eq:old3`.

460460461461

6. Stop when the old and new Q-tables are close enough, i.e., $\lVert\tilde{Q}^{new}-\tilde{Q}^{old}\rVert_{\infty}\leq\delta$ for given $\delta$ or if the worker keeps accepting for $T$ periods for a prescribed $T$.

462462

@@ -474,7 +474,7 @@ The Q-table is updated via temporal difference learning.

474474475475

We iterate this until convergence of the Q-table or the maximum length of an episode is reached.

476476477-

Multiple episodes allow the agent to start afresh and visit states that she was less likely to visit from the terminal state of a previos episode.

477+

Multiple episodes allow the agent to start afresh and visit states that she was less likely to visit from the terminal state of a previous episode.

478478479479

For example, an agent who has accepted a wage offer based on her Q-table will be less likely to draw a new offer from other parts of the wage distribution.

480480

@@ -588,7 +588,7 @@ def run_epochs(N, qlmc, qtable, rng):

588588

"""

589589590590

for n in range(N):

591-

if n%(N/10)==0:

591+

if n % max(1, N // 10) == 0:

592592

print(f"Progress: EPOCHs = {n}")

593593

new_qtable = qlmc.run_one_epoch(qtable, rng)

594594

qtable = new_qtable

@@ -651,10 +651,6 @@ ax.set_xlabel('wages')

651651

ax.set_ylabel('probabilities')

652652653653

plt.show()

654-655-

# VFI

656-

mcm = McCallModel(w=w_new, q=q_new)

657-

valfunc_VFI, flag = mcm.VFI()

658654

```

659655660656

```{code-cell} ipython3

@@ -676,21 +672,23 @@ def plot_epochs(epochs_to_plot, quit_allowed=1):

676672

max_epochs = np.max(epochs_to_plot)

677673

# iterate on epoch numbers

678674

for n in range(max_epochs + 1):

679-

if n%(max_epochs/10)==0:

675+

if n % max(1, max_epochs // 10) == 0:

680676

print(f"Progress: EPOCHs = {n}")

681677

if n in epochs_to_plot:

682678

valfunc_qlr = valfunc_from_qtable(qtable)

683679

error = compute_error(valfunc_qlr, valfunc_VFI)

684680685-

ax.plot(w_new, valfunc_qlr, '-o', label=f'QL:epochs={n}, mean error={error}')

681+

ax.plot(w_new, valfunc_qlr, '-o',

682+

label=f'QL: epochs={n}, mean error={error:.2f}')

686683687684688685

new_qtable = qlmc_new.run_one_epoch(qtable, rng)

689686

qtable = new_qtable

690687691688

ax.set_xlabel('wages')

692689

ax.set_ylabel('optimal value')

693-

ax.legend(loc='lower right')

690+

ax.legend(bbox_to_anchor=(0.5, -0.15), loc='upper center', ncol=2)

691+

plt.subplots_adjust(bottom=0.25)

694692

plt.show()

695693

```

696694

@@ -704,7 +702,7 @@ The above graphs indicates that

704702705703

* the quality of approximation to the "true" value function computed by value function iteration improves for longer epochs

706704707-

## Employed Worker Can't Quit

705+

## Employed worker can't quit

708706709707710708

The preceding version of temporal difference Q-learning described in equation system {eq}`eq:old4` lets an employed worker quit, i.e., reject her wage as an incumbent and instead receive unemployment compensation this period

@@ -715,7 +713,7 @@ This is an option that the McCall worker described in {doc}`this quantecon lectu

715713

See {cite}`Ljungqvist2012`, chapter 6 on search, for a proof.

716714717715

But in the context of Q-learning, giving the worker the option to quit and get unemployment compensation while

718-

unemployed turns out to accelerate the learning process by promoting experimentation vis a vis premature

716+

unemployed turns out to accelerate the learning process by promoting experimentation versus premature

719717

exploitation only.

720718721719

To illustrate this, we'll amend our formulas for temporal differences to forbid an employed worker from quitting a job she had accepted earlier.

@@ -731,7 +729,7 @@ $$ (eq:temp-diff)

731729732730

It turns out that formulas {eq}`eq:temp-diff` combined with our Q-learning recursion {eq}`eq:old3` can lead our agent to eventually learn the optimal value function as well as in the case where an option to redraw can be exercised.

733731734-

But learning is slower because an agent who ends up accepting a wage offer prematurally loses the option to explore new states in the same episode and to adjust the value associated with that state.

732+

But learning is slower because an agent who ends up accepting a wage offer prematurely loses the option to explore new states in the same episode and to adjust the value associated with that state.

735733736734

This can lead to inferior outcomes when the number of epochs/episodes is low.

737735

@@ -744,9 +742,9 @@ We illustrate these possibilities with the following code and graph.

744742

plot_epochs(epochs_to_plot=[100, 1000, 10000, 100000, 200000], quit_allowed=0)

745743

```

746744747-

## Possible Extensions

745+

## Possible extensions

748746749-

To extend the algorthm to handle problems with continuous state spaces,

747+

To extend the algorithm to handle problems with continuous state spaces,

750748

a typical approach is to restrict Q-functions and policy functions to take particular

751749

functional forms.

752750

Read the original on github.com ↗