2  Monte Carlo Methods and Stochastic Approximation

\[ \newcommand{\E}{\mathbb{E}} \newcommand{\R}{\mathbb{R}} \newcommand{\Prob}{\mathbb{P}} \newcommand{\BR}{\operatorname{BR}} \newcommand{\eps}{\varepsilon} \newcommand{\given}{\,\vert\,} \newcommand{\argmax}{\operatorname*{arg\,max}} \newcommand{\argmin}{\operatorname*{arg\,min}} \newcommand{\sm}{\setminus} \newcommand{\defeq}{\equiv} \]

NoteSource:

Ben Moll’s RL lecture slides, Lecture 2.

2.1 Recall: the MDP in RL notation

Recall from Definition 1.2 the optimal control problem

\[ v(s_{0})=\max_{\{a_{t}\}_{t=0}^{\infty}}\E_{0}\!\left[\sum_{t=0}^{\infty}\beta^{t}r(s_{t},a_{t})\right] \quad\text{s.t.}\quad s_{t+1}\sim p(\cdot\given s_{t},a_{t}),\ \ s_{0}\text{ given}, \]

whose solution is an optimal policy \(a=\pi(s)\). We now use two RL conventions.

NoteNotation: from β to γ, and from deterministic to stochastic policies

From this chapter onward:

  • the discount factor is written \(\gamma\) rather than \(\beta\);
  • policies are stochastic, \(a_{t}\sim\pi(\cdot\given s_{t})\), so \(\pi(a\given s)\) is a probability rather than a chosen action.

Under a stochastic policy the maximization in the Bellman equation Equation 1.4 is over distributions over actions rather than over actions, so the one-step reward and the transition both get averaged against \(\pi\):

