Home Module 1 - Introduction to AI Module 2 - Problem-Solving & Search Module 3 - Uncertainty in AI Module 4 - Games & CSP Module 5 - AI in Practice & Ethics Important Questions
Module 3 of 5

Uncertainty in AI

Every algorithm in Modules 1–2 (except the brief detour into non-determinism) assumed a clean, fully-known world. Real environments are noisy, incomplete, and probabilistic. Module 3 builds the mathematical toolkit for reasoning under uncertainty: Bayesian networks for compactly representing and reasoning about probabilistic dependencies, decision theory and utility theory for choosing rationally under uncertainty, and Markov Decision Processes for sequential decision-making - the mathematical foundation beneath modern reinforcement learning.

11 Hours
7 Core Topics
CO3 - Evaluate one-dimensional & uncertainty-based problems (L4)
3.1

Uncertainty in AI: Sources and Dealing with Decision-Making

Classical logic-based AI assumes complete, certain knowledge - a statement is True or False, never "probably true." Real agents almost never have this luxury. Module 3 begins by cataloging why uncertainty arises and why probability theory, not logic alone, is the right mathematical tool.

📘 Definition

Uncertainty in AI refers to the agent's lack of complete, accurate knowledge about the current state of the world, the outcomes of its actions, or both - preventing it from deducing a guaranteed-correct course of action using pure logical inference alone.

Sources of Uncertainty

SourceDescriptionExample
Sensor noise/limitationsPhysical sensors are imprecise or have limited range/resolutionA camera misjudging distance in fog
Partial observabilityThe agent cannot perceive the complete state of the environmentA poker player not seeing opponents' cards
Stochastic/non-deterministic effectsActions don't always produce the same outcomeA robot's wheels slipping unpredictably
Incomplete or noisy dataTraining/decision data has errors, gaps, or is unrepresentativeMissing fields in a patient's medical record
Theoretical ignoranceWe may not even have a complete causal model of the domainImperfect models of disease progression
Practical/computational limitsEven with full information, exact reasoning may be computationally infeasibleExact inference in large Bayesian networks is NP-hard

Why Not Just Use Logic with "Maybe" Rules?

A natural first instinct is to write logical rules like "Toothache → Cavity." But this fails because the rule is neither always true (a toothache can have other causes) nor will adding more and more exception clauses (qualifications) ever produce a complete, manageable rule set - this is known as the qualification problem. Probability theory solves this elegantly by allowing degrees of belief rather than requiring exhaustive logical certainty.

⚠ The Qualification Problem

Trying to list every possible exception to a logical rule (e.g., every possible cause of a "check engine" light besides the obvious one) is practically impossible - there are too many rare interacting causes to enumerate exhaustively. Probability sidesteps this by summarizing all that uncertainty into a single likelihood number instead of requiring a complete logical theory.

Probability as a Summary of Ignorance

A probability statement like P(Cavity | Toothache) = 0.6 doesn't claim cavities cause toothaches 60% of the time in some deep causal sense - it summarizes the agent's degree of belief given everything else it doesn't know, observe, or have bothered to model. This is the foundation for the rest of Module 3.

💡 Real-world example

A self-driving car's perception system reports "80% confidence this is a pedestrian" rather than a binary yes/no - this probabilistic summary captures sensor noise, occlusion, and model uncertainty all at once, in a form the car's decision system can act on rationally.

Key Points

  • Uncertainty arises from sensor noise, partial observability, stochastic effects, incomplete data, and computational limits.
  • Pure logic fails due to the qualification problem - too many exceptions to enumerate.
  • Probability theory provides a principled, compact way to reason under uncertainty.

Interview Questions

Q. Why is probability theory preferred over plain logical rules for representing uncertain medical diagnosis knowledge?

Logical rules like "Toothache → Cavity" are neither universally true (many things besides cavities cause toothaches) nor completable into an exhaustive exception-free rule set, due to the qualification problem. Probability lets us instead express a degree of belief, e.g., P(Cavity|Toothache)=0.6, compactly summarizing all the unlisted causes and uncertainty without needing to enumerate them.

3.2

Bayesian Networks: Basics, Representation, and Reasoning

Storing a full joint probability distribution over n binary variables requires 2n−1 numbers - utterly intractable for even modest n. Bayesian Networks exploit the fact that most variables are only directly influenced by a few others, compactly encoding this structure.

