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 assigns known probabilities summing to one to consequences . Mixture first chooses between two lotteries with probabilities and . Expected utility theory represents preference over lotteries as
For finitely many consequences, the von Neumann–Morgenstern representation follows from four axioms:
- Completeness: any two lotteries are comparable, including indifference.
- Transitivity: if you weakly prefer to and to , you weakly prefer to .
- Continuity: if , a mixture of and is indifferent to .
- Independence: for , if and only if .
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: , with . Thus a utility difference does not permit comparisons of satisfaction between people without further assumptions.
To see the proof mechanism, order consequences from best to worst . Normalize and . By continuity, every intermediate consequence is indifferent to some mixture . Replacing each consequence by that mixture and applying independence reduces any lottery to a mixture of extremes whose probability of the best outcome is . 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 , choosing B over A implies , 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, . Preferring black or yellow to red or yellow requires , 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 is a monetary consequence and is continuous and strictly increasing on an interval containing outcomes, certainty equivalent uniquely satisfies . The risk premium is . Concave utility expresses risk aversion: by Jensen, , so .
Risk attitude may vary with wealth. If is twice differentiable and , Arrow–Pratt absolute risk aversion is . For , , it equals ; for , defined only for , it equals . For a small mean-zero perturbation, the premium is approximately , 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 around : the linear term vanishes because , leaving apart from the remainder. If certainty equivalent is , also expand . Equating both expressions gives . The local conclusion depends on perturbation scale and ; it is not exact for every lottery.
Betting a fraction of wealth
With probability you win units per unit wagered and with probability lose the stake. If you wager fraction of wealth, multipliers are and . For , expected log growth is
On that domain, . The interior solution of is ; if it is not positive, the best admissible fraction is . Betting all wealth, , yields zero wealth after a loss and expected log growth . With even odds, gives . The Kelly criterion maximizes expected log growth under the model; it does not eliminate losses or replace management of constraints, errors in , 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 or ; 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 wealth remains strictly positive at each finite horizon. Exact drawdown probability is calculated by dynamic programming and checks the simulation. With 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 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.
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-12Bayesian decisions and trees
Let be the uncertain state, an action, and its utility. If is observed before acting, the Bayesian rule chooses . If 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 and signal with an arrow encoding the test distribution. A later patch decision receives but not ; utility depends on action and . To value the decision, first obtain , then maximize for each signal and only then average over . Maximizing separately in branches before observing it would value perfect information instead of the actual test. Operation order expresses an information constraint, not just a drawing convention.
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.
"""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.
"""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 as signal, define
The sample expected value of information is and perfect information value is . Always . For the first inequality, after observing you can ignore and repeat the initial optimal action. For the second, every is bounded by : conditioning on , maximizing, and averaging gives . 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 ; do not subtract money directly from a utility difference.
Preparing the value-of-information calculation.
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
Step 1 of 3. Why can value with the signal not be lower than value without it?
def solve(tree):
# Devuelve (utilidad esperada óptima, diccionario de decisiones).
raise NotImplementedError
import math
equivalente=-50*math.log((1+math.exp(-2))/2)
print('Equivalente cierto:',equivalente,'prima de riesgo:',50-equivalente)