You are on page 1of 91

Foundations of Artificial Intelligence

Local Search

Shang-Tse Chen
Department of Computer Science
& Information Engineering
National Taiwan University

(slides adapted from Dan Klein, Pieter Abbeel)


Local Search
o Tree search keeps unexplored alternatives on the fringe (ensures completeness)

o Local search: improve a single option until you can’t make it better (no fringe!)

o New successor function: local changes

o Generally much faster and more memory efficient (but incomplete and
suboptimal)
Hill Climbing
o Simple, general idea:
o Start wherever
o Repeat: move to the best neighboring state
o If no neighbors better than current, quit

o What’s bad about this approach?

o What’s good about it?


Hill-climbing algorithm
function HILL-CLIMBING(problem) returns a state
current ← make-node(problem.initial-state)
loop do
neighbor ← a highest-valued successor of current
if neighbor.value ≤ current.value then
return current.state
current ← neighbor

“Like climbing Everest in thick fog with amnesia”


Hill Climbing Diagram
Hill Climbing Quiz

Starting from X, where do you end up ?

Starting from Y, where do you end up ?

Starting from Z, where do you end up ?


Simulated annealing
o Resembles the annealing process used to cool metals slowly
to reach an ordered (low-energy) state
o Basic idea:
o Allow “bad” moves occasionally, depending on “temperature”
o High temperature => more bad moves allowed, shake the system
out of its local minimum
o Gradually reduce temperature according to some schedule
o Sounds pretty flaky, doesn’t it?
Simulated annealing algorithm
function SIMULATED-ANNEALING(problem,schedule) returns a state
current ← problem.initial-state
for t = 1 to ∞ do
T ←schedule(t)
if T = 0 then return current
next ← a randomly selected successor of current
∆E ← next.value – current.value
if ∆E > 0 then current ← next
else current ← next only with probability e∆E/T
Simulated Annealing
o Theoretical guarantee:
o Stationary distribution (Boltzmann): P(x) a eE(x)/T
o If T decreased slowly enough, will converge to optimal state!
o Proof sketch
o Consider two adjacent states x, y with E(y) > E(x) [high is
good]
o Assume x®y and y®x and outdegrees D(x) = D(y) = D
o Let P(x), P(y) be the equilibrium occupancy probabilities at T
o Let P(x®y) be the probability that state x transitions to state y
Simulated Annealing

o Is this convergence an interesting guarantee?

o Sounds like magic, but reality is reality:


o The more downhill steps you need to escape a local
optimum, the less likely you are to ever make them all in
a row
o “Slowly enough” may mean exponentially slowly
o Random restart hillclimbing also converges to optimal
state…

o Simulated annealing and its relatives are a key


workhorse in VLSI layout and other optimal
configuration problems
Local beam search
o Basic idea:
o K copies of a local search algorithm, initialized randomly
o For each iteration Or, K chosen randomly with
a bias towards good ones
o Generate ALL successors from K current states
o Choose best K of these to be the new current states
o Why is this different from K local searches in parallel?
o The searches communicate! “Come over here, the grass is greener!”
o What other well-known algorithm does this remind you of?
o Evolution!
Genetic Algorithms

o Genetic algorithms use a natural selection metaphor


o Keep best N hypotheses at each step (selection) based on a fitness function
o Also have pairwise crossover operators, with optional mutation to give variety

o Possibly the most misunderstood, misapplied (and even maligned) technique


around
Example: N-Queens

o Why does crossover make sense here?


o When wouldn’t it make sense?
o What would mutation be?
o What would a good fitness function be?
Foundations of Artificial Intelligence
Adversarial Search

Shang-Tse Chen
Department of Computer Science
& Information Engineering
National Taiwan University

(slides adapted from Dan Klein, Pieter Abbeel)


Behavior from Computation

[Demo: mystery pacman (L6D1)]


Video of Demo Mystery Pacman
Types of Games
o Many different kinds of games!

o Axes:
o Deterministic or stochastic?
o One, two, or more players?
o Zero sum?
o Perfect information (can you see the state)?
Types of Games