📘 Definition

A Bayesian Network (BN) is a directed acyclic graph (DAG) where each node represents a random variable, each edge represents a direct probabilistic dependency, and each node is annotated with a Conditional Probability Table (CPT) giving P(node | its parents).

Core Components

  • Nodes - random variables (discrete or continuous), e.g., Burglary, Earthquake, Alarm.
  • Directed Edges - represent direct influence/dependency (parent → child); absence of an edge implies conditional independence given the parents.
  • CPT (Conditional Probability Table) - for each node X with parents Parents(X), specifies P(X | Parents(X)) for every combination of parent values.

Classic Worked Example - Burglary Alarm Network

Burglary
Earthquake
↘ ↙
Alarm
↙ ↘
JohnCalls
MaryCalls

Fig 3.1 - Classic Bayes-net: Burglary and Earthquake are independent causes of Alarm; JohnCalls and MaryCalls are independent effects of Alarm (not of each other, given Alarm)

BEP(Alarm=True | B,E)
TT0.95
TF0.94
FT0.29
FF0.001

Sample CPT for node Alarm - P(B)=0.001, P(E)=0.002 are the prior (root) probabilities; this entire network needs only 10 numbers total vs. 31 for the full joint distribution over 5 binary variables.

The Chain Rule for Bayesian Networks

P(X₁, X₂, …, Xₙ) = ∏i=1n P(Xᵢ | Parents(Xᵢ))

This single formula is the entire payoff of the BN structure: the full joint distribution factors into a product of small, local CPTs, each depending only on a node's direct parents - exploiting conditional independence to avoid the exponential blowup of a naive joint table.

Conditional Independence & D-Separation

A Bayesian network encodes that each node is conditionally independent of its non-descendants, given its parents. More generally, d-separation is the graphical criterion for reading off conditional independence statements directly from the graph structure, without needing to inspect the actual probability numbers.

Three Canonical Connection Patterns

PatternStructureIndependence behavior
Chain (Serial)A → B → CA and C are independent given B (B "blocks" the path)
Fork (Common Cause)A ← B → CA and C are independent given B (B explains away the shared dependency)
Collider (V-structure)A → B ← CA and C are marginally independent, but become DEPENDENT once B (or a descendant of B) is observed - the famous "explaining away" effect
💡 Real-world example - Explaining Away

Burglary and Earthquake are independent a priori. But if we observe Alarm=True, learning that an Earthquake did occur makes Burglary less likely (the earthquake already "explains" the alarm) - this is the collider/explaining-away effect, a famous and frequently-tested BN reasoning pattern.

Advantages & Disadvantages

✓ Advantages
  • Compactly represents joint distributions, exploiting conditional independence
  • Graph structure visually encodes causal/dependency knowledge, aiding interpretability
  • Supports flexible queries: diagnostic, causal, and intercausal (explaining away) reasoning
✗ Disadvantages
  • Constructing the graph structure and CPTs requires domain expertise or substantial data
  • Exact inference is NP-hard in general (see next topic)
  • Assumes the DAG correctly captures all relevant dependencies - a wrong structure misleads inference

Applications

  • Medical diagnosis systems (e.g., disease-symptom networks)
  • Spam filtering and fraud detection
  • Genetic/pedigree analysis
  • Fault diagnosis in industrial/engineering systems
🔑 Key Points
  • BN = DAG + CPTs; factors the joint distribution via the chain rule.
  • Each node is conditionally independent of non-descendants given its parents.
  • Colliders (V-structures) cause the "explaining away" effect - independent until a common effect is observed.

Interview & Exam Questions

Q. How many numbers are needed to fully specify a Bayesian network with n binary nodes, each having at most k parents, vs. a full joint distribution table?

The full joint table requires 2^n − 1 independent numbers. The Bayesian network requires only n × 2^k numbers in the worst case (one CPT per node, each of size up to 2^k for k binary parents) - for sparse graphs where k ≪ n, this is an exponential saving in representation size.

Q. Explain "explaining away" with the Burglary-Earthquake-Alarm example.

