Module contents
Lesson 1 of 37Core 90 min

Deciding under uncertainty: expected utility and the value of information

Before learning, formulate a decision: expected utility, risk, Bayesian decisions, and information value. Solve decision trees and connect a single choice to the agent–environment loop.

After this lesson you can

  • State von Neumann–Morgenstern axioms and the representation theorem.
  • Calculate certainty equivalents, risk premiums, and Kelly fractions.
  • Solve decision trees and influence diagrams by backward induction.
  • Calculate EVPI and EVSI and prove information value is nonnegative.
  • Formulate an agent–environment loop and discuss limits of scalar reward.

Before you start

Before learning, decide

A service has a vulnerability. You can patch it now with a known interruption, or wait and risk exploitation. A scanner can reduce uncertainty but takes time and resources. Predicting exploitation probability accurately helps, but does not yet say what to do: each action’s consequences and information available before choosing matter too.

This lesson builds the single-decision case. Later we repeat the cycle: actions change the environment, new observations arrive, and the agent chooses again. Decision theory supplies the rule for comparing alternatives; reinforcement learning studies sequential decisions when future consequences matter and the model is often unknown.

Lotteries and coherence

A finite lottery L=(p1,x1;…;pn,xn)L=(p_1,x_1;\ldots;p_n,x_n) assigns known probabilities pi≥0p_i\geq 0 summing to one to consequences xix_i. Mixture λL+(1−λ)M\lambda L+(1-\lambda)M first chooses between two lotteries with probabilities λ\lambda and 1−λ1-\lambda. Expected utility theory represents preference ⪰\succeq over lotteries as

L⪰M⟺∑ipiu(xi)≥∑jqju(yj).L\succeq M\quad\Longleftrightarrow\quad \sum_i p_i u(x_i)\geq\sum_j q_j u(y_j).

For finitely many consequences, the von Neumann–Morgenstern representation follows from four axioms:

  1. Completeness: any two lotteries are comparable, including indifference.
  2. Transitivity: if you weakly prefer LL to MM and MM to NN, you weakly prefer LL to NN.
  3. Continuity: if L≻M≻NL\succ M\succ N, a mixture of LL and NN is indifferent to MM.
  4. Independence: for 0<λ≤10<\lambda\leq1, L⪰ML\succeq M if and only if λL+(1−λ)N⪰λM+(1−λ)N\lambda L+(1-\lambda)N\succeq\lambda M+(1-\lambda)N.

The last axiom says adding the same external possibility to both options does not reverse their order. If at least two consequences are not indifferent, representing utility is unique up to a positive affine transformation: v(x)=au(x)+bv(x)=a u(x)+b, with a>0a>0. Thus a utility difference does not permit comparisons of satisfaction between people without further assumptions.

To see the proof mechanism, order consequences from best x+x^+ to worst x−x^-. Normalize u(x+)=1u(x^+)=1 and u(x−)=0u(x^-)=0. By continuity, every intermediate consequence is indifferent to some mixture u(x)x++(1−u(x))x−u(x)x^+ +(1-u(x))x^-. Replacing each consequence by that mixture and applying independence reduces any lottery to a mixture of extremes whose probability of the best outcome is ∑ipiu(xi)\sum_i p_i u(x_i). Transitivity compares those mixtures. This is a sketch for finite consequences; infinite spaces need additional assumptions.

The theory is normative under those axioms, not a psychological law. In the Allais paradox many prefer a sure gain over a higher-prize lottery and, when a common consequence changes, reverse the choice predicted by independence. Ellsberg’s paradox illustrates another difficulty: if probabilities themselves are ambiguous, one distribution may not reflect model uncertainty. Prospect theory models, among other phenomena, reference-point dependence and asymmetric treatment of gains and losses. An artificial agent needs explicit coherent preferences and constraints for an interpretable criterion; this does not require assuming an arbitrary utility faithfully captures human aims.

