[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,62 +2,253 @@
|
||||
id: wiki-2026-0508-fuzzy-logic
|
||||
title: Fuzzy Logic
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [FUZZY-Logic-001]
|
||||
aliases: [fuzzy logic, fuzzy set, Zadeh, fuzzy controller, Mamdani, Sugeno]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [ai, fuzzy-logic, logic, Control-Theory, Robotics]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [fuzzy-logic, control, ai, expert-system, soft-computing, zadeh]
|
||||
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: Python
|
||||
framework: scikit-fuzzy / FuzzyLite
|
||||
---
|
||||
|
||||
# Fuzzy Logic (퍼지 논리)
|
||||
# Fuzzy Logic
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "참과 거짓 사이의 무수히 많은 회색 지대를 수학적으로 수용하여 인간다운 판단력을 구현하라" — 0(거짓)과 1(참) 사이의 소수점 값을 허용하는 소속 함수(Membership Function)를 통해, 현실 세계의 모호한 경계와 불확실성을 다루는 논리 체계.
|
||||
## 매 한 줄
|
||||
> **"매 0/1 의 X — 매 0..1 continuous degree"**. Zadeh 1965. 매 IF-THEN 의 의 의 linguistic. 매 controller, 매 expert system, 매 game AI. 매 modern: 매 mostly 매 ML 의 replace, but 매 control + 매 explainable AI 의 still relevant.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "조금", "적당히", "매우"와 같은 언어적 변수를 수치 범위로 변환(Fuzzification)하고, 이를 바탕으로 규칙 기반 추론을 수행한 뒤 다시 구체적인 행동 값으로 변환(Defuzzification)하는 제어 패턴.
|
||||
- **주요 특징:**
|
||||
- **Membership Function:** 어떤 집단에 속하는 정도(Degree)를 정의 (예: 온도 25도는 '적당함'에 0.8, '더움'에 0.2 소속).
|
||||
- **Fuzzy Rules:** "만약 온도가 '조금 더우면', 냉각 팬의 속도를 '적당히 빠르게' 하라"와 같은 직관적 규칙 적용 가능.
|
||||
- **[[Robustness|Robustness]]:** 입력값의 미세한 변화에도 출력이 급격히 변하지 않고 부드럽게 반응함.
|
||||
- **의의:** 정교한 수학적 모델링이 어려운 복잡한 시스템(가전제품 제어, 차량 브레이크 시스템, 게임 캐릭터의 성격 표현 등)에서 효율적인 해법 제공.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 엄격한 수식만이 정답이라 믿던 고전적 제어론에서 벗어나, 인간의 경험적 지식을 시스템에 녹여낼 수 있는 유연한 도구로 자리매김.
|
||||
- **정책 변화:** Skybound 프로젝트의 적 기체 AI는 플레이어와의 거리에 따라 '도망', '견제', '돌격' 상태를 퍼지 논리로 부드럽게 전환하여, 끊기지 않는 자연스러운 기동을 보여줌.
|
||||
### 매 component
|
||||
- **Fuzzy set**: 매 membership μ(x) ∈ [0, 1].
|
||||
- **Linguistic variable**: "tall", "warm".
|
||||
- **Rule**: IF temp is hot AND humidity is high THEN AC is high.
|
||||
- **Fuzzifier** → **Inference** → **Defuzzifier**.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Control-Theory|Control-Theory]], Expert-Systems, [[Artificial-Life|Artificial-Life]], Decision-Making
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Fuzzy-Logic.md
|
||||
### 매 inference
|
||||
- **Mamdani**: 매 fuzzy output → 매 defuzzify.
|
||||
- **Sugeno**: 매 crisp output (linear).
|
||||
- **Tsukamoto**: 매 monotonic.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. **Controller**: 매 washing machine, AC, brake.
|
||||
2. **Game AI**: 매 NPC behavior.
|
||||
3. **Expert system**: 매 medical diagnostic.
|
||||
4. **Image processing**: 매 edge detect.
|
||||
5. **Risk assessment**.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### Fuzzy set (membership)
|
||||
```python
|
||||
import numpy as np
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
def triangular(x, a, b, c):
|
||||
"""매 a → b → c 의 triangle."""
|
||||
if x <= a or x >= c: return 0
|
||||
if x == b: return 1
|
||||
if x < b: return (x - a) / (b - a)
|
||||
return (c - x) / (c - b)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
def trapezoidal(x, a, b, c, d):
|
||||
if x <= a or x >= d: return 0
|
||||
if b <= x <= c: return 1
|
||||
if x < b: return (x - a) / (b - a)
|
||||
return (d - x) / (d - c)
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
def gaussian(x, mu, sigma):
|
||||
return np.exp(-((x - mu) ** 2) / (2 * sigma ** 2))
|
||||
```
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
### scikit-fuzzy
|
||||
```python
|
||||
import skfuzzy as fuzz
|
||||
import skfuzzy.control as ctrl
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
# 매 inputs
|
||||
temp = ctrl.Antecedent(np.arange(0, 101, 1), 'temp')
|
||||
humidity = ctrl.Antecedent(np.arange(0, 101, 1), 'humidity')
|
||||
# 매 output
|
||||
ac = ctrl.Consequent(np.arange(0, 101, 1), 'ac')
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
# 매 membership
|
||||
temp['cold'] = fuzz.trimf(temp.universe, [0, 0, 30])
|
||||
temp['warm'] = fuzz.trimf(temp.universe, [20, 50, 80])
|
||||
temp['hot'] = fuzz.trimf(temp.universe, [70, 100, 100])
|
||||
|
||||
humidity['low'] = fuzz.trimf(humidity.universe, [0, 0, 50])
|
||||
humidity['high'] = fuzz.trimf(humidity.universe, [50, 100, 100])
|
||||
|
||||
ac['off'] = fuzz.trimf(ac.universe, [0, 0, 30])
|
||||
ac['med'] = fuzz.trimf(ac.universe, [20, 50, 80])
|
||||
ac['high'] = fuzz.trimf(ac.universe, [70, 100, 100])
|
||||
|
||||
# 매 rules
|
||||
rules = [
|
||||
ctrl.Rule(temp['hot'] & humidity['high'], ac['high']),
|
||||
ctrl.Rule(temp['hot'] & humidity['low'], ac['med']),
|
||||
ctrl.Rule(temp['warm'], ac['med']),
|
||||
ctrl.Rule(temp['cold'], ac['off']),
|
||||
]
|
||||
|
||||
ac_ctrl = ctrl.ControlSystem(rules)
|
||||
sim = ctrl.ControlSystemSimulation(ac_ctrl)
|
||||
sim.input['temp'] = 75
|
||||
sim.input['humidity'] = 60
|
||||
sim.compute()
|
||||
print(sim.output['ac'])
|
||||
```
|
||||
|
||||
### Manual Mamdani
|
||||
```python
|
||||
def fuzzify(value, mfs):
|
||||
"""매 value → 매 dict of (label, μ)."""
|
||||
return {label: mf(value) for label, mf in mfs.items()}
|
||||
|
||||
def apply_rule(antecedent_strengths, op='and'):
|
||||
if op == 'and': return min(antecedent_strengths)
|
||||
if op == 'or': return max(antecedent_strengths)
|
||||
|
||||
def aggregate(rule_outputs):
|
||||
"""매 max-aggregation of 매 (label, strength)."""
|
||||
aggregated = {}
|
||||
for label, strength in rule_outputs:
|
||||
aggregated[label] = max(aggregated.get(label, 0), strength)
|
||||
return aggregated
|
||||
|
||||
def defuzzify_centroid(consequent_mfs, aggregated, universe):
|
||||
"""매 center of gravity."""
|
||||
output_curve = np.zeros_like(universe)
|
||||
for label, strength in aggregated.items():
|
||||
mf_curve = np.array([consequent_mfs[label](u) for u in universe])
|
||||
output_curve = np.maximum(output_curve, np.minimum(mf_curve, strength))
|
||||
if output_curve.sum() == 0: return 0
|
||||
return (output_curve * universe).sum() / output_curve.sum()
|
||||
```
|
||||
|
||||
### Sugeno (TSK)
|
||||
```python
|
||||
def sugeno_inference(rules, x):
|
||||
"""매 rules: list of (antecedent_membership, output_function)."""
|
||||
weights = []
|
||||
outputs = []
|
||||
for ant_mu, out_fn in rules:
|
||||
w = ant_mu(x)
|
||||
weights.append(w)
|
||||
outputs.append(out_fn(x))
|
||||
if sum(weights) == 0: return 0
|
||||
return sum(w * o for w, o in zip(weights, outputs)) / sum(weights)
|
||||
```
|
||||
|
||||
### Game AI fuzzy
|
||||
```python
|
||||
def npc_aggression(distance_to_player, npc_health):
|
||||
"""매 close + healthy → aggressive."""
|
||||
close = max(0, 1 - distance_to_player / 100)
|
||||
healthy = npc_health / 100
|
||||
|
||||
aggression = min(close, healthy) # 매 AND
|
||||
fear = max(1 - healthy, 0)
|
||||
|
||||
if aggression > 0.7: return 'attack'
|
||||
if fear > 0.6: return 'flee'
|
||||
return 'patrol'
|
||||
```
|
||||
|
||||
### Defuzzification methods
|
||||
```python
|
||||
def defuzz_max(curve, universe):
|
||||
"""매 max of curve."""
|
||||
return universe[np.argmax(curve)]
|
||||
|
||||
def defuzz_mom(curve, universe):
|
||||
"""매 mean of maxima."""
|
||||
max_val = curve.max()
|
||||
return universe[curve == max_val].mean()
|
||||
|
||||
def defuzz_bisector(curve, universe):
|
||||
"""매 split area."""
|
||||
cum = np.cumsum(curve)
|
||||
half = cum[-1] / 2
|
||||
return universe[np.searchsorted(cum, half)]
|
||||
```
|
||||
|
||||
### Type-2 fuzzy (uncertainty in MF)
|
||||
```python
|
||||
class Type2FuzzyMF:
|
||||
"""매 lower + upper MF."""
|
||||
def __init__(self, lower_params, upper_params):
|
||||
self.lower = triangular_mf(lower_params)
|
||||
self.upper = triangular_mf(upper_params)
|
||||
|
||||
def membership(self, x):
|
||||
return (self.lower(x), self.upper(x))
|
||||
```
|
||||
|
||||
### Hybrid neuro-fuzzy (ANFIS)
|
||||
```python
|
||||
class ANFIS(torch.nn.Module):
|
||||
def __init__(self, n_inputs, n_rules):
|
||||
super().__init__()
|
||||
self.mu = torch.nn.Parameter(torch.randn(n_rules, n_inputs))
|
||||
self.sigma = torch.nn.Parameter(torch.ones(n_rules, n_inputs))
|
||||
self.consequents = torch.nn.Linear(n_inputs + 1, n_rules)
|
||||
|
||||
def forward(self, x):
|
||||
# 매 layer 1: gaussian membership
|
||||
memberships = torch.exp(-((x.unsqueeze(1) - self.mu) ** 2) / (2 * self.sigma ** 2))
|
||||
# 매 layer 2: rule firing strength (product)
|
||||
firing = memberships.prod(dim=-1)
|
||||
# 매 layer 3: normalize
|
||||
weights = firing / firing.sum(dim=-1, keepdim=True)
|
||||
# 매 layer 4: consequent
|
||||
x_aug = torch.cat([x, torch.ones(x.shape[0], 1)], dim=-1)
|
||||
outputs = self.consequents(x_aug)
|
||||
# 매 layer 5: weighted sum
|
||||
return (weights * outputs).sum(dim=-1)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Use |
|
||||
|---|---|
|
||||
| Linguistic rule control | Mamdani |
|
||||
| Crisp output | Sugeno |
|
||||
| Game AI | Lightweight fuzzy |
|
||||
| Modern data-rich | NN (replace) |
|
||||
| Hybrid | ANFIS |
|
||||
| Uncertainty in MF | Type-2 |
|
||||
|
||||
**기본값**: 매 control / expert = scikit-fuzzy Mamdani + 매 ML alternative 의 explore. 매 explainable AI = fuzzy 의 still 매 useful.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[AI]] · [[Control-Theory]] · [[Soft-Computing]]
|
||||
- 변형: [[Mamdani]] · [[Sugeno]] · [[ANFIS]]
|
||||
- 응용: [[Game-AI]] · [[Expert-System]] · [[Controller-Design]]
|
||||
- Adjacent: [[Cybernetics]] · [[PID-Controller]] · [[Probabilistic-Logic]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 explainable rule. 매 simple control. 매 educational.
|
||||
**언제 X**: 매 high-dim ML. 매 rich data.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Too many rules**: 매 explosion.
|
||||
- **No defuzz choice**: 매 default 의 wrong.
|
||||
- **Membership 의 arbitrary**: 매 expert tune 의 X.
|
||||
- **Fuzzy where ML wins**: 매 obsolete.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Zadeh 1965, scikit-fuzzy docs).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-04-26 | FUZZY auto |
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Mamdani / Sugeno + 매 scikit-fuzzy / ANFIS / defuzz code |
|
||||
|
||||
Reference in New Issue
Block a user