Burglary and Earthquake are independent causes of Alarm, forming a collider/V-structure at Alarm. Before observing Alarm, they're independent. Once Alarm=True is observed, learning that Earthquake=True reduces the posterior probability of Burglary, since the earthquake alone sufficiently explains the alarm - the two causes effectively "compete" to explain the observed common effect.

3.3

Bayesian Networks: Learning Parameters & Inference

Once a BN's structure is fixed, two remaining problems must be solved: learning the CPT numbers from data, and inference - answering probability queries given evidence.

Part A: Learning Parameters

📘 Definition - Parameter Learning

Given a fixed BN structure and a dataset of observed variable assignments, parameter learning estimates the CPT entries - most commonly via Maximum Likelihood Estimation (MLE): count co-occurrence frequencies in the data and normalize.

P(X=x | Parents(X)=p) ≈ count(X=x, Parents(X)=p) / count(Parents(X)=p)
⚠ The Zero-Count Problem

If a particular parent-value combination never appears in the training data, raw MLE assigns it probability 0 - an overconfident and often wrong conclusion. Laplace (additive) smoothing adds a small pseudo-count to every combination before normalizing, avoiding zero probabilities.

When some variables are hidden/unobserved in the training data, simple counting doesn't work directly - the Expectation-Maximization (EM) algorithm is used instead, alternating between estimating expected values for hidden variables and re-estimating CPTs, until convergence.

Part B: Inference in Bayesian Networks

📘 Definition - Inference

Inference means computing the posterior probability distribution of some query variable(s), given observed evidence - e.g., P(Burglary | JohnCalls=True, MaryCalls=True).

Types of Reasoning Patterns

TypeDirectionExample
Diagnostic (Bottom-up)Effect → CauseP(Burglary | JohnCalls)
Causal (Top-down)Cause → EffectP(JohnCalls | Burglary)
IntercausalCause ↔ Cause (via shared effect)P(Burglary | Alarm, Earthquake) - "explaining away"
MixedCombinationP(Alarm | JohnCalls, ¬Earthquake)

Exact Inference: Enumeration & Variable Elimination

The simplest exact method, Inference by Enumeration, directly sums out all non-query, non-evidence variables from the full joint (reconstructed via the chain rule). It's correct but computationally wasteful since it repeats the same sub-computations.

Variable Elimination improves on this by eliminating (summing out) hidden variables one at a time, caching intermediate "factors" to avoid redundant computation - significantly faster in practice, though still NP-hard in the worst case for general graphs.

Pseudocode - Enumeration-Ask
function ENUMERATION-ASK(X, e, bn):
    Q(X) ← distribution over X, initially empty
    for each value x of X:
        Q(x) ← ENUMERATE-ALL(bn.VARS, e ∪ {X=x})
    return NORMALIZE(Q)

function ENUMERATE-ALL(vars, e):
    if vars is empty: return 1.0
    Y ← FIRST(vars)
    if Y has a value y in e:
        return P(y | parents(Y)) × ENUMERATE-ALL(REST(vars), e)
    else:
        return Σ_y P(y | parents(Y)) × ENUMERATE-ALL(REST(vars), e ∪ {Y=y})

Approximate Inference: Sampling Methods

For large networks, exact inference is often infeasible. Approximate inference via sampling trades exactness for speed:

  • Direct (Prior) Sampling - generate samples by sampling each variable in topological order according to its CPT; estimate probabilities from sample frequencies.
  • Rejection Sampling - generate full samples, discard ("reject") any inconsistent with the observed evidence, estimate from the rest. Wasteful if evidence is rare.
  • Likelihood Weighting - fix evidence variables to their observed values, sample only the remaining variables, and weight each sample by how likely the evidence was given the sampled values - avoids rejection waste.
  • Markov Chain Monte Carlo (MCMC) / Gibbs Sampling - generate a sequence of samples, each obtained by resampling one variable conditioned on all others, converging to the true posterior distribution over many iterations.
✓ Exact Inference
  • Mathematically precise answers
  • Feasible for small-to-moderate, sparse networks
✗ Approximate Inference
  • Scales to large/dense networks where exact inference is intractable
  • Trades guaranteed correctness for statistical convergence - needs enough samples

Applications

  • Medical diagnostic expert systems
  • Spam/fraud detection (Naive Bayes - a simplified BN)
  • Speech recognition (Hidden Markov Models are a special BN structure)
  • Sensor fusion in robotics