A specific Allais variant in Kahneman and Tversky compares A: 2500 with probability 0.33, 2400 with 0.66, and zero with 0.01, against B: 2400 for sure. Another problem compares C: 2500 with probability 0.33 and zero otherwise, against D: 2400 with probability 0.34 and zero otherwise. The source reports 72 responses for each hypothetical problem: 82% chose B in the first and 83% chose C in the second. With u(0)=0u(0)=0, choosing B over A implies 0,34u(2400)>0,33u(2500)0{,}34u(2400)>0{,}33u(2500), while choosing C over D implies the opposite inequality. These are results from that study, not universal proportions.

In Ellsberg’s urn are 30 red balls and 60 black or yellow in unknown proportions. Consider bets with the same prize. Preferring red to black requires, under one subjective probability, P(R)>P(N)P(R)>P(N). Preferring black or yellow to red or yellow requires P(N)+P(A)>P(R)+P(A)P(N)+P(A)>P(R)+P(A), the opposite. Choosing the known-probability event in both comparisons can express ambiguity aversion that one subjective probability and the same utilities cannot represent in those choices.

Curvature, risk, and certainty equivalent

If XX is a monetary consequence and uu is continuous and strictly increasing on an interval containing outcomes, certainty equivalent cc uniquely satisfies u(c)=E[u(X)]u(c)=\mathbb E[u(X)]. The risk premium is E[X]−c\mathbb E[X]-c. Concave utility expresses risk aversion: by Jensen, E[u(X)]≤u(E[X])\mathbb E[u(X)]\leq u(\mathbb E[X]), so c≤E[X]c\leq\mathbb E[X].

InteractiveOne lottery, different utilities
  • utility of mean prize
  • expected utility at mean prize
  • certainty equivalent

The lottery pays prize 1 with probability p and prize 2 with probability 1−p. Functions: u(x)=x, u(x)=log(1+x), and u(x)=1−exp(−αx); the logarithmic case has initial wealth 1. The premium is E[x] minus the certainty equivalent. Jensen compares u(E[x]) with E[u(x)]; utility units depend on its scale.

Utility function
0
100
0.50
0.02
Expected prize
50.000
Expected utility
0.4323
Certainty equivalent
28.311
Risk premium
21.689
Adjust prizes and probability; compare expected value with certainty equivalent on the utility curve.

Risk attitude may vary with wealth. If uu is twice differentiable and u′>0u'>0, Arrow–Pratt absolute risk aversion is A(w)=−u′′(w)/u′(w)A(w)=-u''(w)/u'(w). For u(w)=1−e−awu(w)=1-e^{-aw}, a>0a>0, it equals A(w)=aA(w)=a; for u(w)=log⁡wu(w)=\log w, defined only for w>0w>0, it equals 1/w1/w. For a small mean-zero perturbation, the premium is approximately 12A(w)Var⁡(X)\tfrac12 A(w)\operatorname{Var}(X), provided derivatives and Taylor remainder justify the approximation. At equal mean, increased dispersion in convex order raises the premium for a fixed concave utility; variance alone cannot order all distributions.

To obtain that approximation, expand E[u(w+X)]\mathbb E[u(w+X)] around ww: the linear term vanishes because E[X]=0\mathbb E[X]=0, leaving u(w)+12u′′(w)E[X2]u(w)+\tfrac12u''(w)\mathbb E[X^2] apart from the remainder. If certainty equivalent is w−πw-\pi, also expand u(w−π)≈u(w)−u′(w)πu(w-\pi)\approx u(w)-u'(w)\pi. Equating both expressions gives π≈−12u′′(w)Var⁡(X)/u′(w)\pi\approx-\tfrac12u''(w)\operatorname{Var}(X)/u'(w). The local conclusion depends on perturbation scale and u′(w)>0u'(w)>0; it is not exact for every lottery.

Betting a fraction of wealth

With probability 0<p<10<p<1 you win b>0b>0 units per unit wagered and with probability 1−p1-p lose the stake. If you wager fraction ff of wealth, multipliers are 1+bf1+bf and 1−f1-f. For 0≤f<10\leq f<1, expected log growth is