o General Games o Zero-Sum Games


o Agents have independent utilities o Agents have opposite utilities (values on
(values on outcomes) outcomes)
o Cooperation, indifference, competition, o Lets us think of a single value that one
and more are all possible maximizes and the other minimizes
o We don’t make AI to act in isolation, it should o Adversarial, pure competition
a) work around people and b) help people
o That means that every AI agent needs to solve
a game
Zero-Sum Game Games J
o Checkers: 1950: First computer player. 1994:
First computer champion: Chinook ended 40-
year-reign of human champion Marion Tinsley
using complete 8-piece endgame. 2007:
Checkers solved!

o Chess: 1997: Deep Blue defeats human


champion Gary Kasparov in a six-game match.
Deep Blue examined 200M positions per
second, used very sophisticated evaluation
and undisclosed methods for extending some
lines of search up to 40 ply. Current programs
are even better, if less historic.

o Go: Human champions are now starting to be


challenged by machines, though the best
humans still beat the best machines. In go, b >
300! Classic programs use pattern knowledge
bases, but big recent advances use Monte
Carlo (randomized) expansion methods.
Zero-Sum Game Games J
o Checkers: 1950: First computer player. 1994:
First computer champion: Chinook ended 40-
year-reign of human champion Marion Tinsley
using complete 8-piece endgame. 2007:
Checkers solved!

o Chess: 1997: Deep Blue defeats human


champion Gary Kasparov in a six-game match.
Deep Blue examined 200M positions per
second, used very sophisticated evaluation
and undisclosed methods for extending some
lines of search up to 40 ply. Current programs
are even better, if less historic.

o Go :2016: Alpha GO defeats human


champion. Uses Monte Carlo Tree Search,
learned evaluation function.

o Pacman
Deterministic Games with Terminal Utilities
o Many possible formalizations, one is:
o States: S (start at s0)
o Players: P={1...N} (usually take turns)
o Actions: A (may depend on player / state)
o Transition Function: SxA ® S
o Terminal Test: S ® {t,f}
o Terminal Utilities: SxP ® R

o Solution for a player is a policy: S ® A


Adversarial Games
Adversarial Search
Cost -> Utility!
o no longer minimizing cost!
o agent now wants to maximize its score/utility!
Single-Agent Trees

2 0 … 2 6 … 4 6
Value of a State
Value of a state: Non-Terminal States:
The best achievable
outcome (utility)
from that state

2 0 … 2 6 … 4 6
Terminal States:
Adversarial Game Trees

-20 -8 … -18 -5 … -10 +4 -20 +8


Minimax Values
States Under Agent’s Control: States Under Opponent’s Control:

-8 -5 -10 +8

Terminal States:
Tic-Tac-Toe Game Tree
Adversarial Search (Minimax)
o Deterministic, zero-sum games: Minimax values:
computed recursively
o Tic-tac-toe, chess, checkers
o One player maximizes result 5 max
o The other minimizes result

2 5 min
o Minimax search:
o A state-space search tree
o Players alternate turns
8 2 5 6
o Compute each node’s minimax
value: the best achievable utility
Terminal values:
against a rational (optimal) part of the game
adversary
Minimax Implementation

def max-value(state): def min-value(state):


initialize v = -∞ initialize v = +∞
for each successor of state: for each successor of state:
v = max(v, min-value(successor)) v = min(v, max-value(successor))
return v return v
Minimax Implementation (Dispatch)
def value(state):
if the state is a terminal state: return the state’s utility
if the next agent is MAX: return max-value(state)
if the next agent is MIN: return min-value(state)

def max-value(state): def min-value(state):


initialize v = -∞ initialize v = +∞
for each successor of state: for each successor of state:
v = max(v, value(successor)) v = min(v, value(successor))
return v return v
Minimax Example

3 2 2

3 12 8 2 4 6 14 5 2
Minimax Properties

max

min

10 10 9 100

Optimal against a perfect player. Otherwise?

[Demo: min vs exp (L6D2, L6D3)]


