Module contents
Lesson 12 of 37Advanced 110 min

Value function approximation and the deadly triad

Study value-function approximation, projected Bellman equations, LSTD and the deadly triad, including gradient TD and fitted Q iteration.

After this lesson you can

  • Explain feature construction and semi-gradient updates.
  • Derive the projected Bellman fixed point and its on-policy contraction.
  • Construct and solve empirical LSTD equations.
  • Analyze off-policy instability and the assumptions of gradient TD.
  • Compare fitted Q iteration and least-squares policy iteration.

Before you start

An update affecting many states

In a table, updating Q(s,a)Q(s,a) leaves other entries intact. But a car climbing a hill can be in innumerable positions and velocities: we cannot wait to visit each pair exactly. An approximate function shares parameters across similar states. Updating one state informs its neighbors, although it can also worsen their predictions.

Value function approximation replaces a table with v^(s;w)\hat v(s;w) or q^(s,a;w)\hat q(s,a;w). In the linear case v^(s;w)=ϕ(s)Tw\hat v(s;w)=\phi(s)^{\mathsf T}w, with features ϕ(s)∈Rd\phi(s)\in\mathbb R^d. Choosing them determines representable values. A representation that generalizes well is an assumption about the task, not an automatic property of every flexible function.

InteractiveTiles for generalization in Mountain Car

Preparing Mountain Car.

Overlay shifted partitions and see which states share parameters.

One way of constructing features is tile coding: multiple grids shift their boundaries over the position–velocity plane. Each activates a tile for the observed state; the feature is a sparse indicator vector. An update changes weights of active tiles and thus the values of states sharing them. More grids smooth dependence on one boundary but also change update scale. Control uses separate parameters per action or features including action. The number of active tiles matters when choosing α\alpha.

What are we trying to minimize?

If dd is a distribution over states, the mean squared value error is

VE(w)=∑sd(s)(vπ(s)−v^(s;w))2.\mathrm{VE}(w)=\sum_s d(s)\bigl(v^\pi(s)-\hat v(s;w)\bigr)^2.

The best representable value depends on both features and dd: a state given little weight by dd matters little for this objective. Generally vπv^\pi is unknown, so we cannot directly use its exact gradient. An observed complete return is a possible sample of the target under suitable conditions; TD instead uses a one-step prediction.

Semi-gradient TD freezes the target when differentiating:

δt=Rt+1+γv^(St+1;w)−v^(St;w),w←w+αδt∇wv^(St;w).\delta_t=R_{t+1}+\gamma\hat v(S_{t+1};w)-\hat v(S_t;w), \qquad w\leftarrow w+\alpha\delta_t\nabla_w\hat v(S_t;w).

For linear features, ∇wv^=ϕ(St)\nabla_w\hat v=\phi(S_t). Semi-gradient SARSA uses the same idea with state–action features and the next action chosen by the behavior policy. True termination cancels bootstrapping; an external cutoff does not make it zero. The target also depends on ww, but the semi-gradient does not differentiate that dependence.

Thus TD is not generally gradient descent on squared Bellman error or value error. Nor is it true that its expected field is never the gradient of any function: in a single state with feature one, reward rr and γ<1\gamma<1, field r−(1−γ)wr-(1-\gamma)w is the negative gradient of (1−γ)(w−r/(1−γ))2/2(1-\gamma)(w-r/(1-\gamma))^2/2. In higher dimensions, linear field b−Awb-Aw is the Euclidean gradient of a quadratic if AA is symmetric; TD does not guarantee that symmetry.

The projected Bellman equation

Now consider a finite chain under a fixed policy, with stationary distribution dd positive on considered states, matrix PP, expected rewards rr and 0≤γ<10\leq\gamma<1. Let D=diag(d)D=\mathrm{diag}(d), Φ\Phi be the feature matrix and ΠD\Pi_D the orthogonal projection onto the column space of Φ\Phi in norm ∥x∥D2=xTDx\lVert x\rVert_D^2=x^{\mathsf T}Dx. If features have full rank, C=ΦTDΦC=\Phi^{\mathsf T}D\Phi is invertible.

The projected fixed point satisfies

ΦwTD=ΠDTπ(ΦwTD),ΦTD(I−γP)Φ⏟AwTD=ΦTDr⏟b.\Phi w_{\mathrm{TD}}=\Pi_D T^\pi(\Phi w_{\mathrm{TD}}), \qquad \underbrace{\Phi^{\mathsf T}D(I-\gamma P)\Phi}_{A}w_{\mathrm{TD}} =\underbrace{\Phi^{\mathsf T}Dr}_{b}.