g(f)=plog⁡(1+bf)+(1−p)log⁡(1−f).g(f)=p\log(1+bf)+(1-p)\log(1-f).

On that domain, g′′(f)<0g''(f)<0. The interior solution of g′(f)=0g'(f)=0 is f∗=(bp−(1−p))/bf^*=(bp-(1-p))/b; if it is not positive, the best admissible fraction is f=0f=0. Betting all wealth, f=1f=1, yields zero wealth after a loss and expected log growth −∞-\infty. With even odds, p=0,55p=0{,}55 gives f∗=0,1f^*=0{,}1. The Kelly criterion maximizes expected log growth under the model; it does not eliminate losses or replace management of constraints, errors in pp, or regime uncertainty.

This simulation uses 4,096 independent sequences of 200 even-odds bets, all with win probability 0.55 and a fixed seed. The same sequences are reused to compare fractions. Each step multiplies wealth by 1+f1+f or 1−f1-f; initial wealth is 1 and no leverage is used.

The lab calls drawdown reaching wealth at or below 0.1 at any point up to the horizon. This is a conventional threshold, not mathematical ruin: for 0≤f<10\leq f<1 wealth remains strictly positive at each finite horizon. Exact drawdown probability is calculated by dynamic programming and checks the simulation. With f=1f=1 one loss does lead to zero wealth. Estimated probability of an extreme drawdown can be zero simply because none occurred in a finite sample.

The theoretical optimum in this example is f∗=2p−1=0,1f^*=2p-1=0,1 and expected log growth per bet is approximately 0.005008. The quantile column shows terminal log wealth, not mean wealth. Edge, independent bets, probabilities, and odds are assumed constant: changing any assumption changes the problem.

[ ]Kelly, drawdown, and terminal wealthBrowser
import math
import numpy as np

P = .55
N_TRAYECTORIAS = 4096
HORIZONTE = 200
SEMILLA = 2201
UMBRAL = .1
FRACCIONES = (0., .05, .1, .2, .5)

def crecimiento_esperado(p, f):
    if not 0 <= p <= 1 or not 0 <= f < 1:
        raise ValueError('Se exige 0 ≤ p ≤ 1 y 0 ≤ f < 1')
    return p * math.log1p(f) + (1-p) * math.log1p(-f)

def probabilidad_caida(p, f, horizonte, umbral):
    """Probabilidad exacta de tocar el umbral antes o en el horizonte."""
    if not 0 <= p <= 1 or not 0 <= f < 1 or horizonte < 0 or not 0 < umbral < 1:
        raise ValueError('Parámetros fuera del dominio')
    supervivencia = np.array([1.])
    for t in range(1, horizonte + 1):
        nueva = np.zeros(t + 1)
        nueva[:-1] += (1-p) * supervivencia
        nueva[1:] += p * supervivencia
        victorias = np.arange(t + 1)
        log_riqueza = victorias * math.log1p(f) + (t-victorias) * math.log1p(-f)
        nueva[log_riqueza <= math.log(umbral)] = 0.
        supervivencia = nueva
    return max(0., min(1., 1. - supervivencia.sum()))

rng = np.random.default_rng(SEMILLA)
victorias = rng.random((N_TRAYECTORIAS, HORIZONTE)) < P
kelly = max(0., min(1., 2*P-1))
print('Apuesta 1:1, p =', P, '; Kelly sin apalancamiento =', round(kelly, 6))
print('Caída: riqueza ≤', UMBRAL, 'alguna vez; riqueza inicial = 1')
print('f | crecimiento teórico | crecimiento simulado | caída simulada | caída exacta | log W final p10, p50, p90')
for f in FRACCIONES:
    pasos = np.where(victorias, math.log1p(f), math.log1p(-f))
    caminos = np.cumsum(pasos, axis=1)
    crecimiento = caminos[:, -1] / HORIZONTE
    caida = np.any(caminos <= math.log(UMBRAL), axis=1)
    cuantiles = np.quantile(caminos[:, -1], [.1, .5, .9])
    print(f'{f:.2f} | {crecimiento_esperado(P,f):.6f} | {crecimiento.mean():.6f} | '
          f'{caida.mean():.4f} | {probabilidad_caida(P,f,HORIZONTE,UMBRAL):.4f} | '
          + ', '.join(f'{v:.3f}' for v in cuantiles))

