Repository navigation
Module 3b ‐ Developing Heuristics
The efficiency, runtime complexity, and memory requirements of heuristic search algorithms such as
In
where:
-
$g(n)$ represents the exact path cost incurred from the initial start state$n_0$ to node$n$ . -
$h(n)$ denotes the heuristic cost-to-go estimate from node$n$ to the nearest goal state$n_g$ .
The heuristic function
To guarantee that
A heuristic
where
Under an admissible heuristic,
When choosing between multiple admissible heuristics for a given problem, the concept of domination provides a formal basis for comparison.
Given two admissible heuristics
- For all states
$n$ in the search space,$h_2(n) \ge h_1(n)$ . - For at least one state
$n$ ,$h_2(n) > h_1(n)$ (ensuring that$h_1$ and$h_2$ are not identically equal).
Mathematically, domination establishes a partial ordering over the space of admissible heuristic functions. If both
The primary theoretical and practical advantage of a dominating heuristic lies in node expansion savings and memory reduction:
An
The intuition behind this theorem follows directly from the definition of the evaluation function
- A larger, more accurate heuristic value
$h_2(n)$ increases the total objective value$f(n)$ for non-optimal or off-path nodes. - Higher
$f(n)$ values delay or completely eliminate the expansion of nodes that lie further from the optimal goal path. - Consequently, a dominating heuristic narrows the search frontier earlier, consumes significantly less memory for open node storage, and shrinks the total explored search tree.
Consider the 8-tile puzzle domain, consisting of a
We evaluate two classic handcrafted heuristics:
-
Misplaced Tiles (
$h_1$ ): The count of non-blank tiles currently not residing in their target goal positions. -
Manhattan Distance (
$h_2$ ): The sum of horizontal and vertical grid distances (taxicab distance) for each tile from its current position to its goal position.
Let
The two heuristics are expressed mathematically as:
For any single tile
Thus, for every individual state
Because
To quantify the efficiency gain provided by a heuristic function, AI researchers use the Effective Branching Factor (
If an
The mathematical relation governing
If
For an unguided brute-force search on a domain like the 8-tile puzzle, the physical branching factor is
- A weak heuristic (such as Misplaced Tiles) may reduce the effective branching factor to
$b^* \approx 6$ . - A strong, dominating heuristic (such as Manhattan Distance or pattern databases) can reduce
$b^*$ down to$2$ or even$1.5$ .
Because total expanded nodes scale exponentially with depth (
Although a dominating heuristic minimizes the number of node expansions, computing a more informed heuristic function at each node often requires additional CPU cycles and memory.
This yields a fundamental design trade-off in intelligent search:
-
Weak Heuristics: Have small
$T_{\text{eval}}$ , but result in large$N$ , leading to high overall runtime and potential memory exhaustion. -
Complex Dominating Heuristics: Drastically reduce
$N$ , but require higher$T_{\text{eval}}$ per node.
A heuristic is effective in practice only if the time saved by avoiding node expansions outweighs the time spent calculating the heuristic value.
In many practical AI applications (such as real-time robotics or large-scale routing), finding a strictly optimal path is less critical than finding a near-optimal path quickly.
Weighted
By amplifying the influence of
Because
If
This property is known as
Weighted
-
High-Quality Heuristic: Provides accurate cost estimates close to
$h^*(n)$ . When paired with Weighted$A^*$ , even a small weight$w$ (e.g.,$w = 1.2$ ) yields massive runtime speedups while keeping the solution cost$C$ extremely close to$C^*$ . -
Low-Quality Heuristic: Poor guidance requires a large weight
$w$ to see meaningful expansion reductions, which drastically increases the bound$w \cdot C^*$ and risks severe solution degradation.
Thus, strong heuristic quality remains essential even when strict optimality is relaxed.
The development of heuristics in artificial intelligence has undergone a fundamental paradigm shift over the past several decades. In early AI search frameworks, heuristics were entirely handcrafted, relying on human domain experts to formulate intuitive rules based on qualitative observation (e.g., counting misplaced pieces in tile puzzles). While simple to compute, handcrafted heuristics often suffer from severe underestimation, offering weak search guidance.
As state-space search matured, researchers shifted toward structural derivations, systematically relaxed problem definitions by stripping away constraints to extract admissible distance metrics automatically. This was followed by memory-enhanced methods such as Pattern Databases (PDBs), which trade offline precomputation and storage for near-optimal online search guidance.
In contemporary AI, particularly within complex domain spaces such as high-dimensional robotics, automated planning, and game-playing agents, heuristic design has evolved into a data-driven process. Rather than relying on human design, modern frameworks leverage deep neural networks and reinforcement learning to learn the cost-to-go function
To appreciate the necessity of principled heuristic design, consider the classical
Despite the structural simplicity of its rules, the state space size of the
Because brute-force uninformed search strategies (e.g., Breadth-First Search or Uniform Cost Search) expand nodes indiscriminately across
A formal method for constructing admissible heuristics is problem relaxation. Given an original search problem
Removing constraints expands the set of permissible actions at any state. Consequently, any valid path from state
Let
Therefore, setting the heuristic function equal to the exact optimal cost of the relaxed problem,
In the formal specification of the
-
Adjacency Constraint: Square
$A$ must be horizontally or vertically adjacent to square$B$ . -
Blank Constraint: Square
$B$ must currently be unoccupied (the blank square). - Unit Step Constraint: A tile can only move exactly one grid unit per operation.
By systematically removing subsets of these three constraints, classical admissible heuristics are naturally derived:
-
Derivation of Misplaced Tiles Heuristic (
$h_{\text{misplaced}}$ ): Relax the Adjacency Constraint and the Unit Step Constraint, allowing a tile to move from square$A$ to square$B$ in a single move regardless of distance, provided square$B$ is blank. Under this relaxation, any tile not currently in its goal position can be moved directly to its destination in exactly$1$ move. The optimal cost to solve this relaxed problem is simply the total count of misplaced tiles:$$h_{\text{misplaced}}(n) = \sum\limits_{i=1}^{8} \mathbb{I}(\overrightarrow{p}_i \neq \overrightarrow{p}_{i, \text{goal}})$$ where
$\mathbb{I}(\cdot)$ is the indicator function,$\overrightarrow{p}_i = (x_i, y_i)^T$ represents the current vector position of tile$i$ , and$\overrightarrow{p}_{i, \text{goal}} = (x_{i, \text{goal}}, y_{i, \text{goal}})^T$ represents its goal vector position. -
Derivation of Manhattan Distance Heuristic (
$h_{\text{Manhattan}}$ ): Relax the Blank Constraint, allowing a tile to slide into square$B$ even if square$B$ is already occupied by another tile. Under this relaxation, tiles can overlap and pass through each other independently along grid lines. The minimum number of horizontal and vertical steps required for tile$i$ to travel from$\overrightarrow{p}_i$ to$\overrightarrow{p}_{i, \text{goal}}$ is its Manhattan distance:$$d_{\text{Manhattan}}(\overrightarrow{p}_i, \overrightarrow{p}_{i, \text{goal}}) = |x_i - x_{i, \text{goal}}| + |y_i - y_{i, \text{goal}}|$$ Summing this relaxed distance over all tiles yields the total Manhattan Distance heuristic:
$$h_{\text{Manhattan}}(n) = \sum\limits_{i=1}^{8} \left( |x_i - x_{i, \text{goal}}| + |y_i - y_{i, \text{goal}}| \right)$$
Because
While relaxed problem heuristics like Manhattan Distance treat each tile independently, they ignore interactions between tiles (such as one tile blocking another). Pattern Databases (PDBs) address this limitation by precomputing exact solution costs for subsets of tiles offline.
A Pattern Database is a lookup table that stores the exact minimum number of moves required to solve a specific sub-problem (pattern) from every possible arrangement of those pattern tiles on the board, ignoring the numbers on all non-pattern tiles.
During
To combine heuristic values from multiple pattern databases without overestimating the true cost to the goal, the set of all tiles must be partitioned into disjoint (non-overlapping) subsets.
Let
When subsets are strictly disjoint, any move made by a tile in subset
Consider a disjoint partition of the
- Subset
$S_1 = {1, 2, 3}$ - Subset
$S_2 = {4, 5, 6}$ - Subset
$S_3 = {7, 8}$ (along with the blank square)
For a given board configuration state
-
$h_{\text{PDB}, 1}(n) = 9$ moves for pattern tiles${1, 2, 3}$ -
$h_{\text{PDB}, 2}(n) = 7$ moves for pattern tiles${4, 5, 6}$ -
$h_{\text{PDB}, 3}(n) = 3$ moves for pattern tiles${7, 8}$
The total additive PDB heuristic for state
For this same state configuration
Because
In large-scale or continuous state spaces where constructing pattern databases requires excessive memory, modern AI constructs data-driven heuristics by training parameterized neural networks
The learning objective is formulated as minimizing an empirical loss function (such as Mean Squared Error) over a dataset of
While neural network heuristics
Neural
In PyTorch, building and utilizing a learned heuristic model
-
Model Architecture Definition (
torch.nn.Module): The heuristic network is defined as a class inheriting fromtorch.nn.Module. Layers such as linear transformations (torch.nn.Linear) or convolutions (torch.nn.Conv2d) are instantiated in__init__, and the forward execution flow is specified in theforwardmethod:import torch import torch.nn as nn class HeuristicNetwork(nn.Module): def __init__(self, input_dim: int, hidden_dim: int): super(HeuristicNetwork, self).__init__() self.fc1 = nn.Linear(input_dim, hidden_dim) self.relu = nn.ReLU() self.fc2 = nn.Linear(hidden_dim, 1) def forward(self, x: torch.Tensor) -> torch.Tensor: out = self.fc1(x) out = self.relu(out) out = self.fc2(out) return out
-
Training Loop & Optimization: Model weights
$\theta$ are updated iteratively using gradient descent. In each iteration, batch inputs$\mathbf{X}_{\text{batch}}$ pass through the network, prediction loss is computed, gradients are reset usingoptimizer.zero_grad(), backpropagation is triggered vialoss.backward(), and weights are updated usingoptimizer.step():model = HeuristicNetwork(input_dim=9, hidden_dim=64) optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) criterion = nn.MSELoss() # Forward pass, loss evaluation, and backpropagation predictions = model(states_batch) loss = criterion(predictions, targets_batch) optimizer.zero_grad() loss.backward() optimizer.step()
-
Inference & Search Integration: During search evaluation, the network is set to evaluation mode (
model.eval()) with gradient tracking disabled (with torch.no_grad():) to evaluate batched state tensors$\mathbf{S}_{\text{batch}}$ efficiently on GPU hardware, yielding heuristic estimates$h_\theta(\overrightarrow{s})$ for priority queue ordering$f(n) = g(n) + h_\theta(\overrightarrow{s})$ .
AlphaZero exemplifies learned heuristic systems in complex decision-making domains (e.g., Chess, Shogi, Go). It operates completely free of human domain knowledge or predefined opening books, acquiring strategy entirely through self-play reinforcement learning.
AlphaZero utilizes a deep neural network parameterized by weights
-
Policy Head
$\overrightarrow{P}_\theta(a|\overrightarrow{s})$ : A vector of probabilities over all valid actions$a$ , providing goal-directed move prioritization. -
Value Head
$V_\theta(\overrightarrow{s})$ : A scalar estimate of the expected game outcome from state$\overrightarrow{s}$ (acting as a learned cost-to-go / state-value heuristic).
During move selection, AlphaZero executes Monte Carlo Tree Search (MCTS) guided by
After playing self-play games to completion, outcome
Through millions of self-play iterations, this feedback loop enables AlphaZero to learn heuristic evaluations that surpass traditional human-engineered heuristics.