---
id: wiki-2026-0508-fuzzy-logic
title: Fuzzy Logic
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [fuzzy logic, fuzzy set, Zadeh, fuzzy controller, Mamdani, Sugeno]
duplicate_of: none
source_trust_level: A
confidence_score: 0.95
verification_status: applied
tags: [fuzzy-logic, control, ai, expert-system, soft-computing, zadeh]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
  language: Python
  framework: scikit-fuzzy / FuzzyLite
---

# Fuzzy Logic

## 매 한 줄
> **"매 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.

## 매 핵심

### 매 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**.

### 매 inference
- **Mamdani**: 매 fuzzy output → 매 defuzzify.
- **Sugeno**: 매 crisp output (linear).
- **Tsukamoto**: 매 monotonic.

### 매 응용
1. **Controller**: 매 washing machine, AC, brake.
2. **Game AI**: 매 NPC behavior.
3. **Expert system**: 매 medical diagnostic.
4. **Image processing**: 매 edge detect.
5. **Risk assessment**.

## 💻 패턴

### Fuzzy set (membership)
```python
import numpy as np

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)

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)

def gaussian(x, mu, sigma):
    return np.exp(-((x - mu) ** 2) / (2 * sigma ** 2))
```

### scikit-fuzzy
```python
import skfuzzy as fuzz
import skfuzzy.control as ctrl

# 매 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')

# 매 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]]
- 변형: [[Mamdani]] · [[Sugeno]]
- Adjacent: [[Cybernetics Foundations|Cybernetics]] · [[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 |
