Expectimax search
Expectimax 搜索
Separate choices from chance, compute exact expected utility, and test cutoff, information and risk assumptions.
expectimaxA bad outcome can matter without deciding everything
A game offers a choice: take 4 points, or draw a ticket that gives 9 points half the time and 0 otherwise. The draw has expected score 4.5. Its worst possible score is 0. A player maximizing expected points chooses the draw; a player maximizing the worst possible score takes 4. The difference comes from the objective and the probability model.
Expectimax combines decision nodes, where the agent chooses the highest-valued action, with chance nodes, where values are averaged using outcome probabilities. Berkeley’s description gives these MAX and expectation backups and distinguishes chance from an adversary choosing a bad outcome. CS188, section 3.3
An expectation is an average under a model. It does not promise 4.5 points on the next draw, and the probabilities do not become correct just because the arithmetic is exact. This chapter makes both the tree calculation and its assumptions inspectable.
Decisions maximize; chance takes a weighted sum
Use a finite tree with observed states and one decision maker. A terminal node has known utility . At a MAX node the agent selects an action; at a chance node the environment selects an outcome according to the stated conditional probabilities. There are no intermediate rewards in this model: the terminal utility already represents everything the agent values about the outcome.
Let count remaining tree edges, including both action edges and chance-outcome edges. A nonterminal node reached with receives an estimate . A terminal node always receives its actual utility, even at depth zero. The recursion is
Here , and are the terminal, MAX and chance nodes; selects the child. The labels need not alternate rigidly. Two consecutive chance nodes can describe two random events. Their probabilities may depend on the complete preceding history encoded in the node; independence between events is not required.
At each chance node, the outcomes must be mutually exclusive and exhaustive for the modeled transition:
Two differently named events leading to the same child may be kept separately if they are genuinely disjoint events. Listing the same event twice would double-count it. Missing probability mass is not an implicit zero-utility outcome. If the inputs are relative weights, normalize them deliberately before supplying probabilities and explain what those weights mean.
For a complete finite tree with correct probabilities and terminal utilities, backward induction chooses a policy with maximum expected utility among the tree’s permitted choices. At a terminal node the value is known. A chance node averages the already computed continuation values; a MAX node chooses the best continuation. Applying those two steps back to the root proves the claim. With a depth cutoff, the same recursion solves the surrogate problem defined by at its artificial leaves. It need not choose the best action for the original full tree.
The order of information matters. Suppose two equally likely outcomes are observed before choosing between two actions. Their utilities are 9/0 for the first action and 0/9 for the second. After observing the outcome, the agent chooses the rewarding action and gets 9. If it must choose before observing, either action has expectation 4.5. In general,
For any fixed action, the pointwise maximum is at least its utility; averaging proves the inequality. A chance-then-MAX tree represents the observed-outcome decision. Using that tree when the outcome is hidden gives the agent information it does not have. Hidden-information problems need a representation that enforces which histories the agent can distinguish.
Use exact probabilities on a small tree
The complete program uses Python’s Fraction. Utilities, estimates and probabilities must be integers or Fraction values; booleans and floats are rejected. Write Fraction(numerator, denominator) to make the intended rational probability explicit. Chance rows must sum to exactly 1. The implementation does not silently rescale a malformed row.
The input is a finite acyclic tree or directed acyclic graph, encoded as a dictionary of string node IDs to (kind, data) pairs. MAX data contains ordered (action_label, child_id) pairs, chance data contains (probability, child_id) pairs, and terminal data is a utility. The code validates expanded rows and visited values. A zero-probability child is not visited; neither are children beyond a depth cutoff. This is not a validator for every record in an unused subtree.
A shared node may be reached with different remaining depths. Its preferred action can then differ because one visit reaches true terminal values while another reaches cutoff estimates. Decisions in the finite-horizon surrogate are therefore indexed by both node and remaining depth.
The result includes the root action when the root was expanded as MAX. A root chance node, a terminal root or a root cutoff has action None. Equal action values choose the first action in input order. used_cutoff records whether any explored positive-probability branch required an estimate, including branches not chosen by MAX. It is deliberately conservative: an estimate in a losing branch may still be relevant to whether that branch really loses.
from fractions import Fraction
def rational(value, label):
if type(value) not in (int, Fraction):
raise ValueError(label + ' must be an int or Fraction')
return Fraction(value)
def expectimax(tree, root, depth, estimate=None):
if type(depth) is not int or depth < 0:
raise ValueError('depth must be a nonnegative integer')
def visit(node, left):
if not isinstance(node, str) or node not in tree:
raise ValueError('a visited node needs a known string identifier')
kind, data = tree[node]
if kind == 'terminal':
return rational(data, 'utility'), None, False
if kind not in ('max', 'chance'):
raise ValueError('node kind must be terminal, max or chance')
if left == 0:
if estimate is None or node not in estimate:
raise ValueError('a nonterminal cutoff needs an estimate')
return rational(estimate[node], 'estimate'), None, True
if not isinstance(data, (list, tuple)) or not data:
raise ValueError('an expanded node needs nonempty children')
used_cutoff = False
if kind == 'max':
best, action, labels = None, None, set()
for name, child in data:
if not isinstance(name, str) or not name or name in labels:
raise ValueError('actions need distinct nonempty labels')
labels.add(name)
value, _, cut = visit(child, left - 1)
used_cutoff |= cut
if best is None or value > best:
best, action = value, name
return best, action, used_cutoff
outcomes = [(rational(p, 'probability'), child) for p, child in data]
if any(p < 0 or p > 1 for p, _ in outcomes):
raise ValueError('probabilities must lie in [0, 1]')
if sum(p for p, _ in outcomes) != 1:
raise ValueError('chance probabilities must sum exactly to one')
total = Fraction(0)
for p, child in outcomes:
if p == 0:
continue
value, _, cut = visit(child, left - 1)
total += p * value
used_cutoff |= cut
return total, None, used_cutoff
value, action, used_cutoff = visit(root, depth)
return {'value': value, 'action': action, 'used_cutoff': used_cutoff}
tree = {
'root': ('max', [('safe', 'four'), ('draw', 'coin')]),
'four': ('terminal', 4),
'coin': ('chance', [(Fraction(1, 2), 'zero'),
(Fraction(1, 2), 'nine')]),
'zero': ('terminal', 0),
'nine': ('terminal', 9),
}
result = expectimax(tree, 'root', 2)
assert result == {'value': Fraction(9, 2), 'action': 'draw', 'used_cutoff': False}
shallow = expectimax(tree, 'root', 1, {'coin': 0})
assert shallow == {'value': Fraction(4), 'action': 'safe', 'used_cutoff': True}
# A nonlinear utility on these outcomes: sqrt(0)=0, sqrt(4)=2, sqrt(9)=3.
risk_averse = dict(tree, four=('terminal', 2), nine=('terminal', 3))
assert expectimax(risk_averse, 'root', 2)['action'] == 'safe'
affine = {node: (kind, 2 * data + 7) if kind == 'terminal' else (kind, data)
for node, (kind, data) in tree.items()}
assert expectimax(affine, 'root', 2)['value'] == 16
print(result)
print(shallow)
print(expectimax(risk_averse, 'root', 2))
At depth 2 the draw’s value is exactly Fraction(9, 2), so the root chooses draw with no cutoff. At depth 1, the safe terminal still receives utility 4, but the chance node receives the supplied estimate 0. The root chooses safe and reports used_cutoff=True. Increasing depth changed which objective values were available; it did not revise the terminal score.
The final run changes the utility of the outcomes: 0 stays 0, 4 becomes 2, and 9 becomes 3. These are their square roots. Taking 4 points now gives utility 2; the draw gives expected utility 1.5, so safe wins. This is risk aversion with respect to points expressed by the chosen utility curve, while the algorithm still maximizes expected utility. Poole and Mackworth explain why utility need not be linear in an outcome measure and how concave utility represents such preferences. Foundations of Computational Agents, section 12.1.1
Let count recursive visits in the unfolded tree through the depth limit, and count the child entries inspected at expanded nodes, including zero-probability entries. The code takes bookkeeping and arithmetic operations. It revisits shared subtrees; it has no memo table. With maximum branching , the familiar worst case is visits. A single-child chain instead takes visits. Building chance-row lists and retaining action-label sets can require working storage on the recursion stack, excluding the input graph. These are operation and object counts: Fraction numerators and denominators can grow, increasing both arithmetic time and stored bits. Python’s recursion limit also restricts deep inputs.
An average needs the unseen outcomes
Suppose the safe alternative already has value 4. While evaluating an equally weighted two-outcome draw, the first revealed child has utility 0. This does not establish that the draw is worse. If the unseen child is 0, the expectation is 0; if it is 12, the expectation is 6. Both are compatible with the value inspected so far. A MIN node could be bounded by one small child; an expectation node cannot use that rule unchanged. Berkeley notes that finite value bounds can make some chance-node pruning possible. CS188, section 3.3
If explored outcomes contribute weighted sum and remaining probability mass , and every unexamined child value is known to lie in , then
An upper bound below the incumbent MAX value can rule out that chance branch. Equality can be pruned only if the specified tie policy permits it. The bounds must cover the actual child values, including any cutoff estimates used by the search. Without bounds on an unseen outcome with positive probability, a partial expectation alone cannot establish a finite upper or lower bound. This does not forbid pruning elsewhere in a mixed tree or ignoring zero-probability outcomes. The program above evaluates every positive-probability outcome and implements no chance pruning.
Utility scales have another consequence. Replace every terminal utility by with . At chance nodes, normalized probabilities give an added constant of exactly ; at MAX nodes, a positive multiplier preserves the ordering. Thus, on the same full tree,
The maximizing actions and ties are preserved. In a truncated tree, transform every cutoff estimate the same way to retain this guarantee. Changing the utility of some leaves but leaving estimates on the old scale mixes two objectives. The code checks the transformation : its root value becomes 16 and the draw remains preferred. A strictly increasing nonlinear transform need not preserve expected-utility choices, as the square-root example already shows. Pointwise rankings of certain outcomes are insufficient to rank uncertain mixtures.
This implementation has MAX and chance nodes only. It does not model an adversarial MIN player, general multiplayer utilities, or hidden information. Adding explicit MIN nodes gives a specified expectiminimax model, but probabilities for genuinely random outcomes remain separate from adversarial choices. Treating an opponent as random requires a behavioral distribution conditional on what that opponent knows; “not optimal” does not mean “uniformly random.”
Check the average and the information available
- Calculate the safe and draw values under raw points, under their square-root utilities, and under . Which choices change?
- For the supplied tree, what are the results at root depth 0 with root estimate 8, at depth 1 with chance-node estimate 0, and at a terminal root with depth 0?
- A partially evaluated chance node has , unexamined mass , and certified remaining child bounds . Can it beat an incumbent value 5? What if no finite upper bound is known?
- Two outcomes are equally likely, and two actions have utility pairs
(9,0)and(0,9). Explain the value before and after observing the outcome. Does ordinary expectimax automatically solve the hidden-information version?
Answers and checks
- Raw values are 4 and 9/2, so choose the draw. Square-root utility gives 2 and 3/2, so choose safe. The affine transformation gives 15 and 16, so the draw remains preferred. Apply utility before averaging: the average of the square roots is not the square root of the average.
- At root depth 0 the result is value 8, no action and
used_cutoff=True. At depth 1, safe wins with value 4 andused_cutoff=True. The terminal nodefourat depth 0 returns actual utility 4, no action andused_cutoff=False, even if the estimate dictionary contains a different entry for it. A terminal value has priority over a cutoff. - The remaining contribution lies in , so the full value lies in . It cannot beat 5 and may be pruned for root action selection. With no finite upper bound, the unseen positive-probability outcome can make the expectation exceed 5; the partial sum alone is insufficient.
- Committing to either action before seeing the outcome gives 9/2. Observing first lets the agent choose the action worth 9 in each outcome. A chance-then-MAX tree gives that information to the decision maker; using it for an unobserved outcome would overstate the available value. The model must enforce the actual information structure.
Audit the chance model as carefully as the search
The two sources supply the MAX/chance distinction and the utility interpretation. The point scores, cutoff example and pruning interval here were constructed for teaching. The accompanying tests enumerate finite deterministic policies indexed by node and remaining depth, with exact rational probabilities and independently of recursive MAX backups, and compare their best expectation with the program. They also check affine transformations, nonlinear utility reversal, zero-probability branches and depth boundaries.
When replacing the toy table with an estimated environment, evaluate whether the probabilities match the situations in which the policy is used. Preserve the state variables needed to condition those probabilities. Compare the search’s chosen action against an exhaustive small-tree oracle before trusting larger instances. For repeated states and longer horizons, Markov decision processes and Bellman equations organize related calculations, with additional conventions for rewards, time and state information.
Make a prediction, then check
A chance node has a first child of utility 0 and an unseen child carrying probability 1/2. Can it be pruned from that observation as if it were MIN?
Learning objectives
- Distinguish MAX, chance and terminal nodes, compute expectations with explicit depth units, and identify heuristic cutoffs.
- Audit probabilities and information timing by policy enumeration, and explain chance-pruning conditions and effects of utility transformations.
Prerequisites & connections
Explore related knowledge →References
- CS188 Textbook: 3.3 Expectimax
University of California, Berkeley; CS188 course staff - Artificial Intelligence: Foundations of Computational Agents, third edition, 12.1 Preferences and Utility
David L. Poole; Alan K. Mackworth · 2023
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable examples, independent finite-game oracles, bilingual review and a second Codex agent cross-check; not independent human peer review.
- Reread the migrated bilingual articles paragraph by paragraph for MAX/chance recursion, history-conditional probabilities, observation timing, terminal priority, edge-counted depth, zero-mass skipping, conservative cutoff flags, (node, remaining depth) policies, affine/nonlinear utility, chance intervals, complexity and four answers. Six anchors, five display equations and the complete Python block match.
- Eight repository tests passed using test_sample_articles.example to read src articles directly; temporary environment-variable and stub paths were removed. Coverage includes 2,025 two-lottery trees, 100 random nested decision trees and the shared-MAX-node DAG at differing depths: correct value 13/2 versus 9/2 with incorrectly coupled choices, including five root probabilities from 0 to 1.
- Both articles passed standalone MDX compilation with the repository math plugins, each producing five display equations without compiler messages or KaTeX errors. Fixed a discovered MDX formatting issue by placing details and summary tags on separate lines; targeted prose scanning passed. No whole-site check/build, rendered-page acceptance or independent human expert review is claimed; this record is a Codex technical check.
- Migration exposed an MDX compilation error from adjacent details/summary opening tags on one line. Split them in both languages, preserving code, formulas and answer content; recompilation and topic checks passed.
- The earlier cross-check found the policy oracle wrongly coupled actions by node alone. It now keys by (node, remaining depth) and verifies the shared DAG value 13/2; the production example was unaffected. Root checked the migrated fix and bilingual depth explanation.
- All 79 search checks, 105 article Python programs and the prose scan passed. Migration-stage written-status notes describe that earlier phase; this record registers the checked files after source review and binds their current hashes. All reviews are AI technical checks, not independent human peer review.
Source locations checked:
- CS188 Textbook: 3.3 Expectimax · Reopened CS188 sections 3.3 and 3.3.1 after migration; checked MAX/chance/terminal definitions at lines 88–91, chance-pruning limitations at line 103, and mixed-layer discussion. The implementation uses one decision maker with observed states, not general expectiminimax.
- Artificial Intelligence: Foundations of Computational Agents, third edition, 12.1 Preferences and Utility · Reopened Poole/Mackworth section 12.1.1 after migration, inspecting lines 101–142 for utility linearity in probabilities, utility scales, and concavity. Normalized lotteries were previously read at lines 28–29. Positive-affine induction and the square-root point example were independently derived and executed.
Related topics