\[ v(s)=\max_{\pi}\sum_{a\in\mathcal{A}}\pi(a\given s) \left(r(s,a)+\gamma\sum_{s'\in\mathcal{S}}p(s'\given s,a)\,v(s')\right). \tag{2.1}\]

Definition 2.1 (Policy-averaged reward and transition) For a policy \(\pi\), define the policy-averaged reward and the policy-averaged transition \[ r_{\pi}(s)=\sum_{a\in\mathcal{A}}\pi(a\given s)\,r(s,a), \qquad p_{\pi}(s'\given s)=\sum_{a\in\mathcal{A}}\pi(a\given s)\,p(s'\given s,a). \]

With Definition 2.1, Equation 2.1 collapses to the same shape as the deterministic case:

\[ v(s)=\max_{\pi}\left(r_{\pi}(s)+\gamma\sum_{s'\in\mathcal{S}}p_{\pi}(s'\given s)\,v(s')\right). \tag{2.2}\]

Tip

Fixing \(\pi\) gives an MRP (Definition 1.1) with reward \(r_{\pi}\) and transition \(p_{\pi}\). Chapter 1’s matrix equations apply with \(\mathbf{r}_{\pi}\) and \(\mathbf{P}_{\pi}\) from Definition 2.1.

2.2 Monte Carlo methods

Where the model still hides

Recall the two steps of Howard policy iteration, now in RL notation:

\[ \begin{cases} \mathbf{v}_{\pi_{k}} &= \mathbf{r}_{\pi_{k}}+\gamma\,\mathbf{P}_{\pi_{k}}\mathbf{v}_{\pi_{k}} \\[2pt] \boldsymbol{\pi}_{k+1} &= \argmax_{\pi}\big(\mathbf{r}_{\pi}+\gamma\,\mathbf{P}_{\pi}\mathbf{v}_{\pi_{k}}\big) \end{cases} \tag{2.3}\]

The first step is policy evaluation (PE), and the second is policy improvement (PI). State by state, PI is

\[ \begin{aligned} \pi_{k+1}(s) &=\argmax_{\pi}\sum_{a}\pi(a\given s)\Big[\underbrace{r(s,a)+\gamma\sum_{s'}p(s'\given s,a)\,v_{\pi_{k}}(s')}_{\defeq\ q_{\pi_{k}}(s,a)}\Big]\\ &=\argmax_{\pi}\sum_{a}\pi(a\given s)\,q_{\pi_{k}}(s,a). \end{aligned} \tag{2.4}\]

Two expressions for the action value

The action value of Definition 1.3 has a model-based and a return-based expression:

\[ q_{\pi_{k}}(s,a)=r(s,a)+\gamma\sum_{s'}p(s'\given s,a)\,v_{\pi_{k}}(s') \tag{2.5}\]

\[ q_{\pi_{k}}(s,a)=\E_{\pi_{k}}\!\left[\sum_{t=0}^{\infty}\gamma^{t}r(s_{t},a_{t})\ \given\ s_{0}=s,\,a_{0}=a\right] \tag{2.6}\]

Table 2.1: The same action value, obtained from a model or from data.
Model-based form Equation 2.5 Model-free form Equation 2.6
Needs the transition density \(p(s'\given s,a)\) and the reward \(r(s,a)\) trajectories generated by \(\pi_{k}\)
Computed by a sum over next states an average over sampled returns
Available when the model is known you can only interact with the environment

The derivation under Definition 1.3 establishes their equivalence.

Estimating \(q\) from episodes

  • start from \((s,a)\), follow \(\pi_{k}\), and generate an episode \(t=0,1,\dots,T\);
  • do this \(N\) times, collecting episodes \(i=1,2,\dots,N\);
  • average the realized returns:

\[ q_{\pi_{k}}(s,a) =\E_{\pi_{k}}\!\left[\sum_{t=0}^{\infty}\gamma^{t}r(s_{t},a_{t})\ \given\ s_{0}=s,\,a_{0}=a\right] \approx\frac{1}{N}\sum_{i=1}^{N}\sum_{t=0}^{T}\gamma^{t}r\big(s_{t}^{i},a_{t}^{i}\big). \tag{2.7}\]

WarningSampling error and truncation bias

Equation 2.7 introduces two distinct sources of error:

  1. a finite number of episodes \(N\), which is sampling error;
  2. truncation at \(T\), which drops the continuation return. If \(|r|\le R\), its absolute expected size is at most \(R\gamma^{T+1}/(1-\gamma)\).

Increasing \(N\) averages out sampling noise; increasing \(T\) reduces the omitted tail.

Truncation bias in closed form, sampling error by simulation
fig, (axL, axR) = plt.subplots(1, 2, figsize=(9.4, 3.9))
trim(axL), trim(axR)
rbar, sd = 1.0, 1.0

# --- left: truncation bias, exact ---------------------------------------
T = np.arange(0, 201)
for gamma, colour, y in ((0.90, COL["sky"], 8e-3), (0.99, COL["vermilion"], 2.0)):
    axL.semilogy(
        T, gamma ** (T + 1) * rbar / (1 - gamma), color=colour, lw=2.0, zorder=4
    )
    label_at(axL, 118, y, rf"$\gamma={gamma}$", color=colour, fontsize=9.5)
axL.set_xlim(0, 200)
axL.set_xlabel(r"episode length $T$")
axL.set_ylabel(r"truncation bias")
axL.set_title(
    r"Truncating at $T$:  bias $=\gamma^{T+1}\bar r/(1-\gamma)$", fontsize=11
)

# --- right: sampling error, simulated + reference slope -----------------
gamma, T_fix, reps = 0.9, 200, 400
disc = gamma ** np.arange(T_fix + 1)
truth = rbar / (1 - gamma) * (1 - gamma ** (T_fix + 1))
Ns = np.unique(np.round(np.logspace(0, 3, 22)).astype(int))
rmse = np.empty(len(Ns))
for i, N in enumerate(Ns):
    rewards = RNG.normal(rbar, sd, (reps, N, T_fix + 1))
    est = (rewards * disc).sum(axis=2).mean(axis=1)
    rmse[i] = np.sqrt(np.mean((est - truth) ** 2))
axR.loglog(Ns, rmse, "o", color=INK, ms=4.2, zorder=5)
ref = rmse[0] * (Ns / Ns[0]) ** -0.5
axR.loglog(Ns, ref, color=COL["green"], lw=1.6, ls="--", zorder=3)
label_at(axR, 30, ref[0] * 0.42, r"slope $-1/2$", color=COL["green"], fontsize=9.5)
axR.set_xlabel(r"number of episodes $N$")
axR.set_ylabel(r"RMSE of $\hat q$")
axR.set_title(r"Averaging $N$ episodes:  error $\propto N^{-1/2}$", fontsize=11)

fig.tight_layout()
plt.show()
Figure 2.1: The two errors of Equation 2.7 die at different rates. Left: truncating each episode at \(T\) leaves a deterministic bias \(\gamma^{T+1}\bar{r}/(1-\gamma)\), geometric in \(T\) but with a rate set by \(\gamma\): at \(\gamma=0.9\) two hundred steps buys eight digits, at \(\gamma=0.99\) it buys barely one. Right: averaging \(N\) episodes leaves sampling error of order \(N^{-1/2}\) (dots simulated at \(\gamma=0.9\), \(T=200\); dashed line the \(-1/2\) reference slope), independent of \(\gamma\). Buying a digit of accuracy costs a fixed number of extra steps but a hundredfold increase in episodes.

The MC Basic algorithm

Substituting Equation 2.7 for the evaluation step of Equation 2.3 gives MC Basic.

NoteAlgorithm: MC Basic

Given an initial policy \(\pi_{0}\), at iteration \(k\), for every state \(s\in\mathcal{S}\) and every action \(a\in\mathcal{A}(s)\):

  1. Collect sufficiently many episodes starting from \((s,a)\) and following \(\pi_{k}\).

  2. Policy evaluation. Estimate the action value by the average return over those episodes: \[ q_{\pi_{k}}(s,a)\approx q_{k}(s,a)=\text{average return of all collected episodes}. \]

  3. Policy improvement. Act greedily with respect to the estimate: \[ a_{k}^{*}(s)=\argmax_{a}q_{k}(s,a), \qquad \pi_{k+1}(a\given s)= \begin{cases} 1 & \text{if } a=a_{k}^{*}(s),\\ 0 & \text{otherwise.} \end{cases} \]

Table 2.2: MC Basic is Howard policy iteration with sample averages in place of the exact evaluation step.
Howard policy iteration MC Basic
Evaluation solve \(\mathbf{v}_{\pi_{k}}=\mathbf{r}_{\pi_{k}}+\gamma\mathbf{P}_{\pi_{k}}\mathbf{v}_{\pi_{k}}\) exactly average sampled returns, Equation 2.7
Estimates state value \(v_{\pi_{k}}\) action value \(q_{\pi_{k}}\)
Improvement \(\argmax_{\pi}\{\mathbf{r}_{\pi}+\gamma\mathbf{P}_{\pi}\mathbf{v}_{\pi_{k}}\}\), reads the model \(\argmax_{a}q_{k}(s,a)\), reads only the estimates
Needs the model yes no

Step 1 assumes episodes can be started from any pair \((s,a)\), an assumption usually called exploring starts. This supplies exploration; the next section replaces it with policy-based exploration.

With exact action values, the greedy step is ordinary policy improvement. Finite batches can reverse the ranking of two actions, even when both estimates are close. The policy-iteration convergence theorem applies in the exact-evaluation limit; a finite-sample convergence result also needs a schedule controlling these evaluation errors.

Important

MC Basic discards previous batches and collects fresh episodes for every state-action pair at every iteration, making it sample-inefficient.

Removing exploring starts: \(\eps\)-greedy policies

Exploring starts requires resetting the environment to an arbitrary state-action pair, which is usually unavailable. Greedy improvement in step 3 of MC Basic assigns probability 1 to one action, so following it supplies no data about other actions. A policy that retains some randomization supplies exploration without arbitrary resets.

Definition 2.2 (ε-greedy policy) For \(\eps\in[0,1]\), choose one maximizer of \(q(s,\cdot)\) using a fixed tie-breaking rule. The \(\eps\)-greedy policy is \[ \pi(a\given s)= \begin{cases} 1-\dfrac{\eps}{|\mathcal{A}(s)|}\big(|\mathcal{A}(s)|-1\big) & \text{if } a=\argmax_{a'}q(s,a'),\\[8pt] \dfrac{\eps}{|\mathcal{A}(s)|} & \text{otherwise.} \end{cases} \]

Tip

With probability \(1-\eps\), choose the selected maximizer; with probability \(\eps\), draw uniformly from all actions. For \(\eps>0\), every action has probability at least \(\eps/|\mathcal A(s)|\). The endpoints are the greedy policy at \(\eps=0\) and the uniform policy at \(\eps=1\).

For a fixed policy with \(\eps>0\) on a finite continuing MDP, irreducibility of the induced state chain gives infinitely many visits to every state-action pair almost surely. Reachability from the starting state is insufficient: a chain that moves from state 0 to absorbing state 1 visits state 0 only once. In an episodic problem, visitation must come from repeated episodes and their reset distribution.

Warning

With exact \(q_\pi\), the \(\eps\)-greedy update is a policy-improvement step when \(\pi(a\mid s)\ge\eps/|\mathcal A(s)|\) for all pairs: it maximizes \(\sum_a\pi'(a\mid s)q_\pi(s,a)\) subject to those same probability floors. Fixed \(\eps>0\) therefore restricts the policies available. Convergence to an unrestricted optimum requires both increasingly greedy policies and enough exploration to estimate every relevant action value; \(\eps_t\to0\) alone gives neither accurate estimates nor infinite visitation.

2.3 Stochastic approximation

Motivating example: mean estimation

Given a random variable \(X\) and iid samples \(\{x_{i}\}_{i=1}^{N}\), estimate \(\E[X]\) by

\[ \E[X]\approx\bar{x}=\frac{1}{N}\sum_{i=1}^{N}x_{i}, \qquad \lim_{N\to\infty}\bar{x}=\E[X]. \]

Let \(w_{k+1}\) denote the average of the first \(k\) samples,

\[ w_{k+1}=\frac{1}{k}\sum_{i=1}^{k}x_{i},\qquad k=1,2,\dots \]

so that \(w_{k}=\frac{1}{k-1}\sum_{i=1}^{k-1}x_{i}\). The incremental form is:

NoteDerivation: the incremental mean

\[ \begin{aligned} w_{k+1}&=\frac{1}{k}\sum_{i=1}^{k}x_{i}\\ &=\frac{1}{k}\left(\sum_{i=1}^{k-1}x_{i}+x_{k}\right)\\ &=\frac{1}{k}\big[(k-1)w_{k}+x_{k}\big]\\ &=w_{k}+\frac{1}{k}(x_{k}-w_{k}). \end{aligned} \]

\[ w_{k+1}=w_{k}-\frac{1}{k}\,(w_{k}-x_{k}). \tag{2.8}\]

NoteIndexing

Equation 2.8 is Equation 1.1 from Chapter 1 with the index shifted: here \(w_{k+1}\) is the mean of the first \(k\) samples, there \(\bar{x}_{k}\) is. The \(w\) convention matches the Robbins-Monro notation below.

Now generalize by replacing the step \(\tfrac{1}{k}\) with an arbitrary positive \(\alpha_{k}\):

\[ w_{k+1}=w_{k}-\alpha_{k}(w_{k}-x_{k}). \tag{2.9}\]

In Equation 2.9, alpha is a constant or an array of steps \(\alpha_{k}\). With \(\alpha_{k}=1/k\), the estimate is the mean of the first \(k\) samples regardless of \(w_{0}\).

def mean_estimation_path(x, alpha, w0):
    """Run w_{k+1} = w_k - alpha_k (w_k - x_k) over the sample stream x.

    Returns the path [w_1, ..., w_{N+1}] of estimates.
    """
    n = len(x)
    a = np.full(n, alpha, float) if np.isscalar(alpha) else np.asarray(alpha, float)
    w = np.empty(n + 1)
    w[0] = w0
    for k in range(n):
        w[k + 1] = w[k] - a[k] * (w[k] - x[k])
    return w

x = np.random.default_rng(20260725).normal(0.0, 1.0, 50)
w = mean_estimation_path(x, 1.0 / np.arange(1, 51), w0=99.0)
assert np.allclose(w[1:], np.cumsum(x) / np.arange(1, 51))   # 1/k IS the running mean

Convergence to \(\E[X]\) follows from the Robbins-Monro conditions on \(\{\alpha_{k}\}\) below.

The Robbins-Monro algorithm

Stochastic approximation (SA) uses stochastic iterative algorithms for root-finding or optimization. It can operate with noisy function observations, without an explicit objective or its derivative. The Robbins-Monro (RM) algorithm is an early example; stochastic gradient descent is a special case, and its convergence theorem explains Equation 2.9.

NotePreliminary: the gradient

For a scalar function \(J(w)\) with \(w=(w_{1},\dots,w_{m})\in\R^{m}\), the gradient is the column vector \[ \nabla_{w}J(w)= \begin{bmatrix} \partial J(w)/\partial w_{1}\\ \partial J(w)/\partial w_{2}\\ \vdots\\ \partial J(w)/\partial w_{m} \end{bmatrix}. \]

Problem statement. Find the root of

\[ g(w)=0, \]

where \(w\in\R\) is the variable to be solved for and \(g:\R\to\R\).

NoteOn dimension

The theorem and proof below are stated for scalar \(w\), because the proof’s mean value theorem step needs a single intermediate point and that is a one-dimensional fact. Everything survives in \(\R^{m}\) with two substitutions: replace the mean value theorem by the integral form \(g(w_{k})-g(w^{*})=\big[\int_{0}^{1}\nabla_{w}g\big(w^{*}+\tau\Delta_{k}\big)\,d\tau\big]\Delta_{k}\), and replace condition 1 by a uniform spectral bound \(0<c_{1}I\preceq\nabla_{w}g(w)\preceq c_{2}I\) on the Jacobian. The vector case is what Chapters 3 and 4 actually use, since there \(w\) and \(\theta\) are parameter vectors.

Tip

Optimization also leads to root-finding. If \(J(w)\) is an objective to be minimized, its first-order condition \(g(w)=\nabla_{w}J(w)=0\) is a root-finding problem.

The method for solving \(g(w)=0\) depends on the information available:

  • Model-based. If the expression of \(g\) is known, standard numerical algorithms apply.
  • Model-free. What if the expression of \(g\) is unknown, and all we obtain are noisy observations of its values?

RM solves the second case:

\[ w_{k+1}=w_{k}-\alpha_{k}\,\tilde{g}(w_{k},\eta_{k}), \tag{2.10}\]

where \(w_{k}\) is the \(k\)-th estimate of the root, \(\tilde{g}(w_{k},\eta_{k})=g(w_{k})+\eta_{k}\) is the \(k\)-th noisy observation, and \(\alpha_{k}>0\) is the step size.

Theorem 2.1 (Robbins-Monro) In the RM algorithm Equation 2.10, suppose

  1. \(0<c_{1}\leq\nabla_{w}g(w)\leq c_{2}\) for all \(w\);
  2. \(\sum_{k=1}^{\infty}\alpha_{k}=\infty\) and \(\sum_{k=1}^{\infty}\alpha_{k}^{2}<\infty\);
  3. \(\E[\eta_{k}\given\mathcal{H}_{k}]=0\) and \(\E[\eta_{k}^{2}\given\mathcal{H}_{k}]\leq C\) almost surely, for a constant \(C\) not depending on \(k\),

where \(\mathcal{H}_{k}=\{w_{k},w_{k-1},\dots\}\). Then \(w_{k}\) converges with probability 1 to the root \(w^{*}\) satisfying \(g(w^{*})=0\).

TipReading the three conditions
  1. \(g\) is increasing and well-conditioned. The lower bound \(c_{1}>0\) makes the root unique and guarantees the update always points toward it; the upper bound \(c_{2}\) stops the steps from overshooting arbitrarily far.
  2. The steps are large enough in total, small enough individually. \(\sum\alpha_{k}=\infty\) means the iteration can still travel an unbounded distance and so cannot stall short of the root no matter where it starts. \(\sum\alpha_{k}^{2}<\infty\) means \(\alpha_{k}\to0\) fast enough that the accumulated noise stays finite and the estimate settles. The canonical choice \(\alpha_{k}=1/k\) satisfies both, which is exactly the step in Equation 2.8.
  3. The noise is zero-mean with finite variance. Unbiased observations, so errors cancel rather than accumulate into a drift.

A constant \(\alpha\) violates condition 2: \(\sum\alpha=\infty\) holds, but \(\sum\alpha^{2}=\infty\) too.

Why the Robbins-Monro theorem is true

Dvoretzky’s theorem proves Theorem 2.1 and also supports the convergence arguments in the next chapter.

Theorem 2.2 (Dvoretzky) Consider the stochastic process \[ \Delta_{k+1}=(1-\alpha_{k})\Delta_{k}+\beta_{k}\eta_{k}, \tag{2.11}\] where \(\{\alpha_{k}\},\{\beta_{k}\},\{\eta_{k}\}\) are stochastic sequences with \(\alpha_{k}\geq0\) and \(\beta_{k}\geq0\). Then \(\Delta_{k}\) converges to zero almost surely if

  1. \(\sum_{k}\alpha_{k}=\infty\), \(\sum_{k}\alpha_{k}^{2}<\infty\), and \(\sum_{k}\beta_{k}^{2}<\infty\) uniformly almost surely;
  2. \(\E[\eta_{k}\given\mathcal{H}_{k}]=0\) and \(\E[\eta_{k}^{2}\given\mathcal{H}_{k}]\leq C\) almost surely,

where \(\mathcal{H}_{k}=\{\Delta_{k},\Delta_{k-1},\dots,\eta_{k-1},\dots,\alpha_{k-1},\dots,\beta_{k-1},\dots\}\) is the history.

Tip

The steps \(\alpha_{k}\) and \(\beta_{k}\) may depend on the history, which allows the effective step size in the RM proof below. The conclusion is almost-sure convergence. The proof of Theorem 2.2 rests on quasimartingale convergence and is not reproduced here.

NoteProof of the Robbins-Monro theorem

Let \(w^{*}\) be the root, so \(g(w^{*})=0\), and write the RM algorithm Equation 2.10 with the noisy observation expanded: \[ w_{k+1}=w_{k}-\alpha_{k}\tilde{g}(w_{k},\eta_{k})=w_{k}-\alpha_{k}\big[g(w_{k})+\eta_{k}\big]. \] Subtract \(w^{*}\) from both sides and use \(g(w^{*})=0\): \[ w_{k+1}-w^{*}=w_{k}-w^{*}-\alpha_{k}\big[g(w_{k})-g(w^{*})+\eta_{k}\big]. \] By the mean value theorem there is a \(w_{k}'\) between \(w_{k}\) and \(w^{*}\) with \[ g(w_{k})-g(w^{*})=\nabla_{w}g(w_{k}')\,(w_{k}-w^{*}). \] Writing \(\Delta_{k}\defeq w_{k}-w^{*}\) for the error and substituting, \[ \begin{aligned} \Delta_{k+1}&=\Delta_{k}-\alpha_{k}\big[\nabla_{w}g(w_{k}')\Delta_{k}+\eta_{k}\big]\\ &=\Big[1-\underbrace{\alpha_{k}\nabla_{w}g(w_{k}')}_{\defeq\,\bar{\alpha}_{k}}\Big]\Delta_{k}+\underbrace{\alpha_{k}}_{\beta_{k}}(-\eta_{k}), \end{aligned} \] which is precisely Equation 2.11. It remains to check its two conditions.

Condition 1. By hypothesis 1 of Theorem 2.1, \(0<c_{1}\leq\nabla_{w}g(w)\leq c_{2}\) for every \(w\), so the effective step is sandwiched: \[ c_{1}\alpha_{k}\leq\bar{\alpha}_{k}\leq c_{2}\alpha_{k}. \] Hypothesis 2 gives \(\sum_{k}\alpha_{k}=\infty\) and \(\sum_{k}\alpha_{k}^{2}<\infty\); the sandwich transfers both to \(\bar{\alpha}_{k}\), since \(\sum\bar{\alpha}_{k}\geq c_{1}\sum\alpha_{k}=\infty\) and \(\sum\bar{\alpha}_{k}^{2}\leq c_{2}^{2}\sum\alpha_{k}^{2}<\infty\). And \(\sum_{k}\beta_{k}^{2}=\sum_{k}\alpha_{k}^{2}<\infty\).

Condition 2. Hypothesis 3 gives \(\E[\eta_{k}\given\mathcal{H}_{k}]=0\) and the uniform bound \(\E[\eta_{k}^{2}\given\mathcal{H}_{k}]\leq C\), which is what Theorem 2.2 asks for; pointwise finiteness at each \(k\) would not be enough, since the constant must not drift with \(k\). Negating \(\eta_{k}\) changes neither.

Both conditions hold, so Theorem 2.2 gives \(\Delta_{k}\to0\) almost surely, that is \(w_{k}\to w^{*}\). \(\square\)

Note

The effective step \(\bar{\alpha}_{k}\) depends on \(w_{k}'\), so the proof requires the history-dependent steps allowed by Theorem 2.2.

Mean estimation is Robbins-Monro

The claim that Equation 2.9 converges now follows from Theorem 2.1 in three steps.

  1. Write mean estimation as root-finding. Define \[ g(w)=w-\E[X], \] whose root is \(w^{*}=\E[X]\). Its value is unknown because it contains the mean being estimated.

  2. Identify the noisy observation. With a sample \(x\) in hand we can evaluate \[ \tilde{g}(w,x)=w-x, \] which is exactly \(g\) plus zero-mean noise: \[ \begin{aligned} \tilde{g}(w,x)&=w-x\\ &=w-x+\E[X]-\E[X]\\ &=\underbrace{\big(w-\E[X]\big)}_{g(w)}+\underbrace{\big(\E[X]-x\big)}_{\eta}. \end{aligned} \]

  3. Apply RM. Substituting into Equation 2.10, \[ w_{k+1}=w_{k}-\alpha_{k}\,\tilde{g}(w_{k},x_{k})=w_{k}-\alpha_{k}(w_{k}-x_{k}), \] which is precisely Equation 2.9. Its convergence follows from Theorem 2.1.

Note

Check the hypotheses hold here: \(\nabla_{w}g(w)=1\), so condition 1 is satisfied with \(c_{1}=c_{2}=1\); and \(\eta=\E[X]-x\) has mean zero by construction, so condition 3 holds whenever \(X\) has finite variance. Condition 2 constrains the chosen step sizes.

One sample stream, three step-size rules, run through @eq-mean-general
fig, ax = new_ax(6.6, 4.4)
mu, sigma, n = 1.0, 1.0, 400
x = RNG.normal(mu, sigma, n)  # one shared sample stream
k = np.arange(1, n + 1)

ax.axhline(mu, color=GREY, lw=0.9, ls="--", zorder=2)

for alpha, colour in ((0.30, COL["orange"]), (0.10, COL["sky"])):
    w = mean_estimation_path(x, alpha, w0=5.0)
    ax.plot(np.arange(n + 1), w, color=colour, lw=1.0, alpha=0.9, zorder=3)
    # stationary std of the constant-step recursion: sigma * sqrt(a/(2-a))
    band = sigma * np.sqrt(alpha / (2 - alpha))
    ax.fill_between([0, n], mu - band, mu + band, color=colour, alpha=0.10, zorder=1)

w = mean_estimation_path(x, 1.0 / k, w0=5.0)
ax.plot(np.arange(n + 1), w, color=COL["vermilion"], lw=2.2, zorder=5)

ax.set_xlim(0, n * 1.13)  # headroom on the right for the E[X] tag
ax.set_ylim(-0.6, 5.3)
ax.set_xlabel(r"iteration $k$")
ax.set_ylabel(r"$w_k$")
# Direct labels live in the empty upper-right quadrant, clear of the paths.
label_at(ax, n * 1.015, mu + 0.28, r"$\mathbb{E}[X]$", color=INK, fontsize=9.5)
label_at(ax, n * 0.50, 4.75, r"constant $\alpha=0.3$", color=COL["orange"], fontsize=9.5)
label_at(ax, n * 0.50, 4.25, r"constant $\alpha=0.1$", color=COL["sky"], fontsize=9.5)
label_at(ax, n * 0.50, 3.75, r"$\alpha_k=1/k$", color=COL["vermilion"], fontsize=9.5)
label_at(
    ax,
    n * 0.50,
    3.20,
    "shaded: stationary band\n" r"$\sigma\sqrt{\alpha/(2-\alpha)}$",
    color=GREY,
    fontsize=8.5,
    va="top",
)
ax.set_title(r"Why $\sum_k \alpha_k^2 < \infty$ is the condition that makes it settle")
plt.show()
Figure 2.2: The recursion Equation 2.9 uses one stream of draws \(x_k\sim N(1,1)\) and starts at \(w_1=5\). With \(\alpha_k=1/k\) (thick), the estimate converges to \(\E[X]\). Constant steps retain fluctuations under this sampling noise. Shading marks one stationary standard deviation, \(\sigma\sqrt{\alpha/(2-\alpha)}\), on either side of the mean; larger steps give wider bands.

Stochastic gradient descent

Applying the same argument to a gradient gives stochastic gradient descent. Suppose we want to minimize

\[ J(w)=\E\big[f(w,X)\big] \tag{2.12}\]

over \(w\), where the expectation is over a random variable \(X\) we can sample but whose distribution we do not know. There are three ways to descend.

Table 2.3: Gradient estimates for Equation 2.12.
Update Needs
Gradient descent \(w_{k+1}=w_{k}-\alpha_{k}\,\E[\nabla_{w}f(w_{k},X)]\) the distribution of \(X\), to take the expectation
Batch gradient descent \(w_{k+1}=w_{k}-\alpha_{k}\,\frac{1}{n}\sum_{i=1}^{n}\nabla_{w}f(w_{k},x_{i})\) \(n\) samples per step
Stochastic gradient descent \(w_{k+1}=w_{k}-\alpha_{k}\,\nabla_{w}f(w_{k},x_{k})\) one sample per step

The last row is stochastic gradient descent (SGD):

\[ w_{k+1}=w_{k}-\alpha_{k}\,\nabla_{w}f(w_{k},x_{k}). \tag{2.13}\]

It replaces the true gradient with a noisy single-sample estimate. Its convergence follows from Theorem 2.1 under that theorem’s assumptions.

NoteDerivation: SGD is Robbins-Monro on the first-order condition

Minimizing Equation 2.12 means solving its first-order condition, which is a root-finding problem in the sense of the previous section: \[ g(w)\defeq\nabla_{w}J(w)=\E\big[\nabla_{w}f(w,X)\big]=0 , \] where the interchange of \(\nabla_{w}\) and \(\E\) assumes \(f(\cdot,x)\) is differentiable and that \(\|\nabla_{w}f(w,X)\|\) is dominated near \(w\) by an integrable envelope, so dominated convergence applies to the difference quotients. We cannot evaluate \(g\), since it is an expectation over an unknown distribution. But with a sample \(x\) in hand we can evaluate \(\nabla_{w}f(w,x)\), and it is \(g\) plus zero-mean noise: \[ \tilde{g}(w,x)=\nabla_{w}f(w,x) =\underbrace{\E\big[\nabla_{w}f(w,X)\big]}_{g(w)} +\underbrace{\Big(\nabla_{w}f(w,x)-\E\big[\nabla_{w}f(w,X)\big]\Big)}_{\eta} . \] Substituting into the RM algorithm Equation 2.10 gives exactly Equation 2.13. SGD is RM applied to a gradient, with the three convergence conditions of Theorem 2.1 imposed on \(g=\nabla_{w}J\).

Example 2.1 (Mean estimation is SGD) Take \(f(w,x)=\tfrac{1}{2}|w-x|^{2}\), so that \(J(w)=\tfrac{1}{2}\E|w-X|^{2}\) is minimized at \(w^{*}=\E[X]\). Then \(\nabla_{w}f(w,x)=w-x\), and Equation 2.13 reads \[ w_{k+1}=w_{k}-\alpha_{k}(w_{k}-x_{k}), \] which is Equation 2.9 once more. Mean estimation is a special case of SGD, which is a special case of Robbins-Monro.