# f=1 no entra en log1p(-f): una sola pérdida deja riqueza cero para siempre.
ruina_exacta = 1 - P**HORIZONTE
ruina_simulada = np.any(~victorias, axis=1).mean()
print('f=1: probabilidad de riqueza cero antes del horizonte =',
      round(ruina_exacta, 8), '(exacta, redondeada);', round(ruina_simulada, 8), '(simulada)')
print('f=1: probabilidad exacta de sobrevivir las 200 rondas =', f'{P**HORIZONTE:.3e}')
assert abs(kelly - .1) < 1e-12
assert crecimiento_esperado(P, kelly) > crecimiento_esperado(P, .05)
assert crecimiento_esperado(P, kelly) > crecimiento_esperado(P, .2)
assert abs(probabilidad_caida(P, 0., HORIZONTE, UMBRAL)) < 1e-12

Bayesian decisions and trees

Let SS be the uncertain state, aa an action, and u(a,S)u(a,S) its utility. If Y=yY=y is observed before acting, the Bayesian rule chooses a∗(y)∈arg⁡max⁡aE[u(a,S)∣Y=y]a^*(y)\in\arg\max_a\mathbb E[u(a,S)\mid Y=y]. If YY is unobserved, maximize expectation under the prior. This connects to Bayes’ rule in statistical decision: maximizing utility equals minimizing loss when defined as its negative.

A tree alternates chance nodes, averaged using probabilities conditional on available information, and decision nodes, maximized. Solve from leaves backward. A policy assigns an action to every possible observation; it cannot use a hidden state not yet seen. In an influence diagram, chance, decision, and utility nodes show dependencies and what information reaches each decision. A missing information arrow matters: knowing a variable’s distribution is not observing its realization.

For example, represent exploitation SS and signal YY with an arrow S→YS\to Y encoding the test distribution. A later patch decision receives YY but not SS; utility depends on action and SS. To value the decision, first obtain P(S∣Y)P(S\mid Y), then maximize for each signal and only then average over YY. Maximizing separately in SS branches before observing it would value perfect information instead of the actual test. Operation order expresses an information constraint, not just a drawing convention.

InteractivePatch, wait, and scan
Initial decision
Patch now

Certain cost: 50.00.

Value: −50.00.

Wait without testing

Exploitation with probability 0.200 and damage 200.00.

Value: −40.00.

Run test

Cost: 0.00. Then choose according to the result.

Positive result · P=0.240

Posterior exploitation probability: 0.667

Expected utility: patch −50.00; wait −133.33.

Optimal decision: patch (−50.00).

Negative result · P=0.760

Posterior exploitation probability: 0.053

Expected utility: patch −50.00; wait −10.53.

Optimal decision: wait (−10.53).

Value before observing: −20.00.

Stage 0: tree and probabilities; stage 1: conditional values; stage 2: best action after each signal; stage 3: average signals and choose initially. Utility is negative money: patching prevents damage while waiting incurs it only if exploitation occurs. Ties favor waiting; initial ties retain the order wait, patch, test. Test accuracy is known and the test does not change the state.

0.20
50
200
0.80
0.90
0
3
Value of waiting
−40.00
Value of patching
−50.00
Value of testing
−20.00
Initial decision
test
Solve branches backward from consequences to the initial decision and change costs and probabilities.

The tree treats signal branches as observable and hides the damage state until after acting. A hidden chance node with downstream decisions is rejected: without information sets, solving each branch separately would give the agent knowledge it lacks. Impossible branches need no posterior.

[ ]PythonBrowser
"""Retroceso en árboles donde el decisor observa toda la historia disponible."""
import math

