[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,88 +2,256 @@
|
||||
id: wiki-2026-0508-fitness-landscape
|
||||
title: Fitness Landscape
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [EVO-FIT-001]
|
||||
aliases: [fitness landscape, ruggedness, NK model, loss landscape, Wright, evolution]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [ai, Evolutionary-Computation, Optimization, fitness-landscape, complex-systems]
|
||||
confidence_score: 0.94
|
||||
verification_status: applied
|
||||
tags: [evolution, optimization, fitness-landscape, nk-model, loss-landscape, neuroevolution]
|
||||
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: NumPy / DEAP
|
||||
---
|
||||
|
||||
# Fitness Landscape (적합도 지형)
|
||||
# Fitness Landscape
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "최적의 해를 찾는 과정은 안개 낀 산맥에서 가장 높은 봉우리를 정복하는 탐험과 같다" — 유전형(Genotype)이나 파라미터 조합에 따른 적합도(Fitness) 값을 다차원 공간상의 지형으로 시각화하여, 최적화 과정의 난이도와 전략을 분석하는 도구.
|
||||
## 매 한 줄
|
||||
> **"매 genotype / parameter → 매 fitness / loss 의 mapping"**. Wright 1932. 매 ruggedness, 매 local optima, 매 plateau, 매 valley. 매 modern: 매 NK model, 매 DL loss landscape (flat vs sharp), 매 quality-diversity (MAP-Elites).
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** 탐색 공간 내의 '봉우리(Local Optima)'와 '골짜기'의 분포를 통해, 현재 알고리즘이 정체되어 있는지 아니면 더 나은 해를 향해 나아가고 있는지 판단하는 공간적 메타포 패턴.
|
||||
- **핵심 특징:**
|
||||
- **Ruggedness (굴곡도):** 지형이 얼마나 험난한지 나타냄. 굴곡이 심할수록 지역 최적해에 빠지기 쉬움.
|
||||
- **Neutrality:** 적합도 변화가 없는 평평한 평원 지대. 탐색 방향을 잃기 쉬움.
|
||||
- **Epistasis:** 변수들 간의 상호작용으로 인해 한 변수의 변화가 지형 전체에 미치는 영향.
|
||||
- **의의:** 알고리즘의 변이율(Mutation rate)이나 탐색 강도를 결정할 때, 지형의 특성에 맞춰 최적의 하이퍼파라미터를 설정하는 이론적 근거 제공.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 단순히 '더 좋은 값'을 찾는 것에서, 탐색 공간의 '구조'를 이해하여 효율적인 경로를 설계하는 방식으로 최적화의 관점 전환.
|
||||
- **정책 변화:** Antigravity 프로젝트는 에이전트의 보상 함수 설계 시, 적합도 지형이 너무 뾰족하거나(Needle in a haystack) 너무 평평하지 않도록 설계하여 학습 안정성을 확보함.
|
||||
### 매 dimensions
|
||||
- **Smooth**: 매 single peak.
|
||||
- **Rugged**: 매 many local optima.
|
||||
- **Neutral**: 매 plateau.
|
||||
- **Holey**: 매 sharp valley.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Evolutionary-Computation|Evolutionary-Computation]], [[Genetic-Algorithms|Genetic-Algorithms]], [[Black-Box-Optimization|Black-Box-Optimization]], [[Exploration-vs-Exploitation|Exploration-vs-Exploitation]]
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Fitness-Landscape.md
|
||||
### 매 model
|
||||
- **NK model** (Kauffman): 매 N genes, K interactions.
|
||||
- **HIFF**: 매 hierarchical.
|
||||
- **Royal Road**.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 ML / DL
|
||||
- **Loss landscape** (Li 2018): 매 visualize.
|
||||
- **Flat vs sharp minima** (Hochreiter): 매 generalization 의 affect.
|
||||
- **Connectivity**: 매 minima 의 path.
|
||||
- **SGD escape saddle**.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### 매 응용
|
||||
1. **Evolution**: 매 search.
|
||||
2. **Drug design**: 매 protein landscape.
|
||||
3. **DL training**: 매 minimum quality.
|
||||
4. **Hyperparameter**: 매 tune landscape.
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
### NK model
|
||||
```python
|
||||
import numpy as np
|
||||
def nk_fitness(genome, K, fitness_table):
|
||||
"""매 N-bit genome, K-interaction."""
|
||||
N = len(genome)
|
||||
fitness = 0
|
||||
for i in range(N):
|
||||
# 매 i 의 K neighbors
|
||||
context = tuple(genome[i] for i in [(i + j) % N for j in range(K + 1)])
|
||||
fitness += fitness_table[i][context]
|
||||
return fitness / N
|
||||
|
||||
- **정보 상태:** 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 init_nk(N, K):
|
||||
fitness_table = []
|
||||
for _ in range(N):
|
||||
fitness_table.append({tuple(np.random.randint(0, 2, K + 1)): np.random.rand() for _ in range(2 ** (K + 1))})
|
||||
return fitness_table
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Local search (hill climbing)
|
||||
```python
|
||||
def hill_climb(fitness_fn, init_genome, max_iter=1000):
|
||||
current = init_genome
|
||||
current_f = fitness_fn(current)
|
||||
for _ in range(max_iter):
|
||||
# 매 try flip 1 bit
|
||||
i = np.random.randint(len(current))
|
||||
neighbor = current.copy()
|
||||
neighbor[i] = 1 - neighbor[i]
|
||||
new_f = fitness_fn(neighbor)
|
||||
if new_f > current_f:
|
||||
current, current_f = neighbor, new_f
|
||||
return current, current_f
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Adaptive walks (count steps)
|
||||
```python
|
||||
def adaptive_walk_length(fitness_fn, N, n_starts=100):
|
||||
lengths = []
|
||||
for _ in range(n_starts):
|
||||
g = np.random.randint(0, 2, N)
|
||||
f = fitness_fn(g)
|
||||
steps = 0
|
||||
improved = True
|
||||
while improved:
|
||||
improved = False
|
||||
for i in range(N):
|
||||
neighbor = g.copy(); neighbor[i] = 1 - neighbor[i]
|
||||
if fitness_fn(neighbor) > f:
|
||||
g, f = neighbor, fitness_fn(neighbor)
|
||||
steps += 1; improved = True; break
|
||||
lengths.append(steps)
|
||||
return np.mean(lengths) # 매 longer = smoother
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Ruggedness measure (correlation)
|
||||
```python
|
||||
def fitness_correlation(fitness_fn, N, distance, n_pairs=1000):
|
||||
"""매 mutation 1 step → 매 correlation."""
|
||||
corrs = []
|
||||
for _ in range(n_pairs):
|
||||
g1 = np.random.randint(0, 2, N)
|
||||
g2 = g1.copy()
|
||||
for _ in range(distance):
|
||||
i = np.random.randint(N)
|
||||
g2[i] = 1 - g2[i]
|
||||
corrs.append((fitness_fn(g1), fitness_fn(g2)))
|
||||
f1, f2 = zip(*corrs)
|
||||
return np.corrcoef(f1, f2)[0, 1]
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### DL loss landscape visualization
|
||||
```python
|
||||
import torch
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
def loss_landscape_2d(model, loss_fn, X, y, alpha=0.5, beta=0.5):
|
||||
"""매 random direction 의 의 의 loss surface."""
|
||||
theta_orig = [p.data.clone() for p in model.parameters()]
|
||||
d1 = [torch.randn_like(p) for p in model.parameters()]
|
||||
d2 = [torch.randn_like(p) for p in model.parameters()]
|
||||
|
||||
losses = np.zeros((20, 20))
|
||||
for i, a in enumerate(np.linspace(-alpha, alpha, 20)):
|
||||
for j, b in enumerate(np.linspace(-beta, beta, 20)):
|
||||
for p, t, e1, e2 in zip(model.parameters(), theta_orig, d1, d2):
|
||||
p.data = t + a * e1 + b * e2
|
||||
losses[i, j] = loss_fn(model(X), y).item()
|
||||
|
||||
# 매 restore
|
||||
for p, t in zip(model.parameters(), theta_orig):
|
||||
p.data = t
|
||||
return losses
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Flat vs sharp
|
||||
```python
|
||||
def measure_flatness(model, loss_fn, X, y, eps=0.01):
|
||||
"""매 small perturbation 의 의 의 loss 변화."""
|
||||
base_loss = loss_fn(model(X), y).item()
|
||||
perturbed_losses = []
|
||||
for _ in range(50):
|
||||
# 매 add noise
|
||||
for p in model.parameters():
|
||||
p.data += eps * torch.randn_like(p)
|
||||
perturbed_losses.append(loss_fn(model(X), y).item())
|
||||
for p in model.parameters():
|
||||
p.data -= eps * torch.randn_like(p) # 매 wrong but illustrative
|
||||
return np.mean(perturbed_losses) - base_loss # 매 small = flat
|
||||
```
|
||||
|
||||
### Sharpness-Aware Minimization (SAM)
|
||||
```python
|
||||
class SAM(torch.optim.Optimizer):
|
||||
def __init__(self, params, base_optim, rho=0.05):
|
||||
super().__init__(params, dict())
|
||||
self.base = base_optim
|
||||
self.rho = rho
|
||||
|
||||
def first_step(self):
|
||||
grad_norm = torch.norm(torch.stack([p.grad.norm() for p in self.param_groups[0]['params'] if p.grad is not None]))
|
||||
for p in self.param_groups[0]['params']:
|
||||
if p.grad is None: continue
|
||||
e_w = self.rho * p.grad / (grad_norm + 1e-12)
|
||||
p.data.add_(e_w)
|
||||
p.state['e_w'] = e_w
|
||||
|
||||
def second_step(self):
|
||||
for p in self.param_groups[0]['params']:
|
||||
if 'e_w' in p.state:
|
||||
p.data.sub_(p.state['e_w'])
|
||||
self.base.step()
|
||||
```
|
||||
|
||||
### Mode connectivity
|
||||
```python
|
||||
def connect_minima(model_a, model_b, alpha=0.5):
|
||||
"""매 매 매 minima 의 path 의 loss."""
|
||||
interpolated = [(1 - alpha) * pa + alpha * pb
|
||||
for pa, pb in zip(model_a.parameters(), model_b.parameters())]
|
||||
# 매 set + eval
|
||||
return eval_loss(interpolated)
|
||||
```
|
||||
|
||||
### Quality-diversity (MAP-Elites)
|
||||
```python
|
||||
def map_elites(fitness_fn, behavior_fn, n_iter=10000, behavior_dim=10):
|
||||
archive = {} # 매 behavior cell → (genome, fitness)
|
||||
for _ in range(n_iter):
|
||||
if archive: parent = random.choice(list(archive.values()))[0]
|
||||
else: parent = random_genome()
|
||||
child = mutate(parent)
|
||||
f = fitness_fn(child)
|
||||
b = tuple(int(x * behavior_dim) for x in behavior_fn(child))
|
||||
if b not in archive or f > archive[b][1]:
|
||||
archive[b] = (child, f)
|
||||
return archive
|
||||
```
|
||||
|
||||
### Population diversity (genotype)
|
||||
```python
|
||||
def diversity(population):
|
||||
"""매 average pairwise distance."""
|
||||
n = len(population)
|
||||
return sum(np.sum(population[i] != population[j]) for i in range(n) for j in range(i+1, n)) / (n*(n-1)/2)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Smooth landscape | Gradient |
|
||||
| Rugged | GA + diversity |
|
||||
| Neutral plateau | Random walk |
|
||||
| DL training | SGD + SAM |
|
||||
| Flat min | SAM, weight averaging |
|
||||
| Quality-diversity | MAP-Elites |
|
||||
|
||||
**기본값**: 매 task-specific — 매 DL = SAM/SWA (flat min). 매 evolution = NK + diversity. 매 design = MAP-Elites.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Optimization]] · [[Evolution]]
|
||||
- 변형: [[Loss-Landscape]] · [[NK-Model]]
|
||||
- 응용: [[Evolutionary-Strategy]] · [[Hyperparameter-Tuning]] · [[MAP-Elites]]
|
||||
- Adjacent: [[Flat-Minima]] · [[Mode-Connectivity]] · [[SAM]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 optimization research. 매 DL training analysis. 매 evolution.
|
||||
**언제 X**: 매 single-shot deterministic.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Assume convex**: 매 rugged 의 ignore.
|
||||
- **No diversity**: 매 stuck local opt.
|
||||
- **Sharp min worship**: 매 generalization 의 lose.
|
||||
- **Visualize 2D for 1B param**: 매 misleading.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Wright 1932, Kauffman NK, Li 2018 loss landscape, Foret SAM 2021).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-04-26 | EVO-FIT auto |
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — NK / hill / ruggedness / loss / SAM / MAP-Elites code |
|
||||
|
||||
Reference in New Issue
Block a user