Video of Demo Min vs. Exp (Min)
Video of Demo Min vs. Exp (Exp)
Minimax Efficiency

o How efficient is minimax?


o Just like (exhaustive) DFS
o Time: O(bm)
o Space: O(bm)

o Example: For chess, b » 35, m » 100


o Exact solution is completely infeasible
o But, do we need to explore the whole tree?
Resource Limits
Game Tree Pruning
Minimax Example

3 <=2 2

3 12 8 2 14 5 2
Alpha-Beta Pruning
o General configuration (MIN version)
o We’re computing the MIN-VALUE at some node n MAX
o We’re looping over n’s children
o n’s estimate of the childrens’ min is dropping MIN a
o Who cares about n’s value? MAX
o Let a be the best value that MAX can get at any
choice point along the current path from the root
o If n becomes worse than a, MAX will avoid it, so we MAX
can stop considering n’s other children (it’s already
bad enough that it won’t be played) MIN n

o MAX version is symmetric


Alpha-Beta Implementation

α: MAX’s best option on path to root


β: MIN’s best option on path to root

def max-value(state, α, β): def min-value(state , α, β):


initialize v = -∞ initialize v = +∞
for each successor of state: for each successor of state:
v = max(v, value(successor, α, β)) v = min(v, value(successor, α, β))
if v ≥ β return v if v ≤ α return v
α = max(α, v) β = min(β, v)
return v return v
Alpha-Beta Pruning Properties
o This pruning has no effect on minimax value computed for the root!

o Values of intermediate nodes might be wrong


o Important: children of the root may have the wrong value max
o So the most naïve version won’t let you do action selection

min
o Good child ordering improves effectiveness of pruning

o With “perfect ordering”:


o Time complexity drops to O(bm/2) 10 10 0
o Doubles solvable depth!
o Full search of, e.g. chess, is still hopeless…

o This is a simple example of metareasoning (computing about what to compute)


Alpha-Beta Quiz
Alpha-Beta Quiz 2

10
<=2

>=100 2
10
Resource Limits
Resource Limits
o Problem: In realistic games, cannot search to leaves! 4 max

o Solution: Depth-limited search -2 4 min


o Instead, search only to a limited depth in the tree
-1 -2 4 9
o Replace terminal utilities with an evaluation function for non-
terminal positions

o Example:
o Suppose we have 100 seconds, can explore 10K nodes / sec
o So can check 1M nodes per move
o a-b reaches about depth 8 – decent chess program

o Guarantee of optimal play is gone


o More plies makes a BIG difference
? ? ? ?
o Use iterative deepening for an anytime algorithm
Depth Matters
o Evaluation functions are
always imperfect
o The deeper in the tree the
evaluation function is buried,
the less the quality of the
evaluation function matters
o An important example of the
tradeoff between complexity of
features and complexity of
computation

[Demo: depth limited (L6D4, L6D5)]


Video of Demo Limited Depth (2)
Video of Demo Limited Depth (10)
Evaluation Functions
Evaluation Functions
o Evaluation functions score non-terminals in depth-limited search

o Typically weighted linear sum of features:


o EVAL(s) = w1 f1(s) + w2 f2(s) + …. + wn fn(s)
o E.g., w1 = 9, f1(s) = (num white queens – num black queens), etc.
o Or a more complex nonlinear function (e.g., NN) trained by self-play RL
Evaluation for Pacman

[Demo: thrashing d=2, thrashing d=2 (fixed evaluation function), smart ghosts coordinate (L6D6,7,8,10)]
Video of Demo Thrashing (d=2)
Why Pacman Starves

o A danger of replanning agents!


o He knows his score will go up by eating the dot now (west, east)
o He knows his score will go up just as much by eating the dot later (east, west)
o There are no point-scoring opportunities after eating the dot (within the horizon,
two here)
o Therefore, waiting seems just as good as eating: he may go east, then back west in
the next round of replanning!
Video of Demo Thrashing -- Fixed (d=2)
Video of Demo Smart Ghosts (Coordination)
Video of Demo Smart Ghosts (Coordination) –
Zoomed In
Uncertain Outcomes
Worst-Case vs. Average Case

