[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,88 +2,172 @@
|
||||
id: wiki-2026-0508-simulated-annealing
|
||||
title: Simulated Annealing
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [MATH-OPT-SA-001]
|
||||
aliases: [SA, Metropolis-Hastings Optimization]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [math, Optimization, simulated-annealing, Heuristics, global-optimum, algorithm, stochastic-process]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [optimization, metaheuristic, combinatorial, stochastic]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-26
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: python
|
||||
framework: scipy/numpy
|
||||
---
|
||||
|
||||
# Simulated Annealing (시뮬레이티드 어닐링)
|
||||
# Simulated Annealing
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "초기에는 뜨거운 열기(Randomness)로 지역적 최적해의 함정을 뛰어넘고, 서서히 식어가는 지혜(Cooling Schedule)를 통해 전역 최적해라는 완벽한 결정체를 형성하라" — 금속 공학의 담금질 원리를 모방하여, 복잡한 탐색 공간에서 지역 최적해(Local Optima)를 탈출하고 전역 최적해(Global Optimum)를 찾기 위한 확률적 최적화 기법.
|
||||
## 매 한 줄
|
||||
> **"매 hot exploration → cold exploitation."**. 1983 Kirkpatrick et al. metallurgy annealing analogy로 도입. Temperature schedule이 acceptance probability 제어 → local optima 탈출. 2026 still production-grade for TSP, scheduling, hyperparam tuning when gradients unavailable.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Stochastic Exploration and Gradual Convergence" — 현재보다 좋지 않은 해([[Solution|Solution]])라도 온도($T$)에 따른 특정 확률로 수용함으로써 탐색의 범위를 넓히고, 시간이 흐름에 따라 온도를 낮춰 점점 정교하게 정답에 안착하는 패턴.
|
||||
- **핵심 메커니즘:**
|
||||
- **Temperature ($T$):** 탐색의 무작위성을 결정하는 변수. 초기에 높고 서서히 낮아짐.
|
||||
- **Metropolis Criterion:** 나쁜 해를 수용할 확률 $P = \exp(-\Delta E / T)$. 온도가 높을수록, 오차가 작을수록 나쁜 해를 더 잘 받아들임.
|
||||
- **Cooling Schedule:** 온도를 얼마나 빨리 식힐지 결정하는 함수. 학습의 성패를 좌우함.
|
||||
- **의의:** 수학적으로 해를 구하기 어려운 조합 최적화 문제(예: TSP)나 매우 복잡한 손실 함수를 가진 모델 학습에서 전역적인 시야를 유지하게 해주는 강력한 메타휴리스틱 도구.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 연산 속도가 느리다는 단점 때문에 경사 하강법(Gradient Descent)에 밀리는 듯했으나, 경사 정보를 알 수 없는 비연속적 공간이나 강화학습의 하이퍼파라미터 최적화 등에서 여전히 대체 불가능한 가치를 발휘함.
|
||||
- **정책 변화:** Antigravity 프로젝트는 에이전트의 작업 스케줄링 최적화나 복잡한 지식 그래프의 클러스터링 초기값 설정 시, 지역 최적해 함정을 피하기 위해 시뮬레이티드 어닐링의 확률적 탐색 로직을 적용함.
|
||||
### 매 Metropolis 기준
|
||||
- ΔE ≤ 0 → always accept.
|
||||
- ΔE > 0 → accept with probability exp(−ΔE / T).
|
||||
- T → 0: greedy descent. T → ∞: random walk.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Optimization-Algorithms|Optimization-Algorithms]], [[Randomized-Algorithms|Randomized-Algorithms]], [[Reinforcement-Learning|Reinforcement-Learning]], Algorithm-Complexity-[[Analysis|Analysis]]
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Simulated-Annealing.md
|
||||
### 매 Cooling Schedules
|
||||
- **Linear**: T_k = T_0 − αk (rare — too aggressive).
|
||||
- **Geometric**: T_k = T_0 · α^k, α ∈ [0.85, 0.99] (most common).
|
||||
- **Logarithmic**: T_k = c / log(k+2) (provable convergence, very slow).
|
||||
- **Adaptive**: 매 reheat on stagnation.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. TSP / VRP 등 combinatorial optim.
|
||||
2. Boltzmann machine training (historical).
|
||||
3. Hyperparameter search w/ noisy objective.
|
||||
4. Protein folding, circuit placement.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### Bare-bones SA
|
||||
```python
|
||||
import math, random
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
def simulated_annealing(x0, energy, neighbor,
|
||||
T0=1.0, alpha=0.95, n_iter=10_000):
|
||||
x, best = x0, x0
|
||||
e = e_best = energy(x0)
|
||||
T = T0
|
||||
for k in range(n_iter):
|
||||
x_new = neighbor(x)
|
||||
e_new = energy(x_new)
|
||||
de = e_new - e
|
||||
if de <= 0 or random.random() < math.exp(-de / T):
|
||||
x, e = x_new, e_new
|
||||
if e < e_best:
|
||||
best, e_best = x, e
|
||||
T *= alpha
|
||||
return best, e_best
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### TSP with 2-opt neighbor
|
||||
```python
|
||||
def tour_length(tour, dist):
|
||||
return sum(dist[tour[i]][tour[(i+1) % len(tour)]]
|
||||
for i in range(len(tour)))
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
def two_opt(tour):
|
||||
i, j = sorted(random.sample(range(len(tour)), 2))
|
||||
return tour[:i] + tour[i:j+1][::-1] + tour[j+1:]
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
best_tour, _ = simulated_annealing(
|
||||
list(range(n)),
|
||||
lambda t: tour_length(t, dist),
|
||||
two_opt, T0=10.0, alpha=0.999, n_iter=100_000
|
||||
)
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### scipy dual_annealing (production)
|
||||
```python
|
||||
from scipy.optimize import dual_annealing
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
def f(x): return (x[0]-3)**2 + (x[1]+1)**2 + 0.1*np.sin(10*x[0])
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
result = dual_annealing(f, bounds=[(-10,10), (-10,10)],
|
||||
maxiter=2000, seed=42)
|
||||
print(result.x, result.fun)
|
||||
```
|
||||
|
||||
### Adaptive reheating
|
||||
```python
|
||||
def sa_with_reheat(x0, energy, neighbor, T0, alpha, n_iter,
|
||||
stall_limit=500):
|
||||
x, e_best = x0, energy(x0)
|
||||
T, stall = T0, 0
|
||||
for k in range(n_iter):
|
||||
x_new = neighbor(x); de = energy(x_new) - e_best
|
||||
if de <= 0 or random.random() < math.exp(-de/T):
|
||||
x = x_new
|
||||
if energy(x) < e_best:
|
||||
e_best = energy(x); stall = 0
|
||||
else: stall += 1
|
||||
else: stall += 1
|
||||
T *= alpha
|
||||
if stall > stall_limit:
|
||||
T = T0 * 0.5 # reheat
|
||||
stall = 0
|
||||
return x, e_best
|
||||
```
|
||||
|
||||
### Parallel tempering (multi-temperature)
|
||||
```python
|
||||
def parallel_tempering(x0, energy, neighbor,
|
||||
Ts=[0.1, 0.5, 1.0, 5.0], n_iter=10_000):
|
||||
chains = [list(x0) for _ in Ts]
|
||||
energies = [energy(c) for c in chains]
|
||||
for k in range(n_iter):
|
||||
for i, T in enumerate(Ts):
|
||||
x_new = neighbor(chains[i])
|
||||
de = energy(x_new) - energies[i]
|
||||
if de <= 0 or random.random() < math.exp(-de/T):
|
||||
chains[i] = x_new; energies[i] = energy(x_new)
|
||||
# Swap adjacent temperatures
|
||||
i = random.randint(0, len(Ts)-2)
|
||||
de = (1/Ts[i] - 1/Ts[i+1]) * (energies[i+1] - energies[i])
|
||||
if random.random() < math.exp(-de):
|
||||
chains[i], chains[i+1] = chains[i+1], chains[i]
|
||||
energies[i], energies[i+1] = energies[i+1], energies[i]
|
||||
return chains[0]
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Smooth, differentiable | gradient methods (Adam, L-BFGS) |
|
||||
| Combinatorial, no gradient | SA / Tabu / GA |
|
||||
| Multi-modal, expensive eval | Bayesian optimization |
|
||||
| Massive scale, structure | branch-and-bound + LP relaxation |
|
||||
| Real-time low-iter budget | greedy + local search |
|
||||
|
||||
**기본값**: SA via `scipy.optimize.dual_annealing` for continuous; custom 2-opt+SA for combinatorial.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Optimization]] · [[Metaheuristics]]
|
||||
- 변형: [[Quantum-Annealing]] · [[Parallel-Tempering]] · [[Tabu-Search]]
|
||||
- 응용: [[TSP]] · [[Combinatorial-Optimization]] · [[Hyperparameter-Tuning]]
|
||||
- Adjacent: [[Markov-Chain-Monte-Carlo]] · [[Genetic-Algorithms]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: cooling schedule 추천, neighbor function 설계 brainstorm, convergence diagnosis.
|
||||
**언제 X**: 매 high-iter SA 매 LLM 안에서 직접 실행 (use scipy locally).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Cooling too fast**: α=0.5 → 매 immediate freeze, no exploration.
|
||||
- **Cooling too slow**: 매 budget 낭비, gradient method 가 빠름.
|
||||
- **Bad neighbor**: 매 너무 큰 jump → random search. 매 너무 작 → local trap.
|
||||
- **No restart**: single chain stuck → use parallel tempering / random restart.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Kirkpatrick et al. 1983 *Science*; *scipy* docs 2025).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Metropolis 기준, cooling schedules, TSP/parallel tempering 패턴 |
|
||||
|
||||
Reference in New Issue
Block a user