The second equation says the Bellman residual is orthogonal to the representable space, not that it is zero in every state. Under these assumptions AA is invertible. The result is the root of the expected on-policy TD update; convergence of sampled iterations also requires conditions on the chain and learning steps.

InteractiveProjecting after applying Bellman

Preparing geometry.

Compare the projected fixed point, best value approximation and minimum Bellman residual.

The geometric reason for on-policy stability is specific. By Jensen, (Px)s2≤∑s′P(s,s′)xs′2(Px)_s^2\leq\sum_{s'}P(s,s')x_{s'}^2; weighting by dd and using dTP=dTd^{\mathsf T}P=d^{\mathsf T} gives ∥Px∥D≤∥x∥D\lVert Px\rVert_D\leq\lVert x\rVert_D. Orthogonal projection also does not expand the norm. Thus ΠDTπ\Pi_D T^\pi is a contraction with modulus at most γ\gamma.

Since vπ=Tπvπv^\pi=T^\pi v^\pi, projection orthogonality and contraction give the bound

∥vπ−ΦwTD∥D≤∥vπ−ΠDvπ∥D1−γ2.\lVert v^\pi-\Phi w_{\mathrm{TD}}\rVert_D \leq\frac{\lVert v^\pi-\Pi_Dv^\pi\rVert_D}{\sqrt{1-\gamma^2}}.

Indeed, decompose vπ−ΦwTDv^\pi-\Phi w_{\mathrm{TD}} into orthogonal error vπ−ΠDvπv^\pi-\Pi_Dv^\pi and representable term ΠDvπ−ΦwTD\Pi_Dv^\pi-\Phi w_{\mathrm{TD}}. They are orthogonal, and the second has norm at most γ∥vπ−ΦwTD∥D\gamma\lVert v^\pi-\Phi w_{\mathrm{TD}}\rVert_D. The best projection of vπv^\pi and the TD fixed point need not coincide. For convergence analysis and assumptions, see Tsitsiklis and Van Roy.

Solving the same fixed point by least squares

LSTD accumulates feature products instead of choosing an update rate for each transition. Given samples (ϕt,rt+1,ϕt′)(\phi_t,r_{t+1},\phi'_t), construct

A^=∑tϕt(ϕt−γϕt′)T,b^=∑tϕtrt+1,A^w=b^.\widehat A=\sum_t\phi_t(\phi_t-\gamma\phi'_t)^{\mathsf T}, \qquad \widehat b=\sum_t\phi_t r_{t+1}, \qquad \widehat A w=\widehat b.

For a true terminal, take ϕt′=0\phi'_t=0. If the matrix is singular there is no unique solution; adding regularization or choosing a least-squares solution changes the solved equation and must be declared. Under suitable on-policy sampling, a law of large numbers and invertibility of the unregularized limit, normalized sums estimate AA and bb. This does not imply that every off-policy or regularized dataset converges to the same fixed point.

LSPI extends the idea to action values: approximately evaluate a policy with LSTDQ, improve the policy and reuse data. Transitions must cover what is needed for informative evaluation; the inversion can be ill-conditioned and approximate improvement does not guarantee monotonic progress in every batch. Lagoudakis and Parr present the method.

The deadly triad and Baird’s example

The deadly triad combines function approximation, bootstrapping and off-policy learning. Their combination diverges in some problems, even with a linear function. This does not mean every instance with those ingredients diverges, or that removing one part solves every practical difficulty.

InteractiveSeven states and a destabilizing value

Preparing the counterexample.

Examine updates and compare what is learned under different rules and distributions.

Baird’s counterexample uses seven states and shared features to construct an unstable off-policy update. Target and behavior policies induce different distributions: the distribution used in projection need not be stationary for the target operator, so the preceding contraction proof no longer applies. Importance correction can make the average represent the target policy, but does not itself make projection contractive under the behavior distribution. Exact features, probabilities, weights and steps are specified in the figure and lab; an isolated plot from one finite run does not prove a theorem.

The difficulty also reaches control: linear Q-learning variants can diverge in this counterexample. The evaluation proof just seen and a control agent are different updates; Maei and colleagues study the control example and alternatives.

A common parameterization has eight weights for seven state values, so the feature matrix lacks full column rank. Weights can contain directions that change no predicted value. A weight norm alone therefore does not describe all value error, and results requiring invertible CC should not automatically be applied or each weight required to converge to zero.

Three different errors and gradient corrections

Value error compares Φw\Phi w with vπv^\pi. Squared Bellman error compares TπΦwT^\pi\Phi w with Φw\Phi w. Projected Bellman error compares ΠDTπΦw\Pi_D T^\pi\Phi w with Φw\Phi w. One being small does not guarantee the others are, except under additional assumptions and bounds.

For linear approximation and invertible CC, mean squared projected Bellman error can be written (b−Aw)TC−1(b−Aw)(b-Aw)^{\mathsf T}C^{-1}(b-Aw). Gradient TD methods use an auxiliary vector to estimate terms arising when differentiating this quantity. TDC is a two-timescale variant; its guarantees require, among other conditions, coverage, suitable features and matrices, and appropriate steps. Renaming TD to TDC does not ensure stability in every configuration. See Sutton and colleagues and later analysis by Ghiassian and colleagues.

For example, with a behavior transition, features ϕ,ϕ′\phi,\phi' and importance ratio ρ=π(A∣S)/b(A∣S)\rho=\pi(A\mid S)/b(A\mid S), one one-step TDC version uses previous values of ww and auxiliary hh in both updates:

δ=R+γϕ′Tw−ϕTw,h←h+β(ρδ−ϕTh)ϕ,w←w+αρ[δϕ−γϕ′(ϕTh)].\begin{aligned} \delta&=R+\gamma\phi'^{\mathsf T}w-\phi^{\mathsf T}w,\\ h&\leftarrow h+\beta\bigl(\rho\delta-\phi^{\mathsf T}h\bigr)\phi,\\ w&\leftarrow w+\alpha\rho\bigl[\delta\phi-\gamma\phi'(\phi^{\mathsf T}h)\bigr]. \end{aligned}

The formula assumes target policy coverage by behavior and ϕ′=0\phi'=0 on true termination. The auxiliary estimates a correction, not an independent second value table; steps and rank conditions matter for the theoretical result.

Another family, emphatic TD, changes update weights using emphasis dependent on trajectory following, interest in states and importance ratios. The resulting weighting can recover stability properties not provided by behavior distribution alone. Its guarantees also require coverage, feature and step assumptions; see Sutton, Mahmood and White.

Another difficulty arises when minimizing unprojected Bellman error from samples. The gradient of a squared conditional expectation contains a product of two expectations depending on the same state; reusing one transition for both factors can introduce bias. Obtaining two independent next states from the same state and action is the double-sampling problem, and is not always possible with collected data. Gradient TD methods address a different objective and have their own assumptions.

Fitting a function by iteration

Fitted Q iteration turns each backup into supervised regression. Freeze QkQ_k and compute for each batch transition

yi=ri+γ1{no terminoˊ}max⁡aQk(si′,a),y_i=r_i+\gamma\mathbf 1\{\text{no terminó}\}\max_a Q_k(s'_i,a),

and fit a new regressor Qk+1Q_{k+1} to predict yiy_i from (si,ai)(s_i,a_i). An external cutoff does not itself remove continuation. Trees, linear regression and networks give different families; evaluate the resulting policy on separate trajectories and do not confuse batch error with out-of-sample performance. Ernst, Geurts and Wehenkel study tree-based batch methods and guarantees under specific conditions, which do not automatically transfer to every ExtraTrees implementation.

In DQN, replay and target networks help control correlation among samples and target movement. These are design choices, not a general proof of convergence against the deadly triad. A dataset lacking coverage cannot reliably reveal consequences of actions it never contains.

Labs

The first experiment implements Mountain Car with state (posición, velocidad), three actions and eight shifted tilings. Each state–action pair activates one tile per layer; explicit dictionary keys avoid hash collisions. The 200-step external cutoff stops sampling, but only reaching the goal removes bootstrapping. This short run checks the mechanism, not a promise that the policy already solves the environment.

[ ]Semi-gradient SARSA and tiles in Mountain CarBrowser
import math
import random

def tiles(position,velocity,action):
    return [(action,t,math.floor((position+1.2)/.22+t/8),
             math.floor((velocity+.07)/.014+((3*t)%8)/8)) for t in range(8)]

def q_value(weights,state,action):
    return sum(weights.get(key,0.0) for key in tiles(*state,action))

def mountain_step(state,action):
    position,velocity=state
    velocity=max(-.07,min(.07,velocity+(action-1)*.001-.0025*math.cos(3*position)))
    position=max(-1.2,min(.6,position+velocity))
    if position<=-1.2 and velocity<0: velocity=0.0
    return (position,velocity),-1.0,position>=.5

def select(weights,state,epsilon,rng):
    if rng.random()<epsilon: return rng.randrange(3)
    values=[q_value(weights,state,a) for a in range(3)]
    maximum=max(values)
    return rng.choice([a for a,v in enumerate(values) if v==maximum])

def train_car(seed,episodes=20,epsilon=.1,alpha=.1):
    rng=random.Random(seed); weights={}; lengths=[]; successes=0
    for _ in range(episodes):
        state=(rng.uniform(-.6,-.4),0.0)
        action=select(weights,state,epsilon,rng)
        for t in range(200):
            nxt,reward,terminated=mountain_step(state,action)
            next_action=select(weights,nxt,epsilon,rng) if not terminated else None
            target=reward if terminated else reward+q_value(weights,nxt,next_action)
            delta=target-q_value(weights,state,action)
            for key in tiles(*state,action): weights[key]=weights.get(key,0.0)+alpha/8*delta
            if terminated:
                successes+=1; break
            if t==199: break  # truncamiento externo: el objetivo ya incluyó bootstrap
            state,action=nxt,next_action
        lengths.append(t+1)
    return weights,lengths,successes

assert len(tiles(-.5,0,1))==len(set(tiles(-.5,0,1)))==8
assert mountain_step((-1.2,-.07),0)[0]==(-1.2,0.0)
weights,lengths,successes=train_car(1201)
print('Mountain Car: episodios',len(lengths),'éxitos',successes,
      'pasos medios',round(sum(lengths)/len(lengths),2),'teselas visitadas',len(weights))

LSTD constructs a linear system from transitions. The example has two states, fixed policy, stationary distribution (0,6; 0,4), independent features [1,s] and discount 0,9. We compare the theoretical solution with one sample from the same chain. Regularization applies only if requested and changes the system solved; here it is zero.

[ ]LSTD: population system and on-policy sampleBrowser
import random
import numpy as np

P=np.array([[.8,.2],[.3,.7]])
r=np.array([1.,0.]); gamma=.9
Phi=np.array([[1.,0.],[1.,1.]])
D=np.diag([.6,.4])
A=Phi.T@D@(Phi-gamma*P@Phi)
b=Phi.T@D@r
theta_true=np.linalg.solve(A,b)
value_true=np.linalg.solve(np.eye(2)-gamma*P,r)
assert np.allclose(Phi@theta_true,value_true,atol=1e-11,rtol=0)

def lstd(phi,rewards,next_phi,gamma,reg=0.0):
    A=phi.T@(phi-gamma*next_phi)/len(phi)+reg*np.eye(phi.shape[1])
    b=phi.T@rewards/len(phi)
    return np.linalg.solve(A,b),A,b

rng=random.Random(1202); state=1 if rng.random()<.4 else 0
current=[]; following=[]; rewards=[]
for _ in range(4000):
    nxt=0 if rng.random()<P[state,0] else 1
    current.append(Phi[state]); following.append(Phi[nxt]); rewards.append(r[state])
    state=nxt
theta,As,bs=lstd(np.asarray(current),np.asarray(rewards),np.asarray(following),gamma)
assert np.allclose(As@theta,bs,atol=1e-10,rtol=0)
print('θ poblacional',np.round(theta_true,6),'θ LSTD muestral',np.round(theta,6),
      'error de valor',round(float(np.linalg.norm(Phi@theta-value_true)),6))

Baird’s counterexample has seven states and eight features: the six upper are (2eᵢ+e₈)/√5 and the lower (e₇+2e₈)/√5. The target policy always chooses the solid transition to the lower state; behavior chooses it with probability 1/7 and distributes the rest uniformly among the six upper states. Rewards are zero and γ=0,99. We calculate exact expected updates under the uniform behavior distribution: these are not a sampled trajectory. Eight features in seven states make the covariance matrix singular, so a theorem requiring full rank does not automatically apply.

[ ]Baird: expected TD and TDCBrowser
import numpy as np
import math

Phi=np.zeros((7,8))
for s in range(6): Phi[s,s]=2; Phi[s,7]=1
Phi[6,6]=1; Phi[6,7]=2
Phi/=math.sqrt(5)
gamma=.99; C=Phi.T@Phi/7
initial=np.ones(8); initial[6]=10

def mean_step(w,h,alpha,beta,corrected):
    delta=gamma*(Phi[6]@w)-Phi@w
    td=Phi.T@delta/7
    if corrected:
        # E_b[ρ φ'(φᵀh)] = φ_sólido · E_b[φᵀh].
        correction=gamma*Phi[6]*float(np.mean(Phi@h))
        return w+alpha*(td-correction),h+beta*(td-C@h)
    return w+alpha*td,h

print('Rango de C',np.linalg.matrix_rank(C),'de',len(initial),'dimensiones')
for label,corrected in [('TD',False),('TDC',True)]:
    w=initial.copy(); h=np.zeros(8)
    for t in range(10001):
        if t in (0,100,1000,10000):
            print(label,'paso',t,'norma pesos',round(float(np.linalg.norm(w)),6),
                  'RMS valor',round(float(np.sqrt(np.mean((Phi@w)**2))),6))
        if t<10000: w,h=mean_step(w,h,.01,.05,corrected)

True value is zero, but a null direction of Φ can leave nonzero parameters without changing values. Hence both predictions and weight norm are shown. TDC needs coverage and step and rank conditions for its guarantees; this finite expected calculation does not prove general convergence or independence of the two estimates.

Fitted Q iteration freezes the previous model before constructing targets and then fits trees. We compare linear LSPI on the same sample of 600 transitions of a pendulum with actions −2, 0, 2. Initial evaluation positions use another seed. The 50-step horizon is only for evaluation: dynamics are continuing and training targets retain bootstrapping. See Ernst, Geurts and Wehenkel; the guarantee of their totally random tree construction is not automatically attributed to ExtraTrees.

[ ]FQI with ExtraTrees versus LSPIBrowser
import numpy as np
from sklearn.ensemble import ExtraTreesRegressor

actions=np.array([-2.,0.,2.]); discount=.95
def angle_normalize(theta):
    return (theta+np.pi)%(2*np.pi)-np.pi

def pendulum_step(state,action):
    theta=state[:,0]; velocity=state[:,1]; torque=actions[action]
    reward=-(angle_normalize(theta)**2+.1*velocity**2+.001*torque**2)
    next_velocity=np.clip(velocity+(15*np.sin(theta)+3*torque)*.05,-8,8)
    next_theta=angle_normalize(theta+next_velocity*.05)
    return np.column_stack((next_theta,next_velocity)),reward

def sa_features(state,action):
    theta=state[:,0]; velocity=state[:,1]
    base=np.column_stack((np.ones(len(state)),np.sin(theta),np.cos(theta),velocity/8,(velocity/8)**2))
    out=np.zeros((len(state),15))
    for a in range(3):
        selected=action==a; out[selected,5*a:5*(a+1)]=base[selected]
    return out

def greedy_linear(state,theta):
    values=np.column_stack([sa_features(state,np.full(len(state),a))@theta for a in range(3)])
    return np.argmax(values,axis=1)

def tree_q(model,state,action):
    return model.predict(np.column_stack((state,actions[action])))

rng=np.random.default_rng(1203); N=600
states=np.column_stack((rng.uniform(-np.pi,np.pi,N),rng.uniform(-8,8,N)))
chosen=rng.integers(0,3,N)
next_states,rewards=pendulum_step(states,chosen)
inputs=np.column_stack((states,actions[chosen]))
model=None
for iteration in range(5):
    if model is None: targets=rewards.copy()
    else:
        next_q=np.column_stack([tree_q(model,next_states,np.full(N,a)) for a in range(3)])
        targets=rewards+discount*np.max(next_q,axis=1)
    model=ExtraTreesRegressor(n_estimators=6,max_depth=8,min_samples_leaf=5,
                              random_state=1204+iteration,n_jobs=1)
    model.fit(inputs,targets)

features=sa_features(states,chosen)
theta=np.zeros(15)
for iteration in range(5):
    next_action=greedy_linear(next_states,theta)
    next_features=sa_features(next_states,next_action)
    A=features.T@(features-discount*next_features)/N+1e-3*np.eye(15)
    b=features.T@rewards/N
    theta=np.linalg.solve(A,b)

def rollout(method,seed,episodes=12,horizon=50):
    rng=np.random.default_rng(seed)
    state=np.column_stack((rng.uniform(-np.pi,np.pi,episodes),rng.uniform(-1,1,episodes)))
    total=np.zeros(episodes); factor=1.0
    for _ in range(horizon):
        if method=='fqi':
            q=np.column_stack([tree_q(model,state,np.full(episodes,a)) for a in range(3)])
            action=np.argmax(q,axis=1)
        else: action=greedy_linear(state,theta)
        state,reward=pendulum_step(state,action)
        total+=factor*reward; factor*=discount
    return float(np.mean(total)),float(np.std(total)),total

fqi_mean,fqi_std,fqi_returns=rollout('fqi',1205)
lspi_mean,lspi_std,lspi_returns=rollout('lspi',1205)
assert np.all(np.isfinite(fqi_returns)) and np.all(np.isfinite(lspi_returns))
print('Transiciones train',N,'evaluación independiente',len(fqi_returns),'horizonte',50)
print('FQI retorno descontado',round(fqi_mean,4),'desviación',round(fqi_std,4))
print('LSPI retorno descontado',round(lspi_mean,4),'desviación',round(lspi_std,4))

Initial evaluation conditions are common to both methods and distinct from the fitting sample; the deviation describes those 12 returns, not calibrated population uncertainty. Changing representation, sample or seed can change the comparison. Regularization 10⁻³I changes LSPI’s system; it does not guarantee improved conditioning or invertibility of an arbitrary matrix. Equality with an unregularized equation is not assumed.

Exercises

ProofProjection does not amplify
Prove: Prove that the projected Bellman operator is a contraction in an appropriate norm.
0
S is finite, P is the transition matrix of a fixed policy, d is a strictly positive stationary distribution with dᵀP=dᵀ, 0≤γ<1 and T v=r+γPv. Π is orthogonal projection under the d-weighted inner product onto a fixed linear subspace of state functions.

Step 1 of 3. How is the norm of P applied to x bounded?

ProofFrom TD to a linear equation
Prove: Derive the LSTD system without confusing it with direct return regression.
0
For column features φ(S), approximate value φ(S)ᵀw and fixed policy, write φ=φ(S_t), φ′=φ(S_{t+1}) and δ=R+γφ′ᵀw−φᵀw. Expectations exist. At terminal take φ′=0.

Step 1 of 3. What is the zero mean TD-update condition?

NumericTD versus best projection
In two states, P=((0,8;0,2),(0,3;0,7)), mean reward r=(0,1), γ=0,9 and d=(0,6;0,4), using decimal commas. Approximate with one feature φ=(1,2). What is the TD fixed-point coefficient w as a decimal?
QuizWhich combination has a guarantee?
In a finite stationary MDP with γ<1 and bounded rewards, which conclusion is justified by classical results, adding their sampling and step conditions?
CodeSolve LSTD without symmetrizing A
Implement lstd(features,rewards,next_features,gamma,reg). Use NumPy: features and next_features are finite N×d matrices with N>0 and d>0; rewards is a finite vector of length N. Terminal rows of next_features are already supplied as zeros. gamma is finite in [0,1); reg is finite and nonnegative. Compute A=featuresᵀ(features−gamma·next_features)/N and b=featuresᵀrewards/N; return the vector solution to (A+reg·I)w=b using numpy.linalg.solve. Do not modify inputs or replace A with its symmetric part. Raise ValueError if shapes or values violate the contract. Propagate numpy.linalg.LinAlgError if solve raises it and also raise it if returned values are nonfinite: in Pyodide a singular matrix can return NaN. reg=0 represents the unregularized empirical fixed point; reg>0 changes the objective and invertibility is not guaranteed for arbitrary matrices.
def lstd(features, rewards, next_features, gamma, reg):
  pass
Shift+Enter to run
[ ]Check the two-state exampleBrowser
import numpy as np
P=np.array([[.8,.2],[.3,.7]])
gamma=.9
d=np.diag([.6,.4])
phi=np.array([[1.],[2.]])
r=np.array([0.,1.])
A=phi.T@d@(np.eye(2)-gamma*P)@phi
b=phi.T@d@r
v=np.linalg.solve(np.eye(2)-gamma*P,r)
w_td=np.linalg.solve(A,b)
w_projection=np.linalg.solve(phi.T@d@phi,phi.T@d@v)
print('A',A[0,0],'b',b[0],'TD',w_td[0])
print('Valor verdadero',v,'proyección',w_projection[0])