🔑 Key Points
  • Parameter learning: MLE via counting, with smoothing to avoid zero probabilities.
  • Exact inference: enumeration (simple, slow) or variable elimination (faster, still NP-hard worst case).
  • Approximate inference: sampling methods (rejection, likelihood weighting, MCMC) scale to large networks.

Interview & Exam Questions

Q. Why is exact inference in Bayesian networks considered NP-hard in general?

Computing exact posterior probabilities requires summing over exponentially many combinations of the hidden variables' values, in the worst case for densely connected (non-tree-structured) networks. While techniques like variable elimination exploit graph structure to reduce redundant computation, the underlying problem remains NP-hard for general DAGs, motivating approximate sampling-based methods for large networks.

Q. What problem does Likelihood Weighting solve compared to Rejection Sampling?

Rejection Sampling generates complete random samples and discards those inconsistent with the evidence - if the evidence is rare, almost all samples are wasted. Likelihood Weighting instead fixes evidence variables directly to their observed values during sampling and weights each generated sample by the likelihood of that evidence, so no samples are discarded, making it far more sample-efficient.

3.4

Decision Theory: Decision-Making Under Uncertainty & Utility Theory

Probability theory tells us how likely outcomes are. But a rational agent (recall Module 1's definition) needs to combine likelihood with preference to actually choose an action. Decision theory = Probability Theory + Utility Theory.

Decision Theory = Probability Theory + Utility Theory
📘 Definition - Utility Function

A utility function U(s) assigns a single real number to each possible state (or outcome), representing the agent's degree of preference for that state. Higher utility = more preferred.

Maximum Expected Utility (MEU) Principle

📘 Definition - MEU

A rational agent should choose the action that maximizes its expected utility - the probability-weighted average utility over all possible outcomes of that action.

EU(a | e) = Σs′ P(RESULT(a) = s′ | a, e) × U(s′)
Choose: a* = argmaxa EU(a | e)

Worked Example

ActionOutcomeProbabilityUtilityContribution
Buy umbrellaRains0.4+83.2
No rain0.6+31.8
EU(Buy umbrella) =5.0
Don't buyRains0.4−5−2.0
No rain0.6+106.0
EU(Don't buy) =4.0

Since EU(Buy umbrella) = 5.0 > EU(Don't buy) = 4.0, the MEU-rational choice is to buy the umbrella - even though "don't buy" has a better best-case outcome, MEU correctly accounts for the probability-weighted full picture.

Axioms of Utility Theory (von Neumann–Morgenstern)

Utility theory is not arbitrary - it can be derived from a small set of rationality axioms about preferences over lotteries (probabilistic combinations of outcomes):

AxiomStatement
OrderabilityFor any two outcomes A, B, exactly one holds: A≻B, B≻A, or A∼B (preferences are totally ordered)
TransitivityIf A≻B and B≻C, then A≻C
ContinuityIf A≻B≻C, there exists a probability p such that B is equally preferred to a lottery [p,A; 1−p,C]
SubstitutabilityIf A∼B, then any lottery containing A is equally preferred to the same lottery with B substituted
MonotonicityIf A≻B, an agent prefers the lottery giving higher probability to A
DecomposabilityCompound lotteries can be reduced to simpler equivalent lotteries using probability rules

The key theorem: if an agent's preferences obey these axioms, then there exists a utility function such that the agent's preferences are exactly equivalent to maximizing expected utility - this is precisely why MEU is considered the formally correct standard of rational decision-making.

Risk Attitudes & Utility Curve Shape

AttitudeUtility curve shapeBehavior
Risk-averseConcavePrefers a certain payoff over a gamble with equal expected value (common for money, especially large amounts)
Risk-neutralLinearIndifferent between a certain payoff and a gamble with the same expected value
Risk-seekingConvexPrefers the gamble over the certain equivalent payoff
💡 Real-world example

Most people are risk-averse about large sums: offered a guaranteed ₹50,000 or a 50% chance of ₹1,00,000 (same expected value), most prefer the guaranteed amount - reflecting a concave utility-of-money curve, where each additional rupee is worth slightly less in utility than the previous one.

Multi-Attribute Utility & Decision Networks (brief mention)

Real decisions often involve multiple competing objectives (cost, safety, time). Multi-attribute utility theory combines several attributes into one scalar utility, often via a weighted sum (under independence assumptions). Decision networks (influence diagrams) extend Bayesian networks with decision nodes and utility nodes, allowing MEU computation directly over a graphical model.

🔑 Key Points
  • Decision Theory = Probability Theory + Utility Theory.
  • MEU principle: choose the action maximizing Σ P(outcome)·U(outcome).
  • Utility functions are justified by the von Neumann–Morgenstern axioms.
  • Utility curve shape (concave/linear/convex) reflects risk-averse/neutral/seeking attitudes.

Interview & Exam Questions

Q. Why does Maximum Expected Utility sometimes recommend an action whose worst-case outcome is worse than an alternative's worst case?

MEU optimizes the probability-weighted average outcome, not the worst case. An action with a slightly worse worst-case outcome can still have higher expected utility overall if its likely/average outcomes are sufficiently better, or if the bad outcome is sufficiently unlikely - MEU is about long-run rational averages, not minimizing worst-case risk (that would be a different criterion, like minimax).

Q. What does a concave utility function imply about an agent's attitude toward risk?

A concave utility function implies risk-aversion: the agent's marginal utility decreases as the underlying quantity (e.g., money) increases, so a guaranteed amount is preferred over a gamble with the same expected value but variable outcomes - losses hurt (in utility terms) more than equivalent gains help.

3.5

Markov Decision Processes: Basics

Decision theory (previous topic) handles a single one-shot decision. Most real agents must make a sequence of decisions over time, in a stochastic environment, where each action affects future states and rewards. Markov Decision Processes formalize exactly this setting - and form the mathematical bedrock of reinforcement learning.

📘 Definition - MDP

A Markov Decision Process is defined by the tuple (S, A, P, R, γ): a set of states S, a set of actions A, a transition model P(s′|s,a) giving the probability of reaching s′ after taking action a in state s, a reward function R(s,a,s′) (or R(s)), and a discount factor γ ∈ [0,1].

The Markov Property

📘 Definition - Markov Property

The probability of transitioning to the next state depends only on the current state and action - not on the full history of how the agent arrived there: P(st+1 | st, at, st-1, …, s₀) = P(st+1 | st, at).

Policy - The Output of MDP Solving

📘 Definition - Policy π

A policy π(s) is a complete mapping from every state to an action - it tells the agent what to do no matter which state it ends up in, unlike a simple plan (a fixed sequence). Solving an MDP means finding the optimal policy π* that maximizes expected cumulative discounted reward.

Discounting and the Value of a Policy

Vπ(s) = E[ Σt=0 γt R(st) | π, s₀=s ]

The discount factor γ (0 ≤ γ < 1) makes future rewards worth less than immediate ones - this (a) reflects realistic preference for sooner rewards, (b) ensures the infinite sum converges to a finite value, and (c) handles the possibility of indefinitely long or infinite-horizon tasks.

Classic Grid-World Example

−0.04
−0.04
−0.04
+1
−0.04
−0.04
−1
−0.04
−0.04
−0.04
−0.04

Fig 3.2 - Classic 4×3 grid MDP: small negative reward (−0.04) per step encourages reaching the goal (+1) quickly, avoiding the pit (−1); actions are stochastic (e.g., 80% intended direction, 10%/10% perpendicular slip)

MDP vs. Standard Search Problem - Key Distinctions

AspectClassical Search (Module 1–2)MDP
TransitionsDeterministic (mostly)Stochastic - P(s′|s,a)
Solution formA fixed action sequence (plan)A policy π(s) - a full mapping from states to actions
ObjectiveReach a goal state, minimize path costMaximize expected cumulative discounted reward
HorizonTypically finite, ends at goalOften infinite or indefinite horizon

Applications

  • Robot navigation under actuator/sensor uncertainty
  • Reinforcement learning (MDPs are RL's foundational mathematical model)
  • Inventory management and supply chain optimization
  • Healthcare treatment planning under uncertain patient response
🔑 Key Points
  • MDP = (S, A, P, R, γ); obeys the Markov property (memoryless transitions).
  • Solution is a policy, not a single path - robust to any state the agent might land in.
  • Discount factor γ ensures convergence and models time-preference for rewards.
Q. Why is the solution to an MDP a policy rather than a fixed action sequence?

Because MDP transitions are stochastic, the same action in the same state can lead to different next states on different occasions. A fixed sequence would be useless if the agent ends up somewhere unexpected. A policy specifies an action for every possible state, so the agent always knows what to do regardless of which stochastic outcome actually occurred.

Q. What role does the discount factor γ play, and what happens at γ=0 vs γ→1?

γ controls how much future rewards are weighted relative to immediate ones. At γ=0, the agent is fully myopic, caring only about the immediate reward. As γ→1, the agent becomes far-sighted, valuing long-term cumulative reward almost as much as immediate reward - γ<1 also guarantees the infinite discounted sum converges to a finite value.

3.6

Solving MDPs: Value Iteration

Value Iteration is the most direct algorithm for solving an MDP - it computes the optimal value of every state by repeatedly applying the Bellman equation as an update rule until the values converge.

📘 Definition - Bellman Equation (Optimality)

The optimal value V*(s) of a state satisfies: V*(s) = maxa Σs′ P(s′|s,a) [R(s,a,s′) + γV*(s′)] - the best achievable value is the best action's immediate reward plus the discounted value of wherever it's likely to lead.

Vk+1(s) ← maxa∈A Σs′ P(s′|s,a) [R(s,a,s′) + γVk(s′)]

Step-by-Step Algorithm

  1. Initialize V₀(s) = 0 for all states s (arbitrary starting point).
  2. For each state s, compute Vk+1(s) using the Bellman update above, considering every action.
  3. Repeat step 2 for all states simultaneously (one "sweep" = one iteration).
  4. Stop when the maximum change in V between iterations falls below a small threshold ε (convergence).
  5. Extract the optimal policy: π*(s) = argmaxa Σs′ P(s′|s,a)[R(s,a,s′) + γV*(s′)].
Python
def value_iteration(states, actions, P, R, gamma=0.9, theta=1e-4):
    V = {s: 0.0 for s in states}
    while True:
        delta = 0
        new_V = {}
        for s in states:
            if is_terminal(s):
                new_V[s] = R(s); continue
            new_V[s] = max(
                sum(P(s, a, s2) * (R(s, a, s2) + gamma * V[s2]) for s2 in states)
                for a in actions(s)
            )
            delta = max(delta, abs(new_V[s] - V[s]))
        V = new_V
        if delta < theta:
            break
    # extract greedy policy
    policy = {}
    for s in states:
        policy[s] = max(actions(s), key=lambda a:
            sum(P(s, a, s2) * (R(s, a, s2) + gamma * V[s2]) for s2 in states))
    return V, policy

Convergence Properties

PropertyResult
ConvergenceGuaranteed to converge to the unique optimal V* as k → ∞, for γ < 1 (Bellman update is a contraction mapping)
Convergence rateGeometric, governed by γ - smaller γ converges faster
Per-iteration costO(|S|²|A|) - must consider every state, every action, every possible next state
✓ Advantages
  • Conceptually simple, guaranteed convergence
  • Doesn't require an explicit initial policy - starts from arbitrary value estimates
✗ Disadvantages
  • Can require many iterations to converge precisely, especially with γ close to 1
  • Each iteration is computationally expensive for large state/action spaces
  • Recomputes the max over all actions every sweep, even for states whose optimal action is already obvious
🔑 Key Points
  • Value Iteration repeatedly applies the Bellman optimality equation as an update rule.
  • Converges to the unique V* regardless of initialization (for γ < 1).
  • Optimal policy is extracted at the end via argmax over the converged values.

Interview Questions

Q. Why does Value Iteration converge regardless of how V is initialized?

The Bellman update is a contraction mapping under the discount factor γ < 1 - each application strictly reduces the maximum distance between any current value estimate and the true V*, by a factor of γ. Repeated application therefore drives any starting estimate toward the unique fixed point V*, regardless of initial values.

3.7

Solving MDPs: Policy Iteration

Policy Iteration is an alternative MDP-solving algorithm that often converges in far fewer iterations than Value Iteration, by working directly with policies rather than values.

📘 Definition - Policy Iteration

Policy Iteration alternates between two steps until convergence: Policy Evaluation (compute the value function for the current fixed policy) and Policy Improvement (greedily update the policy using those values). It terminates when the policy stops changing - guaranteed to be optimal at that point.

Step-by-Step Algorithm

  1. Initialize an arbitrary policy π₀(s) for all states.
  2. Policy Evaluation: solve for Vπ(s) = Σs′ P(s′|s,π(s)) [R(s,π(s),s′) + γVπ(s′)] - either by solving the linear system exactly, or by iterating it to convergence (a fixed policy, unlike Value Iteration's max).
  3. Policy Improvement: for each state, compute π′(s) = argmaxa Σs′ P(s′|s,a)[R(s,a,s′) + γVπ(s′)].
  4. If π′ = π for every state (no change), stop - π is optimal.
  5. Otherwise set π ← π′ and repeat from step 2.
Python
def policy_iteration(states, actions, P, R, gamma=0.9):
    policy = {s: actions(s)[0] for s in states}     # arbitrary initial policy
    while True:
        # --- Policy Evaluation (iterative version) ---
        V = {s: 0.0 for s in states}
        while True:
            delta = 0
            for s in states:
                v = V[s]
                a = policy[s]
                V[s] = sum(P(s, a, s2) * (R(s, a, s2) + gamma * V[s2]) for s2 in states)
                delta = max(delta, abs(v - V[s]))
            if delta < 1e-6:
                break

        # --- Policy Improvement ---
        stable = True
        for s in states:
            old_action = policy[s]
            policy[s] = max(actions(s), key=lambda a:
                sum(P(s, a, s2) * (R(s, a, s2) + gamma * V[s2]) for s2 in states))
            if old_action != policy[s]:
                stable = False
        if stable:
            return policy, V

Value Iteration vs. Policy Iteration - The Most-Asked Comparison

AspectValue IterationPolicy Iteration
Core operationmax over actions, every sweepFixed-policy evaluation, then greedy improvement
Per-iteration costCheaper per sweep - O(|S|²|A|)Expensive per iteration - requires solving/iterating a linear system for evaluation, O(|S|³) for exact solve
Number of iterations to convergeOften many (gradual value convergence)Often very few - policy typically stabilizes quickly
GuaranteeConverges to V* asymptoticallyConverges to π* in a finite number of iterations (finite policy space)
Best suited whenLarge state spaces, simple updates preferredSmaller/medium state spaces where exact evaluation is feasible
🔑 Key Points
  • Policy Iteration alternates Policy EvaluationPolicy Improvement.
  • Converges in a finite number of iterations (unlike Value Iteration's asymptotic convergence) since there are finitely many distinct policies.
  • Each iteration is more expensive (solving a linear system) but typically needs far fewer iterations overall.

Interview & Exam Questions

Q. Why does Policy Iteration converge in a finite number of steps, while Value Iteration only converges asymptotically?

There are only finitely many possible deterministic policies for a finite MDP (|A|^|S| of them). Each policy improvement step strictly improves the policy (or leaves it unchanged at convergence) - since the policy space is finite and strictly improving, the algorithm cannot cycle and must reach the optimal policy in finitely many steps. Value Iteration, by contrast, refines a continuous-valued function V(s) that approaches V* in the limit but technically never reaches it exactly in finite iterations (only within ε-tolerance).

Q. When would you prefer Value Iteration over Policy Iteration?

When the state space is very large, making the exact policy-evaluation linear-system solve (O(|S|³)) too expensive per iteration. Value Iteration's cheaper per-sweep update (no system solve needed) is more scalable in that regime, even though it may take more total iterations to converge to an acceptable tolerance.

📋 Module 3 - Complete Summary

Module 3 moved AI from certainty to uncertainty: we identified why uncertainty is unavoidable (sensor noise, partial observability, the qualification problem) and why probability is the principled response. Bayesian networks compactly represent joint distributions as a DAG of conditional dependencies, supporting diagnostic, causal, and "explaining away" intercausal reasoning, learned via MLE and queried via exact (enumeration, variable elimination) or approximate (sampling) inference. Decision theory combined probability with utility theory (grounded in the von Neumann–Morgenstern axioms) via the Maximum Expected Utility principle. Finally, Markov Decision Processes extended this to sequential decision-making - solved via Value Iteration (repeated Bellman updates, asymptotic convergence) or Policy Iteration (evaluate-then-improve, finite convergence) - the mathematical foundation of modern reinforcement learning.