def has_decision(node):
    if node['type']=='decision': return True
    if node['type']=='chance': return any(has_decision(child) for _,_,child in node['branches'])
    return False

def solve(node):
    kind=node['type']
    if kind=='utility':
        value=float(node['value'])
        if not math.isfinite(value): raise ValueError('Utilidad no finita')
        return value,{}
    if kind=='chance':
        branches=node['branches']
        if not branches: raise ValueError('Nodo de azar vacío')
        if len({name for name,_,_ in branches})!=len(branches): raise ValueError('Ramas repetidas')
        probs=[float(p) for _,p,_ in branches]
        if any(not math.isfinite(p) or p<0 or p>1 for p in probs) or not math.isclose(sum(probs),1.,abs_tol=1e-12,rel_tol=0.):
            raise ValueError('Las probabilidades deben sumar uno')
        if not node.get('observed',False) and any(has_decision(child) for _,_,child in branches):
            raise ValueError('La incertidumbre oculta no puede preceder a una decisión en este árbol')
        value=0.; policy={}
        for (name,p,child) in branches:
            if p==0: continue
            child_value,child_policy=solve(child);value+=p*child_value
            if child_policy: policy[name]=child_policy
        return value,policy
    if kind=='decision':
        options=node['options']
        if not options: raise ValueError('Nodo de decisión vacío')
        if len({name for name,_ in options})!=len(options): raise ValueError('Acciones repetidas')
        results=[(name,*solve(child)) for name,child in options]
        name,value,following=max(results,key=lambda item:item[1])
        return value,{'choose':name,'then':following}
    raise ValueError('Tipo de nodo desconocido')

def utility(value): return {'type':'utility','value':value}
def chance(observed,branches): return {'type':'chance','observed':observed,'branches':branches}
def decision(options): return {'type':'decision','options':options}

def after_signal(posterior,test_cost):
    # El estado permanece oculto hasta después de elegir la acción.
    return decision([('parchear',utility(-30-test_cost)),
                     ('esperar',chance(False,[('daño',posterior,utility(-100-test_cost)),
                                              ('sin daño',1-posterior,utility(-test_cost))]))])

def observation_tree(p,sensitivity,specificity,test_cost=0.):
    hp=p*sensitivity;sp=(1-p)*(1-specificity);hn=p*(1-sensitivity);sn=(1-p)*specificity
    pos=hp+sp;neg=hn+sn
    positive=after_signal(hp/pos,test_cost) if pos else utility(0)
    negative=after_signal(hn/neg,test_cost) if neg else utility(0)
    return chance(True,[('positivo',pos,positive),('negativo',neg,negative)])

p=.4;sensitivity=.8;specificity=.9;test_cost=4.
without=after_signal(p,0.)
with_sample=observation_tree(p,sensitivity,specificity)
with_perfect=chance(True,[('daño',p,after_signal(1.,0.)),('sin daño',1-p,after_signal(0.,0.))])
base,base_policy=solve(without);sample,sample_policy=solve(with_sample);perfect,_=solve(with_perfect)
net,net_policy=solve(observation_tree(p,sensitivity,specificity,test_cost))
assert abs(base+30)<1e-12 and abs(sample+19.4)<1e-12 and abs(perfect+12)<1e-12
assert abs(sample-base-10.6)<1e-12 and abs(perfect-base-18)<1e-12 and abs(net+23.4)<1e-12
try:
    solve(chance(False,[('oculto',1.,decision([('acción',utility(1))]))]))
except ValueError:
    pass
else:
    raise AssertionError('El árbol reveló un estado oculto antes de decidir')
assert solve(chance(True,[('imposible',0.,utility(-999)),('cierto',1.,utility(2))]))[0]==2
print('Sin test:',round(base,2),base_policy)
print('Con test gratis:',round(sample,2),sample_policy)
print('Información perfecta:',round(perfect,2))
print('EVSI:',round(sample-base,2),'EVPI:',round(perfect-base,2),'valor neto:',round(net-base,2))
print('Política condicionada:',net_policy)

