AI Wiki中文/EN

Local search and neighborhoods

局部搜索与邻域设计

Model feasible assignments, derive exact MAX-CUT move gains, and compare neighborhoods under a declared evaluation budget.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A move changes what “stuck” means

A solver divides four vertices into two groups, written as 0011. It tries moving each vertex to the other group. Every move makes the score worse, so it stops. Give the solver permission to move two vertices together and the same partition has an immediate improvement.

Local search works with a current complete assignment and edits it through a chosen neighborhood. The desired output is often the assignment itself; the sequence of edits need not be part of the answer. Berkeley’s introduction uses this distinction to separate configuration optimization from finding a route. CS188, section 1.5

This chapter designs the representation, neighborhood and score of a small weighted MAX-CUT problem. Hill climbing studies how to choose improving moves, while simulated annealing studies accepting some worsening moves. Both need the modeling decisions made here.

Specify the assignments before choosing a solver

Let G=(V,E)G=(V,E) be a finite, undirected graph without self-loops. Each edge is stored once and has a nonnegative weight wuvw_{uv}. A bit xvx_v assigns vertex vv to group 0 or 1. Either group is allowed to be empty, and there is no balance constraint. The objective counts edges whose endpoints lie in different groups:

C(x)=∑{u,v}∈Ewuv 1[xu≠xv].C(x)=\sum_{\{u,v\}\in E}w_{uv}\,\mathbf{1}[x_u\ne x_v].

The indicator is 1 when its condition is true and 0 otherwise. Complementing every bit leaves the cut unchanged, so two bit strings can represent the same unlabeled partition. Our implementation keeps both strings to keep the move rules simple.

Define Nk(x)N_k(x) as the assignments obtained by flipping between 1 and kk distinct bits. A local optimum for maximization satisfies

C(x)≥C(y)∀y∈Nk(x).C(x)\ge C(y)\qquad\forall y\in N_k(x).

The neighborhood is part of this statement. A local optimum for N1N_1 need not be one for N2N_2. Since N1N_1 is contained in N2N_2, every N2N_2 local optimum is also an N1N_1 local optimum. No implication about the time needed to find one follows from that inclusion.

Consider the cycle with edges (0,1)(0,1) and (2,3)(2,3) of weight 2, and edges (1,2)(1,2) and (3,0)(3,0) of weight 3. At 0011, the two weight-3 edges cross, giving 6. Flipping any single vertex loses a crossing edge of weight 3 and gains one of weight 2: the change is −1. Flipping vertices 1 and 2 together gives 0101, where all four edges cross, giving 10. The value 10 is globally optimal here because it equals the total edge weight. This four-vertex calculation says nothing about larger instances.

The exact gain from flipping a single vertex vv is

Δv(x)=∑u:{u,v}∈E, xu=xvwuv−∑u:{u,v}∈E, xu≠xvwuv.\Delta_v(x)=\sum_{u:\{u,v\}\in E,\ x_u=x_v}w_{uv}-\sum_{u:\{u,v\}\in E,\ x_u\ne x_v}w_{uv}.

Only incident edges change. For a set SS of flipped vertices, edges with both endpoints in SS keep their crossing status. Count only edges with exactly one endpoint in SS:

ΔS(x)=∑{u,v}∈E∣{u,v}∩S∣=1wuv(1−21[xu≠xv]).\Delta_S(x)=\sum_{\substack{\{u,v\}\in E\\|\{u,v\}\cap S|=1}}w_{uv}\bigl(1-2\mathbf{1}[x_u\ne x_v]\bigr).

Adding two single-vertex gains without correcting their shared edge is wrong. In our example, the two gains are −1 and −1, but the combined gain is +4: their crossing weight-3 edge stays crossing rather than being lost twice.

There is a useful guarantee when every single-vertex gain is nonpositive. Write WW for total edge weight. Summing the gains over all vertices counts every uncut edge positively twice and every cut edge negatively twice:

∑v∈VΔv(x)=2(W−2C(x)).\sum_{v\in V}\Delta_v(x)=2\bigl(W-2C(x)\bigr).

