@@ -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.
29293030This 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
8282rng = np.random.default_rng(123)
8383```
848485-## Review of McCall Model
85+## Review of McCall model
86868787We 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
239239print(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.
246246247247They 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.
279279280280These 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
317317318318We noted above that the optimal Q function for our McCall worker satisfies the Bellman equations
319319@@ -326,7 +326,7 @@ $$ (eq:probtosample1)
326326327327Notice 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.
330330331331Thus, construct a difference equation system that keeps the first equation of {eq}`eq:probtosample1`
332332but replaces the second by removing integration over $F (w')$:
@@ -370,7 +370,7 @@ to objects in equation system {eq}`eq:old105`.
370370371371This informal argument takes us to the threshold of Q-learning.
372372373-## Q-Learning
373+## Q-learning
374374375375Let's first describe a $Q$-learning algorithm precisely.
376376@@ -456,7 +456,7 @@ pseudo-code for our McCall worker to do Q-learning:
4564564574574. 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`.
4604604614616. 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.
474474475475We 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.
478478479479For 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')
651651ax.set_ylabel('probabilities')
652652653653plt.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
708706709707710708The 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
715713See {cite}`Ljungqvist2012`, chapter 6 on search, for a proof.
716714717715But 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
719717exploitation only.
720718721719To 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)
731729732730It 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.
735733736734This 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.
744742plot_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,
750748a typical approach is to restrict Q-functions and policy functions to take particular
751749functional forms.
752750