Chapter 1
The Reinforcement Learning Problem
Nobody tells an infant which muscle to move. It moves anyway, and the world answers: a toy rattles, a hand reaches the mouth, the bottle comes or does not. Out of that stream of consequences it learns what to do. Reinforcement learning is the computational study of this kind of learning: an agent that acts, observes how good the outcome was, and adjusts its behavior so as to collect as much reward as possible over time.Richard S. Sutton and Andrew G. Barto. Reinforcement Learning: An Introduction. Adaptive Computation and Machine Learning. MIT Press, Cambridge, MA, second edition, 2018. ISBN 978-0-262-03924-6. URL http://incompleteideas.net/book/the-book-2nd.html This chapter fixes the vocabulary of everything that follows, shows on a small game the first temporal-difference update, and sketches the three historical threads that produced the field. The formal machinery (Markov decision processes, Bellman equations) waits for Chapter 3.
1.1Learning from Evaluative Interaction#
Sutton and Barto open with a deliberately loose definition: reinforcement learning is learning what to do, a mapping from situations to actions, so as to maximize a numerical reward signal. Two features set the problem apart. First, the learner is never shown the right action; it must discover good actions by trying them, which is trial-and-error search. Second, an action may influence not only the reward that follows it but also the next situation, and through it every later reward: the consequences are delayed. Trial and error together with delayed reward are the two hallmarks the rest of the book keeps returning to.
The same name covers three things, and it pays to keep them apart: a problem (an agent interacting over time with an environment to achieve a goal), a class of solution methods that work well on it, and the field that studies both. Many confusions in the literature come from mixing a property of a method with a property of the problem. Sutton and Barto count any method that solves the problem well as a reinforcement learning method, including the dynamic programming of Chapter 4, which needs a complete model of the environment and learns nothing at all.
Definition 1.1 (The Reinforcement Learning Problem, Informally). An agent and an environment interact at discrete times . At each step the agent observes a state , selects an action , and one step later receives a numerical reward and finds itself in a new state . The agent’s objective is to choose actions so as to maximize the reward it accumulates in the long run. The environment is not known in advance: the agent can sense it to some extent, can affect it through actions, and has a goal expressed only through the rewards.
Sensation, action and goal are the three ingredients that the Markov decision processes of Chapter 3 capture in their simplest non-trivial form, and that is why the book adopts them as its formal setting.
1.1.1Evaluative versus Instructive Feedback#
The contrast with supervised learning is the heart of the matter. A supervised learner receives, for each input, a label saying what the correct output would have been, whatever output it actually produced. That feedback is instructive. A reinforcement learner receives a reward that tells it how good the action it took was, and nothing about the actions it did not take. That feedback is evaluative: it depends entirely on the action chosen and does not say whether a better one existed. In interactive problems it is rarely possible to collect correct and representative examples of desired behavior for all the situations an agent will meet; in uncharted territory, the agent has only its own experience.
Nor is reinforcement learning a form of unsupervised learning, which looks for hidden structure in unlabeled data. Discovering structure in experience can help an agent, but by itself it does not maximize a reward signal. Sutton and Barto therefore treat reinforcement learning as a third paradigm of machine learning, alongside the other two.
1.1.2Exploration and Exploitation#
Evaluative feedback creates a difficulty that has no counterpart in the other paradigms. To collect reward, the agent should repeat actions that have paid well in the past: it should exploit. But it only learns which actions pay well by trying actions it has not tried enough: it must explore. Neither can be pursued exclusively without failing at the task, and on a stochastic task every action must be tried many times before its average payoff is known reliably. This exploration–exploitation dilemma gets a whole chapter in its simplest setting, a single situation with actions (Chapter 2), and it returns whenever an agent must decide whether to trust its current estimates.
A last distinctive trait is that reinforcement learning studies the complete agent. Rather than isolating a subproblem such as classification or planning and asking how to solve it in the abstract, it starts from a goal-seeking agent embedded in an uncertain environment and asks which subproblems matter and why. The agent need not be a robot or an organism: a module monitoring a robot’s battery, which issues commands to the rest of the robot, is an agent whose environment is the robot together with the robot’s world.The book’s examples range from a chess master, whose moves combine look-ahead with intuitive judgments of positions, to a refinery controller, a newborn gazelle learning to run, a trash-collecting robot deciding whether to recharge, and a person making breakfast. All share an active decision maker, uncertainty about the environment, delayed consequences, and a goal that can be judged by what the agent senses.
1.2The Elements of a Reinforcement Learning System#
Besides agent and environment, four subelements recur in almost every system of the book. We introduce them with the notation that later chapters make precise.
- A policy is the agent’s way of behaving: a mapping from states to actions, or more generally to probabilities of actions, written . It may be a lookup table, a simple function, or an elaborate search procedure. The policy alone determines behavior; everything else exists to improve it.
- A reward signal defines the goal. At each step the environment sends the agent one number , and the agent’s sole objective is to maximize the total reward it receives over the long run. Rewards are the immediate, defining features of the problem, analogous to pleasure and pain, and they are the primary basis for changing the policy.
- A value function says what is good in the long run. The value of a state is the total reward an agent can expect to accumulate from that state onward. In Chapter 3 this becomes , with the (possibly discounted) sum of future rewards. A state with a low immediate reward may have a high value because good states regularly follow it, and conversely.
- A model of the environment, optionally, predicts how the environment will respond: given a state and an action, the next state and reward, ultimately the dynamics . Models are used for planning, that is, deciding by considering possible futures before experiencing them. Methods that use models are model-based; trial-and-error methods that do without are model-free.
The relation between rewards and values organizes the whole subject. Rewards are primary: without them there would be no values, and the only purpose of estimating values is to obtain more reward. Yet decisions are made on values, because the action that is best in the long run is the one leading to states of highest value, not of highest immediate reward. And values are hard to obtain. Rewards are given by the environment; values must be estimated, and re-estimated, from the sequences of observations an agent makes over its whole lifetime. Sutton and Barto call efficient value estimation the most important component of almost all the algorithms they study, and the central lesson of six decades of research.
1.2.1State, and What the Book Leaves Out#
Policy, value function and model all take the state as input. Formally, state is defined by the Markov property in Chapter 3; informally it is whatever information the agent has about its environment at a given time, produced by some preprocessing that we treat as part of the environment. The book deliberately does not study how to construct or learn that signal (except for a glance in Chapter 16): it asks what to do given the state, not how to perceive it. That is a choice of focus, not a judgment that representation is unimportant.
1.3Value Functions versus Evolutionary Search#
Value functions are not the only route to good behavior. Evolutionary methods, such as genetic algorithms, genetic programming or simulated annealing, never estimate a value. They run many fixed policies, each for an extended period against its own copy of the environment, keep those that collect the most reward together with random variations of them, and repeat. When the space of policies is small or well structured, or when plenty of time is available, this works; it also copes well when the agent cannot sense the full state.
The objection is not that evolutionary search fails but that it wastes information. It treats each policy as a black box scored by its total reward, ignoring three facts that the reinforcement learning problem hands us for free: that a policy is a function from states to actions, which states a policy actually visited, and which actions it took there. A policy that wins a game is credited as a whole, including for moves that were blunders and even for moves it would have made in states never reached. A value-based learner instead evaluates individual states during play, and so assigns credit at the level where decisions are made. This credit assignment problem (how to distribute the merit of an outcome among the many decisions that led to it) is, in one form or another, what every method of the book addresses. Policy-gradient methods (Chapter 13) do search policy space directly, but they too exploit the state–action structure of the problem, and their best versions use a learned value function as a critic.
1.4Tic-Tac-Toe: A First Temporal-Difference Method#
Take the child’s game of tic-tac-toe, played against an imperfect opponent who sometimes errs; treat draws and losses as equally bad. How can a player learn to exploit the opponent’s weaknesses and win as often as possible?
The classical answers do not fit. The minimax solution of game theory assumes an opponent who plays perfectly, so it would avoid positions from which it could lose, even positions from which this opponent always loses. Dynamic programming can compute the best reply to any opponent, but it needs the opponent’s complete specification: the probability of each move in each position. We do not have it. We could estimate it by playing many games and then plan, which is essentially the model-based route of Chapter 8. An evolutionary method would hill-climb in the space of policies, scoring each by its winning frequency over many games. The value-function method does something simpler and, in a precise sense, more economical.
We play X. Set up a table with one number per board position , our current estimate of the probability of winning from . Positions with three Xs in a row get ; positions with three Os in a row, or a full board, get ; all others start at . To move, we look at every position our legal moves would produce and pick, most of the time, the one with the highest value: a greedy move. Occasionally we pick one of the others at random, an exploratory move, so as to see positions we would otherwise never meet. After each greedy move we back up value: the estimate of the position before the move is moved a fraction of the way toward the estimate of the position after it. With the position after our previous move and the position after our current greedy move,
(1.1)where the step-size parameter sets the rate of learning. The change is driven by the difference between the estimates at two successive times, hence the name temporal-difference learning. Note what the positions are: boards after our move and before the opponent’s reply. Values of such afterstates are convenient precisely because we know the rules of the game, so we can compute the afterstate of each of our moves, while the opponent’s reply remains the unknown part of the environment.
Algorithm 1.2 (Tabular TD Learning of Winning Probabilities for Tic-Tac-Toe). Parameters: step size ; exploration probability .
Initialization: for every afterstate , set if X has three in a row, if O has three in a row or the board is full, and otherwise.
Loop for each game:
- Let be undefined (no previous afterstate yet).
- Loop for each of our turns until the game ends:
- Wait for the opponent’s move (if any) and list the afterstates reachable by our legal moves.
- With probability choose the move whose afterstate maximizes (ties at random): a greedy move. Otherwise choose a move uniformly at random among the others: an exploratory move.
- If the move was greedy and is defined, update , where is the chosen afterstate.
- Set .
- When the game ends after the opponent’s move, the final board is a terminal position with value or ; update toward it as in step 2.
Two features deserve emphasis. The player has a model of the game (it can foresee the board each of its moves produces), but none of the opponent: with respect to the opponent it is model-free. And it learns during play, from every greedy move, rather than from the final outcome only.
1.4.1How Large Is the Table?#
Tabular methods need one entry per state, so it is worth knowing how many there are. The kernel can enumerate every position reachable from the empty board under the rules (X moves first, play stops at a win or a full board) and count those that follow a move of X, the afterstates our player evaluates.
Breadth-first generation of all legal positions, as vectors of nine entries in for X, O and empty: the number of positions and the number of X-afterstates (one more X than O).const tttReach = await wl`Function[{}, With[{lines = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {1, 4, 7}, {2, 5, 8}, {3, 6, 9}, {1, 5, 9}, {3, 5, 7}}}, With[{succ = Function[b, If[AnyTrue[lines, Function[l, Abs[Total[b[[l]]]] == 3]] || FreeQ[b, 0], {}, Map[Function[i, ReplacePart[b, i -> If[Total[b] == 0, 1, -1]]], Flatten[Position[b, 0]]]]]}, Union @@ NestList[Function[s, Union[Flatten[Map[succ, s], 1]]], {ConstantArray[0, 9]}, 9]]]]`
const tttAll = await wl`${tttReach}[]`
await show`{Length[${tttAll}], Count[${tttAll}, b_ /; Total[b] == 1]}`A table of a few thousand numbers is tiny, which is why tic-tac-toe can be learned by a lookup table in a few thousand games. Backgammon’s states, or the legal positions of Go, are another matter, and they are why Part II of the book replaces tables by parameterized functions.
1.4.2What the Update Converges To#
The book states without proof that, with a step size decreasing appropriately over time and a fixed opponent, the table converges to the true winning probabilities of our best play, and the greedy moves become optimal against that opponent. The deterministic core of the statement is easy to see. Fix the policy we follow at our moves and let be the probability that afterstate is followed by afterstate (or terminal position) , which combines the opponent’s reply and our own choice. The expected update of is , which vanishes exactly when
(1.2)with on wins and on draws and losses. These equations say that is the probability of winning from under the policy, and they have a unique solution: a game cannot revisit a position, so the afterstates can be ordered so that each points only to later ones, and (1.2) is solved by backward induction from the end of the game.
Proposition 1.3 (Expected TD Iteration on an Acyclic Game). Let collect the values of the nonterminal afterstates, let be the matrix of transition probabilities among them and the vector of one-step probabilities of reaching a winning terminal position. Applying the expected update to all states at once,
converges from every initial table to the unique solution of (1.2) if and only if .
Proof. Order the afterstates so that transitions only go forward in the game. Then is strictly upper triangular, hence nilpotent, and is upper triangular with every diagonal entry equal to ; all its eigenvalues are . The error obeys , and if and only if the spectral radius is less than one. Since is unit upper triangular it is invertible, which gives existence and uniqueness of . □
The real algorithm updates one sampled state at a time, with sampled successors; making that step rigorous needs the stochastic-approximation conditions on of Theorem A.7, and is the business of Chapter 6. Here we check the proposition on the smallest interesting game.
1.4.3In Wolfram Language#
Consider two nonterminal afterstates . From , the opponent blunders with probability and our greedy reply wins; otherwise our greedy reply leads to . From the opponent blunders with probability and we win; otherwise the game is drawn. The expected update is a map of the pair .
Solve for the fixed point of the expected TD update: it is the winning probability of the greedy policy, and .const ttExpected = await wl`Function[{va, vb}, {va + \[Alpha] (p + (1 - p) vb - va), vb + \[Alpha] (q - vb)}]`
const ttFixed = await show`Solve[${ttExpected}[Subscript[V, a], Subscript[V, b]] == {Subscript[V, a], Subscript[V, b]}, {Subscript[V, a], Subscript[V, b]}]`const ttM = await wl`(1 - \[Alpha]) IdentityMatrix[2] + \[Alpha] {{0, 1 - p}, {0, 0}}`
await show`Eigenvalues[${ttM}]`await show`FullSimplify[Limit[MatrixPower[${ttM}, n] . {Subscript[V, a], Subscript[V, b]} + Sum[MatrixPower[${ttM}, j] . (\[Alpha] {p, q}), {j, 0, n - 1}], n -> Infinity, Assumptions -> 0 < \[Alpha] < 1 && 0 < p < 1 && 0 < q < 1]]`1.4.4The Update as a Recency-Weighted Average#
Unrolling (1.1) for a single state that receives targets (the successive values it is pulled toward) shows what a constant step size does: after updates the estimate is , a weighted average in which the initial guess and old targets fade geometrically. Chapter 2 proves that the weights sum to one and studies the bias and variance this causes; it is the reason a constant- player keeps adapting to an opponent who slowly changes style, while a step size decreasing to zero would eventually freeze.
Three constant- updates toward symbolic targets from : the weights are and .await show`Collect[Expand[Fold[Function[{v, g}, v + \[Alpha] (g - v)], Subscript[V, 0], {Subscript[T, 1], Subscript[T, 2], Subscript[T, 3]}]], {Subscript[V, 0], Subscript[T, 1], Subscript[T, 2], Subscript[T, 3]}, Factor]`1.4.5Lessons of the Example#
The tic-tac-toe player already shows most of what makes reinforcement learning distinctive. It learns while interacting with its environment (the opponent). It has a clear goal, and good play requires foresight: against a short-sighted opponent it learns to set multi-move traps. Yet it achieves the effects of look-ahead without a model of the opponent and without any explicit search over move sequences: the backed-up values carry the information that planning would compute.
The example is also misleadingly small, and the book is careful to say in which ways. Reinforcement learning does not need an adversary (a “game against nature” will do), nor episodes with reward only at the end, nor even discrete time. It does not need a small state set: Tesauro combined essentially this update with a neural network to play backgammon, which has about states, far beyond what any player can visit.TD-Gammon learned from self-play to a level comparable to the best human players; Chapter 15 tells the story. Whenever states are too many to visit, generalization from visited to unvisited states becomes the crux, and this is where supervised learning methods, neural networks among them, enter reinforcement learning (Chapter 9).Gerald Tesauro. Temporal Difference Learning and TD-Gammon. Communications of the ACM, 38(3):58–68, 1995. doi: 10.1145/203330.203343 It does not require starting from scratch: prior knowledge can be built into the values, the features or the policy. It does not need the true state either; parts of it may be hidden. Finally, reinforcement learning works at every level of a system, from motor commands to choices among whole problem-solving procedures.
1.5Three Threads of History#
The modern field formed in the late 1980s when three largely independent threads came together.
The first, trial-and-error learning, comes from the psychology of animal learning. Its classic statement is Thorndike’s Law of Effect: responses followed by satisfaction become more firmly connected with the situation, those followed by discomfort less so.Edward L. Thorndike. Animal Intelligence: Experimental Studies. Macmillan, New York, 1911 The law is selectional (it tries alternatives and keeps the better) and associative (it ties choices to situations), the two features of every method in the book.Turing’s 1948 design of a “pleasure–pain system”, the SNARC analog machine described in Minsky’s 1954 dissertation, Michie’s matchbox tic-tac-toe learner MENACE (1961–63) and the BOXES pole-balancer of Michie and Chambers (1968) are early machine embodiments. Minsky’s “Steps Toward Artificial Intelligence” named the credit-assignment problem. In the 1960s and 1970s much of this work drifted toward supervised pattern recognition, and genuine trial-and-error learning survived mainly in learning automata (Tsetlin), in Holland’s classifier systems, and in Klopf’s insistence on the “hedonic” side of learning, which led Barto and Sutton to the subject.Marvin Minsky. Steps Toward Artificial Intelligence. Proceedings of the IRE, 49(1):8–30, 1961. doi: 10.1109/JRPROC.1961.287775
The second thread is optimal control. In the mid-1950s Bellman and others extended Hamilton–Jacobi theory using the state of a dynamical system and a value (or “optimal return”) function, obtaining a functional equation now called the Bellman equation; the methods solving it are dynamic programming, and Bellman’s discrete stochastic version is the Markov decision process.Richard Bellman. Dynamic Programming. Princeton University Press, Princeton, NJ, 1957. A Rand Corporation Research Study; xxv+342 pp. Howard introduced policy iteration in 1960.Ronald A. Howard. Dynamic Programming and Markov Processes. MIT Press, Cambridge, MA, 1960 Dynamic programming suffers from Bellman’s curse of dimensionality (cost exponential in the number of state variables) but remains the only general method for stochastic optimal control. For decades it was seen as an offline computation on an exact model, running backwards in time, and its link with learning, which must run forwards, was slow to be recognized.
The third and smallest thread is temporal-difference learning: learning driven by the difference between successive estimates of the same quantity. Its roots are in the psychology of secondary reinforcers, stimuli that acquire value by being paired with primary ones. Samuel’s checkers player (1959) was the first program to use the idea, inspired by Shannon’s suggestion that a chess program could improve its evaluation function online.Arthur L. Samuel. Some Studies in Machine Learning Using the Game of Checkers. IBM Journal of Research and Development, 3(3):210–229, 1959. doi: 10.1147/rd.33.0210 Witten proposed what is now called tabular TD(0) as part of an adaptive controller in 1977,Ian H. Witten. An Adaptive Optimal Controller for Discrete-Time Markov Environments. Information and Control, 34(4):286–295, 1977. doi: 10.1016/S0019-9958(77)90354-0 Barto, Sutton and Anderson combined TD learning with trial-and-error learning in the actor–critic architecture,Andrew G. Barto, Richard S. Sutton, and Charles W. Anderson. Neuronlike Adaptive Elements That Can Solve Difficult Learning Control Problems. IEEE Transactions on Systems, Man, and Cybernetics, SMC-13(5):834–846, 1983. doi: 10.1109/TSMC.1983.6313077 and Sutton separated TD learning from control and treated it as a general prediction method, introducing TD().Richard S. Sutton. Learning to Predict by the Methods of Temporal Differences. Machine Learning, 3(1):9–44, 1988. doi: 10.1007/BF00115009
The threads were tied together in 1989 by Watkins’s Q-learning, which joined temporal differences to the dynamic programming of MDPs;Christopher John Cornish Hellaby Watkins. Learning from Delayed Rewards. PhD thesis, King’s College, University of Cambridge, Cambridge, UK, May 1989. doi: 10.17863/CAM.132164. URL https://www.repository.cam.ac.uk/handle/1810/406035 TD-Gammon’s success in 1992 brought wide attention. Since the first edition of the book, a further connection has grown into its own subfield: the activity of dopamine neurons in the brain closely resembles a TD error (Chapter 14).
1.5.1After 2018#
The second edition of the book went to press as deep reinforcement learning was taking off; its last chapters already describe the Atari-playing DQN and AlphaGo. Since then reinforcement learning has moved from games to the training of general-purpose AI systems.Beyond Sutton and Barto (2018). AlphaZero (Silver et al., Science, 2018) learned chess, shogi and Go from self-play alone with one algorithm. Reinforcement learning from human feedback (RLHF) fits a reward model to human comparisons of behavior and optimizes a policy against it (Christiano et al., 2017); applied to GPT-3, it produced InstructGPT (Ouyang et al., 2022), the template for aligning chat language models. In 2025 DeepSeek-R1 showed that RL with automatically checkable rewards (correct answers to mathematics and coding problems) can by itself elicit long chains of reasoning in a language model (Guo et al., Nature, 2025).David Silver, Thomas Hubert, Julian Schrittwieser, Ioannis Antonoglou, Matthew Lai, Arthur Guez, Marc Lanctot, Laurent Sifre, Dharshan Kumaran, Thore Graepel, Timothy Lillicrap, Karen Simonyan, and Demis Hassabis. A General Reinforcement Learning Algorithm that Masters Chess, Shogi, and Go through Self-Play. Science, 362(6419):1140–1144, 2018. doi: 10.1126/science.aar6404; Paul F. Christiano, Jan Leike, Tom B. Brown, Miljan Martic, Shane Legg, and Dario Amodei. Deep Reinforcement Learning from Human Preferences. In Isabelle Guyon, Ulrike von Luxburg, Samy Bengio, Hanna Wallach, Rob Fergus, S. V. N. Vishwanathan, and Roman Garnett, editors, Advances in Neural Information Processing Systems 30 (NIPS 2017), volume 30, pages 4299–4307. Curran Associates, Inc., 2017; Long Ouyang, Jeff Wu, Xu Jiang, Diogo Almeida, Carroll L. Wainwright, Pamela Mishkin, Chong Zhang, Sandhini Agarwal, Katarina Slama, Alex Ray, John Schulman, Jacob Hilton, Fraser Kelton, Luke Miller, Maddie Simens, Amanda Askell, Peter Welinder, Paul F. Christiano, Jan Leike, and Ryan Lowe. Training Language Models to Follow Instructions with Human Feedback. In S. Koyejo, S. Mohamed, A. Agarwal, D. Belgrave, K. Cho, and A. Oh, editors, Advances in Neural Information Processing Systems 35 (NeurIPS 2022), volume 35, pages 27730–27744. Curran Associates, Inc., 2022. doi: 10.52202/068431-2011; and Daya Guo, Dejian Yang, Haowei Zhang, Junxiao Song, Peiyi Wang, Qihao Zhu, Runxin Xu, Ruoyu Zhang, Shirong Ma, Xiao Bi, et al. DeepSeek-R1 Incentivizes Reasoning in LLMs through Reinforcement Learning. Nature, 645(8081):633–638, Springer Nature, 2025. doi: 10.1038/s41586-025-09422-z. Preprint: DeepSeek-AI, “DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning”, arXiv:2501.12948 (2025) These developments rest on the ideas of the book (policy gradients, value baselines, exploration, the reward signal as the definition of the goal); RLHF and its successors are treated in Section 13.8.7, and the other developments in Chapter 15 and Chapter 16. They also make one of the book’s warnings concrete: an agent maximizes the reward it is given, not the one its designer meant, and with a learned reward model the gap between the two can be exploited.
1.6A Map of the Book#
The book is built around a few ideas that recur in every chapter, and it is worth naming them before the details begin.
- Value functions and Bellman equations. Almost every method estimates , , or , and the Bellman equations of Chapter 3 express each value in terms of the values of successor states.
- Generalized policy iteration. Evaluation of the current policy and its improvement by acting greedily with respect to the values interact until both stabilize (Section 4.7). Dynamic programming, Monte Carlo, TD, planning and actor–critic methods are all instances.
- Sampling and bootstrapping. An update may use a full expectation over successors (dynamic programming) or a sample (Monte Carlo, TD), and it may wait for the actual return (Monte Carlo) or bootstrap from the current estimate of the next state’s value (dynamic programming, TD). The tic-tac-toe rule (1.1) samples and bootstraps.
- On- and off-policy learning. One may learn about the policy that generates the data, or about another one, typically the greedy policy, from data produced by an exploratory one.
- From tables to approximation. Part I stores one number per state; Part II replaces tables with parameterized functions , which brings generalization and new instabilities.
Part I, tabular methods. Chapter 2 isolates evaluative feedback and exploration in a single-state problem. Chapter 3 defines the full problem, returns, value functions and Bellman equations. Chapter 4 solves it with a perfect model; Chapter 5 learns from complete episodes without a model; Chapter 6 combines the two ideas into TD learning, Sarsa and Q-learning. Chapter 7 interpolates between Monte Carlo and one-step TD, and Chapter 8 unifies learning and planning with learned models, up to Monte Carlo tree search.
Part II, approximate methods. Chapter 9 develops prediction with function approximation (gradient and semi-gradient methods, linear features, neural networks), Chapter 10 extends it to control and to the average-reward setting, and Chapter 11 confronts the instability of off-policy learning with approximation, the “deadly triad”. Chapter 12 unifies the -step ideas through eligibility traces and the -return, and Chapter 13 learns parameterized policies directly, with the policy-gradient theorem and actor–critic methods.
Part III, looking deeper. Chapter 14 relates the algorithms to animal learning and to the dopamine system, Chapter 15 studies landmark applications from TD-Gammon to AlphaGo Zero, and Chapter 16 surveys open problems. The appendix, Appendix A, collects the mathematical results used throughout: contraction mappings, stochastic approximation and stationary distributions of Markov chains.
The next chapter starts where Sutton and Barto start: with the simplest setting in which evaluative feedback and the need to explore can be studied in isolation, a single situation with actions and no delayed consequences.
1.7Exercises#
Exercise 1.4. Self-play (Sutton and Barto, Exercise 1.1). Suppose the tic-tac-toe learner plays against a copy of itself, both sides learning. What happens? Does it learn a different policy from the one it learns against a fixed imperfect opponent?
Solution
Against a fixed opponent the environment is stationary and the values converge to winning probabilities against that opponent; the policy exploits its specific mistakes. In self-play the opponent is the learner itself, so the environment changes as learning proceeds and neither side’s mistakes persist. If both sides keep exploring and their values settle, the natural limit is a pair of mutually best responses, which for a finite, two-player zero-sum game of perfect information is minimax play: in tic-tac-toe a policy that never loses, with every game a draw. The learned policy is therefore different: it is safe against any opponent but no longer exploits a weak one, because it never met one. (Convergence of self-play is not guaranteed in general games; TD-Gammon and AlphaZero show that in practice it can work very well.) Note also that with draws and losses scored alike, the values are winning probabilities, so a minimax-like learner would value most positions near ; scoring a draw as would make the learned values more informative.
Exercise 1.5. Symmetries (Exercise 1.2). Many tic-tac-toe positions are equivalent under the eight rotations and reflections of the board. How could the learner exploit this? Should it, if the opponent does not play symmetrically?
Solution
Store one value per equivalence class of positions (map each board to a canonical representative before looking up or updating ). Every update then improves the estimate of up to eight positions at once, the table is about eight times smaller, and learning is correspondingly faster: this is the simplest instance of generalization, which Chapter 9 develops with function approximation. But the values we learn are winning probabilities against this opponent. If the opponent’s behavior is not symmetric (say it always blocks threats on the left column but misses them on the right), two symmetric positions have different true values, and tying them together introduces bias: the learner would average the two and could no longer exploit the asymmetry. Symmetry of the rules does not imply symmetry of the values; only symmetry of the whole environment, opponent included, does.
Map each legal position to the lexicographically smallest of its eight images under the symmetries of the square, and count the distinct canonical forms (the first entry checks that the eight symmetries are distinct).await show`With[{m = Partition[Range[9], 3]}, With[{perms = Flatten /@ Flatten[Table[f[g[m]], {g, {Identity, Transpose}}, {f, {Identity, Reverse, Map[Reverse], Composition[Reverse, Map[Reverse]]}}], 1]}, {Length[Union[perms]], Length[Union[Map[Function[b, First[Sort[Map[Function[p, b[[p]]], perms]]]], ${tttAll}]]]}]]`Symmetry reduces the positions of Section 1.4.1 to classes, a factor close to the ideal eight (positions with symmetries of their own, such as the empty board, have fewer than eight distinct images).
Exercise 1.6. Greedy play (Exercise 1.3). Suppose the learner always makes the greedy move. Might it play better or worse than an exploring player? What can go wrong?
Solution
A purely greedy learner updates only the values of positions its current preferences lead to. If a good move initially looks bad (its afterstate starts at like all others, and an early unlucky game lowers it), the learner may never play it again, so its value is never corrected: the estimate stays wrong exactly where being right would matter. The learner then settles into a policy that is self-consistent but suboptimal. It can do better than an exploring player in the short run, since it never wastes moves, and in the long run too if its first impressions happen to be right; in general it will do worse, because the cost of exploration is bounded while the cost of never discovering the best move grows with the number of games. Chapter 2 quantifies this on the -armed testbed, where a greedy method finds the best action in only about a third of the problems. Optimistic initial values (starting every nonterminal value above any achievable winning probability) are one way to make a greedy learner explore.
Exercise 1.7. Learning from exploration (Exercise 1.4). Suppose updates are also made after exploratory moves and the step size is reduced appropriately, while exploration continues with probability . To which values does the table converge, compared with learning only from greedy moves? Which set is better to learn, and which gives more wins? Answer in the two-afterstate game of Section 1.4.3, assuming that at the position reached from we may move to (later win probability ) or, exploring, to (later win probability ).
Solution
Learning only from greedy moves, the target of is always the value of the greedy successor, so the table estimates the winning probabilities of the greedy policy, here . Learning from all moves, the target is the value of whichever successor was actually chosen, so the table estimates the winning probabilities of the -greedy policy actually followed:
Fixed point of the expected update when exploratory moves (probability ) are learned from too.await show`Collect[Subscript[V, a] /. First[Solve[Subscript[V, a] == Subscript[V, a] + \[Alpha] (p + (1 - p) ((1 - \[Epsilon]) q + \[Epsilon] OverTilde[q]) - Subscript[V, a]), Subscript[V, a]]], \[Epsilon], Factor]`The difference is the price of exploring. This is exactly the distinction between off-policy and on-policy learning (Chapter 6): the first set of values (Q-learning-like) describes the best policy and is the right one to act greedily on, while the second (Sarsa-like) describes the behavior actually followed. If exploration continues, the on-policy values are more accurate predictions of what will happen and can lead to safer choices, avoiding positions where an exploratory slip is costly (the cliff-walking example of Chapter 6); if exploration is eventually turned off, the greedy values give more wins.
Exercise 1.8. Other improvements (Exercise 1.5). Suggest ways to improve the tic-tac-toe learner, and a better way to solve the problem as posed.
Solution
Several improvements anticipate later chapters. (i) Initialize the values with prior knowledge, for instance adjusted by simple features such as open lines, instead of a uniform guess. (ii) Exploit symmetries (Exercise 1.5) or, more generally, features that let one update generalize to similar positions (Chapter 9). (iii) Back up value along the whole game rather than one step at a time, with -step returns or eligibility traces (Chapter 7, Chapter 12), so that a win propagates to early moves in one game instead of many. (iv) Learn a model of the opponent (the frequency of each reply in each position) and use it to plan: in the limit this is the “estimate a model, then apply dynamic programming” approach the chapter mentions, and with the model one can also replay simulated games, as Dyna does (Chapter 8). (v) Make exploration smarter than uniform, for example by preferring moves whose values are uncertain (Chapter 2), and decay it over time if the opponent is stationary.
As for a better solution of the problem as posed: since the game tree is small (the counts of Section 1.4.1), the model-based route is attractive. Play enough games to estimate the opponent’s move probabilities in the positions that matter, then compute the optimal reply by backward induction over the tree; positions never seen can be handled with an optimistic or a minimax assumption. With a stationary opponent this uses each game’s information more efficiently than one-step TD updates, which is the trade-off between model-based and model-free methods studied in Chapter 8.