Independent enumeration traverses four possible policies depending only on the signal. EVSI is gross savings versus the best decision without observation; test cost is subtracted afterward. The same calculation permits inverted tests and impossible signals.

[ ]PythonBrowser
"""EVSI por enumeración de políticas dependientes solo de la señal."""
import itertools
import math

def voi(p,sensitivity,specificity,patch_cost=30.,harm=100.):
    if any(not 0<=v<=1 or not math.isfinite(v) for v in (p,sensitivity,specificity)):
        raise ValueError('Probabilidad fuera de [0,1]')
    if not math.isfinite(patch_cost) or not math.isfinite(harm) or not 0<=patch_cost<=harm:
        raise ValueError('Costes inválidos')
    masses=[(p*sensitivity,(1-p)*(1-specificity)),(p*(1-sensitivity),(1-p)*specificity)]
    base=min(p*harm,patch_cost)
    policies=[]
    for actions in itertools.product(('parchear','esperar'),repeat=2):
        risk=sum((h+s)*patch_cost if action=='parchear' else h*harm for action,(h,s) in zip(actions,masses))
        policies.append((risk,actions))
    sample,policy=min(policies,key=lambda x:x[0])
    perfect=p*patch_cost
    return {'base':base,'test':sample,'evsi':base-sample,'evpi':base-perfect,'policy':policy}

result=voi(.4,.8,.9)
assert abs(result['evsi']-10.6)<1e-12 and abs(result['evpi']-18)<1e-12
second=voi(.2,.8,.9,patch_cost=50.,harm=200.)
assert abs(second['base']-40)<1e-12 and abs(second['test']-20)<1e-12
assert abs(second['evsi']-20)<1e-12 and abs(second['evpi']-30)<1e-12
try:
    voi(.5,.8,.9,patch_cost=float('inf'),harm=float('inf'))
except ValueError:
    pass
else:
    raise AssertionError('Se admitieron costes infinitos')
for p in (i/100 for i in range(101)):
    for sensitivity,specificity in ((.8,.9),(1.,1.),(.5,.5),(0.,0.),(1.,0.)):
        r=voi(p,sensitivity,specificity)
        assert r['evsi']>=-1e-12 and r['evsi']<=r['evpi']+1e-12
        if sensitivity==specificity==.5: assert abs(r['evsi'])<1e-12
print('EVSI por enumeración:',round(result['evsi'],2),'EVPI:',round(result['evpi'],2))
print('Política para señal positiva y negativa:',result['policy'])
print('Segundo caso, parche 50 y daño 200: sin test',round(second['base'],2),
      'con test gratis',round(second['test'],2),'EVSI',round(second['evsi'],2),'EVPI',round(second['evpi'],2))
print('Malla comprobada: 101 priores y cinco pares de sensibilidad/especificidad')

The value of observing

Assume finite state and action sets, integrable utilities, and observation that does not change states, available actions, or consequences. With YY as signal, define

V0=max⁡aE[u(a,S)],VY=EY ⁣[max⁡aE[u(a,S)∣Y]],VS=ES ⁣[max⁡au(a,S)].V_0=\max_a\mathbb E[u(a,S)],\qquad V_Y=\mathbb E_Y\!\left[\max_a\mathbb E[u(a,S)\mid Y]\right],\qquad V_S=\mathbb E_S\!\left[\max_a u(a,S)\right].

The sample expected value of information is EVSI⁡=VY−V0\operatorname{EVSI}=V_Y-V_0 and perfect information value is EVPI⁡=VS−V0\operatorname{EVPI}=V_S-V_0. Always 0≤EVSI⁡≤EVPI⁡0\leq\operatorname{EVSI}\leq\operatorname{EVPI}. For the first inequality, after observing you can ignore YY and repeat the initial optimal action. For the second, every u(a,S)u(a,S) is bounded by max⁡a′u(a′,S)\max_{a'}u(a',S): conditioning on YY, maximizing, and averaging gives VY≤VSV_Y\leq V_S. Perfect information is a bound, not necessarily a physically available observation.