max

min

10 10 9 100

Idea: Uncertain outcomes controlled by chance, not an adversary!


Expectimax Search
o Why wouldn’t we know what the result of an action will be?
o Explicit randomness: rolling dice max
o Unpredictable opponents: the ghosts respond randomly
o Unpredictable humans: humans are not perfect
o Actions can fail: when moving a robot, wheels might slip
chance
o Values should now reflect average-case (expectimax)
outcomes, not worst-case (minimax) outcomes

o Expectimax search: compute the average score under


optimal play 10 10
4 5
9 100
7
o Max nodes as in minimax search
o Chance nodes are like min nodes but the outcome is uncertain
o Calculate their expected utilities
o I.e. take weighted average (expectation) of children

o Later, we’ll learn how to formalize the underlying


uncertain-result problems as Markov Decision Processes
[Demo: min vs exp (L7D1,2)]
Video of Demo Minimax vs Expectimax (Min)
Video of Demo Minimax vs Expectimax (Exp)
Expectimax Pseudocode

def value(state):
if the state is a terminal state: return the state’s utility
if the next agent is MAX: return max-value(state)
if the next agent is EXP: return exp-value(state)

def max-value(state): def exp-value(state):


initialize v = -∞ initialize v = 0
for each successor of state: for each successor of state:
v = max(v, value(successor)) p = probability(successor)
return v v += p * value(successor)
return v
Expectimax Pseudocode

def exp-value(state):
initialize v = 0
for each successor of state: 1/2 1/6
p = probability(successor) 1/3
v += p * value(successor)
return v 5
8 24
7 -12

v = (1/2) (8) + (1/3) (24) + (1/6) (-12) = 10


Expectimax Example

3 12 9 2 4 6 15 6 0
Expectimax Pruning?

3 12 9 2
Depth-Limited Expectimax

Estimate of true
400 300 …expectimax value
(which would
require a lot of
… work to compute)

492 362 …
Probabilities
Reminder: Probabilities
o A random variable represents an event whose outcome is unknown
o A probability distribution is an assignment of weights to outcomes
0.25
o Example: Traffic on freeway
o Random variable: T = whether there’s traffic
o Outcomes: T in {none, light, heavy}
o Distribution: P(T=none) = 0.25, P(T=light) = 0.50, P(T=heavy) = 0.25

o Some laws of probability (more later):


o Probabilities are always non-negative
0.50
o Probabilities over all possible outcomes sum to one

o As we get more evidence, probabilities may change:


o P(T=heavy) = 0.25, P(T=heavy | Hour=8am) = 0.60
o We’ll talk about methods for reasoning and updating probabilities later
0.25
Reminder: Expectations
o The expected value of a function of a random variable is
the average, weighted by the probability distribution
over outcomes

o Example: How long to get to the airport?

Time: 20 min 30 min 60 min


x + x + x 35 min
Probability: 0.25 0.50 0.25
What Probabilities to Use?
o In expectimax search, we have a probabilistic
model of how the opponent (or environment)
will behave in any state
o Model could be a simple uniform distribution (roll a
die)
o Model could be sophisticated and require a great deal
of computation
o We have a chance node for any outcome out of our
control: opponent or environment
o The model might say that adversarial actions are likely!

o For now, assume each chance node magically


comes along with probabilities that specify the
distribution over its outcomes
Having a probabilistic belief about
another agent’s action does not mean
that the agent is flipping any coins!
Quiz: Informed Probabilities
o Let’s say you know that your opponent is actually running a depth 2 minimax,
using the result 80% of the time, and moving randomly otherwise
o Question: What tree search should you use?
§ Answer: Expectimax!
§ To figure out EACH chance node’s probabilities,
you have to run a simulation of your opponent
§ This kind of thing gets very slow very quickly
0.1 0.9
§ Even worse if you have to simulate your
opponent simulating you…
§ … except for minimax and maximax, which
have the nice property that it all collapses into
one game tree
This is basically how you would model a human, except for their utility: their utility might be the
same as yours (i.e. you try to help them, but they are depth 2 and noisy), or they might have a
slightly different utility (like another person navigating in the office)
Modeling Assumptions
The Dangers of Optimism and Pessimism
Dangerous Optimism Dangerous Pessimism
Assuming chance when the world is adversarial Assuming the worst case when it’s not likely
Assumptions vs. Reality