The left side is nonpositive at an N1N_1 local optimum, so C(x)≥W/2C(x)\ge W/2. Nonnegative weights give OPT≤W\mathrm{OPT}\le W, hence C(x)≥OPT/2C(x)\ge\mathrm{OPT}/2. This is a worst-case lower bound, not a claim that half is the usual quality or the best known approximation guarantee. It requires all single flips to be permitted and inspected. A budget interruption supplies no such certificate. Wayne’s lecture presents the nonnegative MAX-CUT guarantee. Local Search, slide 23

Hard constraints need separate treatment. If each group must contain exactly two vertices, a single flip is infeasible. Swapping vertices from opposite groups preserves group sizes, but changes the neighborhood and invalidates the preceding single-flip proof. A finite penalty for imbalance also changes the objective; a high penalized score alone does not certify a feasible partition. Decide whether feasibility is enforced by representation, move filtering or an explicit constraint check.

Compute the changed edges and count the work

The complete Python program uses only the standard library. make_graph validates positive vertex count, distinct endpoints, nonnegative integer weights and no repeated undirected edges. Zero-weight edges and isolated vertices are allowed. The search validates an initial sequence of integer bits, k∈{1,2}k\in\{1,2\} and a nonnegative integer candidate budget. Booleans are rejected where integers are required. The small helper functions assume validated graph, state and move arguments.

A sweep examines the neighborhood in a fixed order: single flips first, then pairs in lexicographic vertex order. It retains the first strictly best gain. A complete sweep with no improvement certifies local optimality for the selected neighborhood. When the budget ends partway through a sweep, the program applies the best improving move examined so far, if any, and reports budget. That move need not be best over the whole neighborhood. Only positive gains are accepted, so the current state is also the best state visited.

from itertools import combinations, product


def make_graph(n, edges):
    if type(n) is not int or n < 1:
        raise ValueError('n must be a positive integer')
    adjacent = [[] for _ in range(n)]
    stored, seen = [], set()
    for u, v, weight in edges:
        if (type(u) is not int or type(v) is not int
                or not 0 <= u < n or not 0 <= v < n or u == v):
            raise ValueError('edges need distinct vertices in range(n)')
        if type(weight) is not int or weight < 0:
            raise ValueError('weights must be nonnegative integers')
        key = tuple(sorted((u, v)))
        if key in seen:
            raise ValueError('store each undirected edge only once')
        seen.add(key)
        stored.append((u, v, weight))
        adjacent[u].append((v, weight))
        adjacent[v].append((u, weight))
    return adjacent, stored


def cut_value(graph, state):
    return sum(w for u, v, w in graph[1] if state[u] != state[v])


def gain(graph, state, move):
    # Helpers assume a valid state and distinct, in-range move vertices.
    moved = set(move)
    delta = visits = 0
    for u in move:
        for v, w in graph[0][u]:
            visits += 1
            if v not in moved:
                delta += w if state[u] == state[v] else -w
    return delta, visits


def moves(n, k):
    for size in range(1, k + 1):
        yield from combinations(range(n), size)


def search(graph, initial, k=1, budget=100):
    n = len(graph[0])
    state = list(initial)
    if len(state) != n or any(type(b) is not int or b not in (0, 1)
                              for b in state):
        raise ValueError('initial must contain n integer bits')
    if type(k) is not int or k not in (1, 2):
        raise ValueError('k must be 1 or 2')
    if type(budget) is not int or budget < 0:
        raise ValueError('budget must be a nonnegative integer')
    value = cut_value(graph, state)
    evaluations = visits = accepted = 0
    while True:
        best_gain, best_move, complete = 0, None, True
        for move in moves(n, k):
            if evaluations == budget:
                complete = False
                break
            delta, work = gain(graph, state, move)
            evaluations += 1
            visits += work
            if delta > best_gain:
                best_gain, best_move = delta, move
        if best_move is None:
            status = 'local-optimum' if complete else 'budget'
            break
        for u in best_move:
            state[u] ^= 1
        value += best_gain
        accepted += 1
        if not complete:
            status = 'budget'
            break
    return {'state': tuple(state), 'value': value, 'status': status,
            'evaluations': evaluations, 'edge_visits': visits,
            'accepted': accepted}


graph = make_graph(4, [(0, 1, 2), (1, 2, 3),
                       (2, 3, 2), (3, 0, 3)])