Gross information has positive value only if the signal improves action in states with positive probability; switching between tied alternatives is insufficient. If a signal has zero probability its posterior is irrelevant to the average and no division by zero is needed. A costly test may not pay: with linear monetary utility buy it only if EVSI exceeds cost. With nonlinear utility incorporate cost into each consequence before applying uu; do not subtract money directly from a utility difference.

InteractiveValue of a test

Preparing the value-of-information calculation.

Change prior, sensitivity, and specificity. The curve compares sample and perfect information in the same utility units.

In the patch example, loss 200, patch cost 50, and exploitation prior 0.2 give expected utility −40 without testing. With sensitivity 0.8 and specificity 0.9, positive signal probability is 0.24; exploitation probability is 2/3 after it and 1/19 after a negative signal. A free test yields −20, whereas perfect information yields −10. Thus EVSI is 20 and EVPI 30 in linear monetary utility. A test costing more than 20 is not worthwhile in this example. The preceding cell calculates these without using the hidden state to choose.

From one decision to the agent

In the agent–environment loop, at each step the agent receives an observation and reward, chooses an action, and the environment transitions to another state. The agent may not observe the full state. A policy maps available information to actions; horizon, discount, and reward summation determine which future consequences count.

The reward hypothesis proposes representing objectives with a scalar reward, as in Sutton and Barto, section 3.2. It is a hypothesis about objective formulation, not a guarantee an easily measured signal captures what is wanted. A robot maximizing distance can ignore safety; expected-profit reward can hide loss limits. Constraints, uncertainty, time preferences, and risk must appear explicitly in the formulation or decision mechanism.

With a known transition model you can plan; when unknown, interaction can learn a policy or model. Prediction, control, and policy evaluation are distinct tasks. The next lessons formalize states, actions, returns, and Markov decision processes before learning methods.

Exercises

ProofInformation cannot worsen a decision
Prove: Consider a finite nonempty action set with integrable utilities. Before acting you can observe a zero-cost signal X. Prove the value of sample information lies between zero and the value of perfect state information.
0
The policy can ignore the signal, and the same actions are available before and after observing it.

Step 1 of 3. Why can value with the signal not be lower than value without it?

NumericCertainty equivalent and risk premium
A lottery pays 100 or 0 with probability 1/2 each. For u(x)=1−exp⁡(−x/50)u(x)=1-\exp(-x/50), calculate the certainty equivalent.
NumericRisk premium
For the same lottery and utility as the previous exercise, calculate the risk premium: expected payoff minus certainty equivalent.
NumericKelly fraction
A bet pays 1:1 with win probability 0.55. You can stake a fixed fraction between 0 and 1 of wealth each round. Which fraction maximizes expected log growth?
QuizThe Allais tension
If a person reverses preference between two lotteries after mixing both with the same third lottery in the same proportion, which expected-utility axiom is violated?
CodeBackward induction
Implement solve(tree) and return (value, policy). A leaf is {'type':'utility','value': number}; a chance node is {'type':'chance','outcomes': [(probability, subtree), ...]}; a decision is {'type':'decision','id': identifier, 'actions': {name: subtree, ...}}. Each chance-node outcome is observed before any descendant decision; hidden states require another representation preserving the same decision on indistinguishable branches. The policy maps each decision reachable from the root under chosen actions to an action name; include decisions on all chance branches, including zero-probability ones. IDs are unique, trees finite, every list and dictionary nonempty, and probabilities nonnegative and summing to one. Break ties by choosing the dictionary’s first action.
def solve(tree):
  # Devuelve (utilidad esperada óptima, diccionario de decisiones).
  raise NotImplementedError
Shift+Enter to run
[ ]Certainty equivalent and premiumBrowser
import math
equivalente=-50*math.log((1+math.exp(-2))/2)
print('Equivalente cierto:',equivalente,'prima de riesgo:',50-equivalente)