Adversarial Ghost Random Ghost

Minimax Won 5/5 Won 5/5


Pacman Avg. Score: 483 Avg. Score: 493

Expectimax Won 1/5 Won 5/5


Pacman Avg. Score: -303 Avg. Score: 503

Results from playing 5 games

Pacman used depth 4 search with an eval function that avoids trouble
Ghost used depth 2 search with an eval function that seeks Pacman
[Demos: world assumptions (L7D3,4,5,6)]
Assumptions vs. Reality

Adversarial Ghost Random Ghost

Minimax Won 5/5 Won 5/5


Pacman Avg. Score: 483 Avg. Score: 493

Expectimax Won 1/5 Won 5/5


Pacman Avg. Score: -303 Avg. Score: 503

Results from playing 5 games

Pacman used depth 4 search with an eval function that avoids trouble
Ghost used depth 2 search with an eval function that seeks Pacman
[Demos: world assumptions (L7D3,4,5,6)]
Video of Demo World Assumptions
Random Ghost – Expectimax Pacman
Video of Demo World Assumptions
Adversarial Ghost – Minimax Pacman
Video of Demo World Assumptions
Adversarial Ghost – Expectimax Pacman
Video of Demo World Assumptions
Random Ghost – Minimax Pacman
Why not minimax?
o Worst case reasoning is too conservative
o Need average case reasoning
Mixed Layer Types
o E.g. Backgammon
o Expectiminimax
o Environment is an
extra “random
agent” player that
moves after each
min/max agent
o Each node
computes the
appropriate
combination of its
children
Example: Backgammon
o Dice rolls increase b: 21 possible rolls with 2 dice
o Backgammon » 20 legal moves
o Depth 2 = 20 x (21 x 20)3 = 1.2 x 109

o As depth increases, probability of reaching a


given search node shrinks
o So usefulness of search is diminished
o So limiting depth is less damaging
o But pruning is trickier…

o Historic AI: TDGammon uses depth-2 search +


very good evaluation function + reinforcement
learning:
world-champion level play

o 1st AI world champion in any game! Image: Wikipedia


Other Game Types
Multi-Agent Utilities
o What if the game is not zero-sum, or has multiple players?
o Generalization of minimax:
o Terminals have utility tuples
o Node values are also utility tuples
o Each player maximizes its own component
o Can give rise to cooperation and
competition dynamically…
1,6,6

1,6,6 7,1,2 6,1,2 7,2,1 5,1,7 1,5,2 7,7,1 5,2,5


Utilities
Utilities

o Utilities are functions from


outcomes (states of the world) to
real numbers that describe an
agent’s preferences

o Where do utilities come from?


o In a game, may be simple (+1/-1)
o Utilities summarize the agent’s goals
o Theorem: any “rational” preferences
can be summarized as a utility
function

o We hard-wire utilities and let


behaviors emerge
o Why don’t we let agents pick utilities?
o Why don’t we prescribe behaviors?
Utilities: Uncertain Outcomes
Getting ice cream

Get Single Get Double

Oops Whew!
Maximum Expected Utility

o Why should we average utilities? Why not minimax?

o Principle of maximum expected utility:


o A rational agent should chose the action that maximizes its
expected utility, given its knowledge

o Questions:
o Where do utilities come from?
o How do we know such utilities even exist?
o How do we know that averaging even makes sense?
o What if our behavior (preferences) can’t be described by
utilities?
What Utilities to Use?

0 40 20 30 x2 0 1600 400 900

o For worst-case minimax reasoning, terminal function scale doesn’t matter


o We just want better states to have higher evaluations (get the ordering
right)
o We call this insensitivity to monotonic transformations

o For average-case expectimax reasoning, we need magnitudes to be meaningful

You might also like