start = (0, 0, 1, 1)
assert cut_value(graph, start) == 6
assert [gain(graph, start, (v,))[0] for v in range(4)] == [-1] * 4
assert gain(graph, start, (1, 2))[0] == 4
for k in (1, 2):
    result = search(graph, start, k=k, budget=10)
    print(k, result['value'], result['status'],
          result['evaluations'], result['edge_visits'])
# Exhaustive enumeration certifies this tiny instance only.
optimum = max(cut_value(graph, x) for x in product((0, 1), repeat=4))
assert optimum == 10
assert search(graph, start, k=2, budget=20)['status'] == 'local-optimum'
assert search(graph, start, budget=0)['status'] == 'budget'

The printed columns are neighborhood size limit, final value, stopping reason, candidate evaluations and incident-edge visits:

kkValueReasonCandidatesEdge visits
16local-optimum48
210budget1032

The second run has reached the optimum, but its own search has not completed a no-improvement sweep at the new state. The separate exhaustive check certifies the tiny example. Keeping those two forms of evidence separate prevents a fortunate answer from being mistaken for a search certificate.

A full objective evaluation scans mm edges. A single-flip gain scans deg⁡(v)\deg(v) entries; a two-flip gain scans deg⁡(u)+deg⁡(v)\deg(u)+\deg(v), including their shared edge twice for membership checks but never adding its weight. Across a complete single-flip sweep there are nn candidates and 2m2m visits. Adding all pairs gives n+(n2)n+\binom n2 candidates and 2mn2mn visits. Each vertex appears in n−1n-1 pairs, which explains the second count.

Including candidate bookkeeping, a sweep costs O(n+m)O(n+m) for k=1k=1 and O(n2+mn)O(n^2+mn) for k=2k=2, assuming constant-time integer arithmetic and set operations. The graph takes O(n+m)O(n+m) storage; the search uses O(n)O(n) extra storage and generates moves lazily. Very large integer weights add arithmetic costs. A complete run may require many sweeps even though each accepted move strictly increases the value: the elementary bound of at most WW accepted moves for integer weights depends on the numerical weight sum, not just its binary encoding length.

Poole and Mackworth describe the broader tradeoff between selecting the best available move and taking cheaper steps, including updating scores only where an assignment changed. The adjacency-based gain calculation above is an original implementation of that principle for this graph. Foundations of Computational Agents, section 4.6.3

Compare results at a declared budget

“Ten iterations” is ambiguous: one iteration might inspect one candidate or thousands. Our table fixes at most ten candidate evaluations per run and also reports edge visits. Those ten candidates cost different amounts in the two neighborhoods. Graph construction and the initial full score are outside the candidate budget; the exhaustive oracle is validation work and is also excluded. A time-based comparison must include the preparation costs that the application actually pays.

For a reproducible small comparison, run both settings from each of the 16 initial bit strings of this graph, with budget 10 and the code’s fixed tie order. The outcomes are below. The value 10 and value 6 columns count runs; the final column counts total edge visits:

kkRuns with value 10Runs with value 6Mean valueTotal edge visits
11429.5240
216010512

This is an exhaustive set of starts for one constructed instance. It establishes neither a distribution of real problems nor a speed ranking. For larger experiments, pair the same starts and instances across methods, predeclare budgets and restart rules, report outcome distributions, and retain failed or interrupted runs. For randomized methods, record seeds and repeat across seeds. Parameter tuning needs different instances from final evaluation.

On a graph whose optimum is unknown, the best score found is a lower bound on the maximization optimum, not the optimum itself. Here WW is a simple certified upper bound; stronger bounds may require another algorithm. Report the bound and its origin with any gap. If W=0W=0, every cut scores zero, and a relative ratio with zero denominator is undefined.

Strict improvements terminate on a finite state space, but may stop below the global optimum. Enlarging the neighborhood can remove a particular local optimum while making each sweep more expensive. An unsatisfied constraint at a local optimum does not prove that the constraint problem has no solution. Poole and Mackworth distinguish that failure to find a solution from proving unsatisfiability. Section 4.6.1

