Clustering with simulated annealing
Simulated annealing is a stochastic optimisation method for clustering that searches for a low-cost partition by occasional uphill moves controlled by a temperature parameter, useful when clustering objective surfaces have many local minima.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Simulated annealing (SA) for clustering gives an engineer a way to find better clusterings when the objective (for example, within-cluster variance) has many local minima. It is used when K-means or greedy heuristics get stuck, in situations such as image segmentation, feature grouping, or any clustering in non-convex spaces.
Key ideas
Configuration (state): a complete assignment of each data point to a cluster (for K clusters). Denote assignment vector c where c(i) ∈ {1..K}. A configuration uniquely determines cluster centroids when using WCSS.
Neighbourhood: a rule that defines which configurations are reachable from the current one in a single move. Common neighbourhoods for clustering:
- Reassign move: pick one point i and assign it to a different cluster j ≠ c(i).
- Swap move: swap the cluster labels of two points.
- Merge/split moves: combine two clusters or split one cluster into two (used in variable-K SA). The neighbourhood must allow the entire configuration space to be explored (ergodicity assumption) for convergence results.
Temperature (T): a positive scalar controlling acceptance of uphill moves. High T allows worse configurations to be accepted often; low T makes the algorithm greedy.
Metropolis acceptance criterion: when a proposed move changes energy by ΔE = E(new) − E(old), accept the new configuration with probability 1 if ΔE ≤ 0 (energy decreases) and otherwise with probability
exp(−ΔE/T). This form assumes a symmetric proposal distribution; for asymmetric proposals use the Metropolis–Hastings acceptance min(1, exp(−ΔE/T) · q(old|new)/q(new|old)).Cooling schedule: how T is reduced over iterations. Common schedules: geometric T_{k+1} = α·T_k (0 < α < 1) and logarithmic T_k = c / log(k + k0) with k ≥ 1 and k0 > 1. A theoretical result (stated below) requires a slow (logarithmic) cooling to guarantee convergence to a global optimum.
Convergence theorem (exact statement used in university courses): Under the assumptions that (1) the Markov chain induced by the neighbourhood and the Metropolis acceptance probabilities is irreducible and aperiodic for each fixed positive T, (2) the cooling schedule is of the form T_k = c / log(k + k0) with k ≥ 1, k0 > 1, and c chosen at least as large as the problem’s critical depth (energy barrier height), and (3) each temperature stage is allowed to approach equilibrium (e.g., the number of iterations per temperature L_k increases so the chain mixes sufficiently), then simulated annealing visits the global minimum with probability tending to 1 as k → ∞. This is a theoretical guarantee; in practice geometric cooling is used for reasonable run times.
Algorithm outline (step-by-step):
- Choose initial configuration c0 (for example from random assignment or K-means), initial temperature T0, cooling schedule, and number of iterations per temperature L.
- Repeat for k = 0, 1, 2, ... until stopping condition: a. For ℓ = 1..L: propose a neighbour configuration c' from current c (for example, reassign one random point). b. Compute ΔE = E(c') − E(c). c. If ΔE ≤ 0 accept c := c'. Else accept with probability p = exp(−ΔE / T_k). d. (Optionally) update best-so-far solution. e. After L proposals reduce temperature T_{k+1} according to cooling schedule. For theoretical convergence, L is typically increased with k to allow near-equilibration at each temperature.
- Return best configuration found.
Diagrams to draw for exams: draw a 1D energy landscape (x axis = configurations or an index of configurations, y axis = energy). Show multiple local minima and a global minimum. Draw paths of greedy descent (stuck in local minimum) and SA path that jumps over barriers at high T and refines at low T. Label local minima, barrier height Δ, temperature effect on acceptance probability.
Formulas
E = Σ_{i=1..n} || x_i − μ_{c(i)} ||^2 where E is the WCSS energy (units: (feature units)^2), x_i is the i-th feature vector, and μ_{c(i)} is the centroid of the cluster assigned to x_i. Applies when using squared Euclidean cost for clustering.
μ_j = (1 / n_j) Σ_{i: c(i)=j} x_i where μ_j is the centroid of cluster j (units: feature units) and n_j is the number of points assigned to cluster j (dimensionless count). Applies when n_j > 0.
ΔE = E(new configuration) − E(current configuration) change in energy after a proposed move (units same as E).
p_accept = 1, if ΔE ≤ 0 acceptance probability for downhill moves.
p_accept = exp(−ΔE / T), if ΔE > 0 acceptance probability for uphill moves; T is temperature (same units as E so ΔE/T is dimensionless; in practice T is in same units as E).
T_{k+1} = α · T_k geometric cooling schedule, 0 < α < 1 (dimensionless); common α in [0.8,0.99].
T_{k} = c / log(k + k0) logarithmic cooling schedule with k ≥ 1 and k0 > 1; c is a constant chosen with respect to energy barrier depths. This schedule is used in convergence proofs.
Worked examples
Example 1 — small 1D numerical step-by-step (university style)
Data (unit: arbitrary feature units): x = [1, 2, 3, 10, 11]. Let K = 2.
Initial assignment: c = [1, 1, 1, 2, 2] (clusters labelled 1 and 2).
Step 1: compute centroids.
Formula: μ_j = (1 / n_j) Σ_{i: c(i)=j} x_i.
Cluster 1: points {1,2,3} → μ1 = (1+2+3)/3 = 2.0 (units: feature units).
Cluster 2: points {10,11} → μ2 = (10+11)/2 = 10.5.
Step 2: compute energy E.
Formula: E = Σ ||x_i − μ_{c(i)}||^2.
Cluster 1 contribution: (1−2)^2 + (2−2)^2 + (3−2)^2 = 1 + 0 + 1 = 2.
Cluster 2 contribution: (10−10.5)^2 + (11−10.5)^2 = 0.25 + 0.25 = 0.5.
Total E = 2 + 0.5 = 2.5 (feature units^2).
Propose a move: reassign point x3 = 3 from cluster 1 to cluster 2.
New clusters: cluster 1: {1,2} → μ1' = (1+2)/2 = 1.5. cluster 2: {3,10,11} → μ2' = (3+10+11)/3 = 8.0.
New energy:
Cluster 1: (1−1.5)^2 + (2−1.5)^2 = 0.25 + 0.25 = 0.5.
Cluster 2: (3−8)^2 + (10−8)^2 + (11−8)^2 = 25 + 4 + 9 = 38.
E' = 0.5 + 38 = 38.5.
ΔE = 38.5 − 2.5 = 36.0 (increase).
Acceptance probability at temperature T = 10: p = exp(−ΔE/T) = exp(−36/10) ≈ 0.0273.
At T = 100: p ≈ exp(−0.36) ≈ 0.6977.
Conclusion: at high temperature the move may be accepted; at low temperature it is very unlikely.
Example 2 — complete small Python program (runable) that implements SA for the 1D example above and prints exact output. Program (Python 3):
import math
import random
random.seed(0)
# Data and parameters
X = [1.0, 2.0, 3.0, 10.0, 11.0]
K = 2
assign = [0, 0, 0, 1, 1] # initial assignment (0-based cluster indices)
def centroids(X, assign, K):
sums = [0.0]*K
counts = [0]*K
for x, c in zip(X, assign):
sums[c] += x
counts[c] += 1
mus = []
for j in range(K):
if counts[j] > 0:
mus.append(sums[j]/counts[j])
else:
mus.append(None) # empty cluster
return mus, counts
def energy(X, assign, K):
mus, counts = centroids(X, assign, K)
E = 0.0
for x, c in zip(X, assign):
mu = mus[c]
E += (x - mu)**2
return E
# SA parameters
T = 10.0
alpha = 0.9
iters_per_T = 10
max_temps = 5
print('Initial assignment:', assign)
print('Initial energy: {:.4f}'.format(energy(X, assign, K)))
best_assign = list(assign)
best_E = energy(X, assign, K)
current_assign = list(assign)
current_E = best_E
for temp_iter in range(max_temps):
for _ in range(iters_per_T):
i = random.randrange(len(X))
oldc = current_assign[i]
newc = random.choice([c for c in range(K) if c != oldc])
candidate_assign = list(current_assign)
candidate_assign[i] = newc
cand_E = energy(X, candidate_assign, K)
dE = cand_E - current_E
if dE <= 0 or random.random() < math.exp(-dE / T):
current_assign = candidate_assign
current_E = cand_E
if current_E < best_E:
best_E = current_E
best_assign = list(current_assign)
T *= alpha
mus, counts = centroids(X, best_assign, K)
print('\nBest assignment found:', best_assign)
print('Best energy: {:.4f}'.format(best_E))
print('Centroids:', mus)
Sample exact output when run (Python 3.8+) with the code above and random.seed(0):
Initial assignment: [0, 0, 0, 1, 1] Initial energy: 2.5000
Best assignment found: [0, 0, 0, 1, 1] Best energy: 2.5000 Centroids: [2.0, 10.5]
Notes: this simple program uses single-point reassign moves and geometric cooling. It demonstrates that for this easy problem the initial good partition is kept.
Common mistakes
- Using too-fast cooling (α too small) which makes SA behave like greedy descent and get stuck in local minima.
- Not ensuring neighbourhood ergodicity — for example, only allowing moves that never change certain points makes global optimum unreachable.
- Not handling empty clusters (division by zero when computing centroids). Either forbid moves that empty a cluster or impose a penalty.
- Miscomputing acceptance probability sign: use exp(−ΔE/T) only when ΔE > 0; accept immediately when ΔE ≤ 0.
For your exam
Kinds of questions:
- Definitions: define simulated annealing, temperature, neighbourhood, Metropolis criterion.
- Short notes: advantages/disadvantages of SA vs K-means; cooling schedules.
- Derivations: derive the Metropolis acceptance probability from detailed balance (you should state detailed balance and show the acceptance ensures the stationary distribution ∝ exp(−E/T)).
- Numericals: compute ΔE and acceptance probability for a given dataset and single-point reassignment (like Example 1). Show centroids, energies and probabilities with units.
- Programs: write a short pseudocode or Python program for SA clustering; explain choices for neighbourhood, initial configuration, cooling schedule and stopping condition.
- Diagrams: sketch an energy landscape with local minima and annotate how SA can escape at high T.
What a full-marks answer includes:
- Clear definitions with bolded terms, explicit formula for energy, description of neighbourhood and temperature, and a correct Metropolis acceptance rule.
- For derivations: state and use detailed balance; for convergence mention assumptions (irreducibility, aperiodicity, logarithmic cooling) and explain practical trade-off vs theoretical guarantee.
- For numericals: show all steps, compute centroids and energies correctly, show ΔE and compute exact exponential probability to at least 3 significant figures.
Quick check
- State the Metropolis acceptance probability for a proposed move that increases energy by ΔE at temperature T.
- Why must the neighbourhood be ergodic (irreducible) for SA convergence proofs?
- Give one practical disadvantage of using the theoretical logarithmic cooling schedule.
Answers: 1) exp(−ΔE / T) for ΔE > 0 (accept always if ΔE ≤ 0). 2) So every configuration is reachable eventually and the Markov chain can explore the whole state space; without it some global minima may be unreachable. 3) It is too slow in practice — requires impractically many iterations to converge, so geometric cooling is often used instead.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?