Check the model before trusting the score

  1. At 0011, what happens when only vertex 1 moves, and when vertices 1 and 2 move together?
  2. A completed single-flip search on a nonnegative graph returns value 18 and total edge weight 30. What can be certified about the optimum? Does budget support the same conclusion?
  3. Both groups must contain exactly two vertices. Which of the program’s pair flips preserve feasibility, and why can the original one-flip proof no longer be used?
  4. Reproduce the 16-start comparison. Why does the k=2k=2 result fail to prove that it runs faster? What status should a budget of zero return?
Answers and checks
  1. Flipping vertex 1 gives 0111: gain −1 and value 5. Flipping 1 and 2 gives 0101: gain +4 and value 10. The edge between 1 and 2 remains crossing in the combined move.
  2. The returned cut proves 18≤OPT≤3018\le\mathrm{OPT}\le30. Checking every single flip supplies the half-optimum theorem; the numerical upper bound 30 is tighter than the derived bound 36. A budget stop still gives the feasible cut and total-weight upper bound, but does not certify local optimality or the theorem’s premise. If the cut separately satisfies C≥W/2C\ge W/2, that observed inequality independently implies the half-optimum bound.
  3. Flip one vertex from each current group. Flipping two vertices from the same group changes the sizes. Single flips are forbidden, so the required inequalities for all individual vertices are unavailable. The implementation must filter moves before it can solve the balanced variant.
  4. The table gives 14 versus 16 optimum-valued runs, but 240 versus 512 incident-edge visits. Candidate counts do not equal elapsed time or equal arithmetic work. A zero budget returns the unchanged initial partition with budget, zero candidates and zero accepted moves. It has not inspected the neighborhood.

Separate a neighborhood design from a search policy

The four-vertex example, gain evaluator and budget experiment in this chapter were constructed for teaching. They are not a published MAX-CUT benchmark. The repository tests recompute objective differences by exhaustive bit-mask enumeration, inspect all four-vertex graphs whose six possible edges have weights 0, 1 or 3, and check solver certificates against independent full enumeration.

For another problem, write down its legal assignments and moves before importing a search policy. Keep a slow full scorer beside the incremental one during development: their answers should agree after each move, including moves that touch the same constraint twice. A score drift of one unit can change a tie, alter the trajectory and invalidate a claimed local optimum. The next chapters use the same distinction between the state model and the rule that chooses the next state.

Make a prediction, then check

A run exhausts its budget and returns a partition. What can be directly asserted?

Choose one answer

Learning objectives

  • Specify states, feasibility and neighborhoods, and distinguish local optima with one- and two-flip counterexamples.
  • Derive and independently check MAX-CUT gains, state the half-optimum bound conditions, and interpret fixed-budget comparisons.

Prerequisites & connections

Explore related knowledge →

References

  1. CS188 Textbook: 1.5 Local Search
    UC Berkeley CS188 course staff
  2. Artificial Intelligence: Foundations of Computational Agents, third edition, 4.6 Local Search
    David L. Poole; Alan K. Mackworth
  3. Local Search: Algorithm Design lecture slides
    Kevin Wayne · 2017

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check:primary-source locations,original executable examples,independent finite-state oracles,bilingual review and a second Codex agent cross-check;not independent human peer review.

  • Reread both languages for feasibility, singleton and set gains, nonnegative proof, strict improvement, partial-budget rules, complexity and four answers; matched equations, code and six section anchors.
  • Seven tests passed: all16states and10moves on729four-vertex weight assignments against an independent full scorer;64unweighted graphs under complete and limited searches, certificates, shared-edge correction,16-start table, boundaries and input preservation.
  • Root reread bilingual modeling,gain sums,nonnegative half-optimum bound,partial budgets and work counts; another Codex agent independently checked1920budgeted searches on160sparse graphs of1–8vertices,all passing.
  • Paired code,display formulas and main anchors match. All48search checks and101article Python programs passed. Reviews are AI technical checks,not independent human peer review.
  • Static build found a same-line details/summary MDX parsing error. Split opening tags onto separate lines only; prose,equations and code are unchanged. Targeted inspection completed and hashes rebound.
  • After mobile screenshots, shortened Chinese headers and clarified run-count/total-edge-visit columns in both local-search articles. Algorithms,equations,values and conditions are unchanged; targeted rereading completed.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.