# อัลกอริทึมวิวัฒนาการ (Evolutionary Algorithms) **ผู้จัดทำ:** อรรถพล คงหวาน --- # สารบัญ (Outline) 1. บทนำ: วิวัฒนาการในโลกของอัลกอริทึม 2. Genetic Algorithms (อัลกอริทึมพันธุกรรม) 3. Genetic Programming (โปรแกรมพันธุกรรม) 4. Evolution Strategies (กลยุทธ์วิวัฒนาการ) 5. Swarm Intelligence (ความฉลาดของฝูง) 6. การเปรียบเทียบอัลกอริทึม 7. การประยุกต์ใช้ในงานจริง 8. Parameter Tuning และการออกแบบ EA ที่ดี 9. สรุป --- # บทที่ 1 ## บทนำ: วิวัฒนาการในโลกของอัลกอริทึม --- ## Evolutionary Algorithms คืออะไร? - **Evolutionary Algorithms (EA)** คือกลุ่มอัลกอริทึมที่ได้รับแรงบันดาลใจจากกระบวนการวิวัฒนาการตามธรรมชาติ - อิงทฤษฎีของ **Charles Darwin** — หลักการ "Survival of the Fittest" - แนวคิดหลัก: ค้นหา **Optimal Solution** สำหรับปัญหาซับซ้อน - จำลองกระบวนการวิวัฒนาการผ่าน **Population of Candidates** - แต่ละรุ่น (Generation) มีการปรับตัวให้ดีขึ้นเรื่อยๆ --- ## ประวัติและวิวัฒนาการของสาขา ```mermaid %%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#282828', 'primaryTextColor': '#ebdbb2', 'primaryBorderColor': '#fabd2f', 'lineColor': '#83a598', 'secondaryColor': '#3c3836', 'tertiaryColor': '#504945'}}}%% flowchart TD subgraph era1["🕰️ ยุคบุกเบิก (1950s-1960s)"] A1["1954: Nils Barricelli - Numerical Evolution"] A2["1962: John Holland - Adaptive Systems"] A3["1964: Ingo Rechenberg - Evolution Strategies"] end subgraph era2["🔬 ยุคพัฒนา (1970s-1980s)"] B1["1975: John Holland - Adaptation in Natural and Artificial Systems"] B2["1975: David Fogel - Evolutionary Programming"] B3["1989: David Goldberg - Genetic Algorithms"] end subgraph era3["🌐 ยุครุ่งเรือง (1990s-2000s)"] C1["1992: John Koza - Genetic Programming"] C2["1995: Kennedy & Eberhart - PSO"] C3["1999: Marco Dorigo - ACO"] end subgraph era4["🚀 ยุคปัจจุบัน (2010s-Now)"] D1["2012: DEAP Library"] D2["2017+: Neuroevolution / NEAT / CMA-ES"] D3["2020+: EA in AutoML / NAS"] end era1 --> era2 --> era3 --> era4 style era1 fill:#3c3836,stroke:#fabd2f,color:#ebdbb2 style era2 fill:#3c3836,stroke:#b8bb26,color:#ebdbb2 style era3 fill:#3c3836,stroke:#83a598,color:#ebdbb2 style era4 fill:#3c3836,stroke:#d3869b,color:#ebdbb2 ``` --- ## ภาพรวมของ Evolutionary Computation ```mermaid %%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#282828', 'primaryTextColor': '#ebdbb2', 'primaryBorderColor': '#fabd2f', 'lineColor': '#83a598', 'secondaryColor': '#3c3836'}}}%% mindmap root((Evolutionary Computation)) GA[Genetic Algorithms] Binary Encoding Real-valued Encoding Selection / Crossover / Mutation GP[Genetic Programming] Tree Representation Symbolic Regression ES[Evolution Strategies] CMA-ES Self-adaptation SI[Swarm Intelligence] PSO Particle Swarm ACO Ant Colony ``` --- # บทที่ 2 ## Genetic Algorithms (อัลกอริทึมพันธุกรรม) --- ## GA คืออะไร? - **Genetic Algorithm (GA)** คืออัลกอริทึมการค้นหาและปรับแต่ง (Search & Optimization) - จำลองกระบวนการคัดเลือกตามธรรมชาติ - ทำงานกับประชากรของ **Chromosome** ซึ่งแต่ละตัวแทน Candidate Solution - องค์ประกอบหลัก: **Encoding → Fitness → Selection → Crossover → Mutation** --- ## วงจรชีวิตของ Genetic Algorithm ```mermaid %%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#282828', 'primaryTextColor': '#ebdbb2', 'primaryBorderColor': '#fabd2f', 'lineColor': '#83a598', 'secondaryColor': '#3c3836'}}}%% flowchart TD A(["🧬 Initialization - สร้างประชากรเริ่มต้น"]) B["📊 Fitness Evaluation - คำนวณค่า Fitness"] C{{"🏁 Termination Condition?"}} D["🎯 Selection - Roulette / Tournament"] E["✂️ Crossover - แลกเปลี่ยนยีน"] F["🔀 Mutation - เปลี่ยน Gene แบบสุ่ม"] G["👥 New Generation - แทนที่ประชากรเก่า"] H(["✅ Best Solution"]) A --> B --> C C -- "ยังไม่หยุด" --> D C -- "หยุด" --> H D --> E --> F --> G --> B style A fill:#98971a,stroke:#b8bb26,color:#282828 style H fill:#98971a,stroke:#b8bb26,color:#282828 style C fill:#cc241d,stroke:#fb4934,color:#ebdbb2 style B fill:#458588,stroke:#83a598,color:#ebdbb2 style D fill:#d65d0e,stroke:#fe8019,color:#282828 style E fill:#b16286,stroke:#d3869b,color:#ebdbb2 style F fill:#689d6a,stroke:#8ec07c,color:#282828 style G fill:#3c3836,stroke:#fabd2f,color:#ebdbb2 ``` --- ## การเข้ารหัส (Encoding) — Binary & Real-valued **Binary Encoding** — ตัวอย่าง Knapsack (5 ชิ้น): ``` Chromosome: [1, 0, 1, 1, 0] ความหมาย: ใส่ชิ้นที่ 1, 3, 4 ไม่ใส่ชิ้นที่ 2, 5 ``` **Real-valued Encoding** — ตัวอย่าง Neural Network weights: ``` Chromosome: [0.42, -1.73, 2.15, 0.89, -0.31] w₁ w₂ w₃ w₄ bias ``` --- ## ประเภทการเข้ารหัส (Encoding Types) | การเข้ารหัส | ข้อดี | ข้อเสีย | เหมาะกับปัญหา | |---|---|---|---| | **Binary** | ง่าย, เป็นมาตรฐาน | ต้องการบิตมากสำหรับความแม่นยำสูง | Combinatorial, 0/1 | | **Real-valued** | ความแม่นยำสูง | Mutation ต้องออกแบบดี | Continuous | | **Permutation** | เหมาะกับการจัดลำดับ | Crossover ซับซ้อน | TSP, Scheduling | | **Tree** | ยืดหยุ่น, แทน Programs | ขนาดไม่แน่นอน | Genetic Programming | --- ## Fitness Function — ปัญหา Knapsack **สมการ Fitness:**
f
(
x
)
=
∑
i
=
1
n
v
i
x
i
ถ้า
∑
i
=
1
n
w
i
x
i
≤
W
0
ถ้าน้ำหนักเกิน
- **vᵢ** = มูลค่าสินค้าชิ้นที่ i **xᵢ** ∈ {0,1} = ตัวแปรตัดสินใจ - **wᵢ** = น้ำหนักสินค้าชิ้นที่ i **W** = ความจุสูงสุด --- ## Roulette Wheel Selection **สมการความน่าจะเป็น:**
P
i
=
f
(
x
i
)
∑
j
=
1
N
f
(
x
j
)
| Chromosome | Fitness | โอกาส (%) | |---|---|---| | [1,0,1,1,0] | 27,000 | **40.3%** | | [0,1,0,1,1] | 25,000 | **37.3%** | | [1,0,0,1,0] | 7,000 | **10.4%** | | [0,0,1,1,0] | 8,000 | **11.9%** | --- ## Tournament Selection - สุ่มเลือก **k ตัว** มาแข่งขัน แล้วเลือกตัวที่ดีที่สุด ``` Tournament Size k=3: 1. สุ่มเลือก: [1,0,1,1,0], [0,0,1,1,0], [0,1,0,1,1] 2. เปรียบ Fitness: 27,000 vs 8,000 vs 25,000 3. ผู้ชนะ: [1,0,1,1,0] (Fitness = 27,000) ``` --- ## Crossover (การผสมข้าม) **Single-Point Crossover:** ``` Parent 1: [1, 0, 1 | 1, 0] Child 1: [1, 0, 1 | 1, 1] Parent 2: [0, 1, 0 | 1, 1] Child 2: [0, 1, 0 | 1, 0] ``` **Two-Point Crossover:** ``` Parent 1: [1 | 0, 1, 1 | 0] Child 1: [1 | 1, 0, 1 | 0] Parent 2: [0 | 1, 0, 1 | 1] Child 2: [0 | 0, 1, 1 | 1] ``` **Uniform Crossover:** ``` Mask: [1, 0, 1, 0, 1] Child 1: [1, 1, 1, 1, 1] ← mask=1: ใช้ P1, mask=0: ใช้ P2 ``` --- ## Mutation (การกลายพันธุ์) **สมการอัตรา Mutation (John Holland):**
P
m
=
1
L
**Bit-flip Mutation (Binary):** ``` ก่อน: [1, 0, 1, 1, 0] → หลัง: [1, 0, 1, 0, 0] (bit 4 flip) ``` **Gaussian Mutation (Real-valued):** ``` ก่อน: [0.42, -1.73, 2.15] หลัง: [0.42, -1.73+N(0,σ), 2.15] = [0.42, -1.51, 2.15] ``` --- ## ตัวอย่างโค้ด GA — Knapsack ด้วย DEAP (1/2) ```python from deap import algorithms, base, creator, tools import random, numpy as np ITEMS = { 'มือถือ': {'weight': 1, 'value': 5000}, 'แล็ปท็อป': {'weight': 4, 'value': 20000}, 'กล้อง': {'weight': 3, 'value': 12000}, 'หนังสือ': {'weight': 1, 'value': 2000}, } MAX_WEIGHT = 6 def evaluate_knapsack(individual): total_w = sum(w*x for w,x in zip(WEIGHTS, individual)) total_v = sum(v*x for v,x in zip(VALUES, individual)) if total_w > MAX_WEIGHT: return (max(0, total_v - (total_w-MAX_WEIGHT)*10000),) return (total_v,) ``` --- ## ตัวอย่างโค้ด GA — Knapsack ด้วย DEAP (2/2) ```python creator.create("FitnessMax", base.Fitness, weights=(1.0,)) creator.create("Individual", list, fitness=creator.FitnessMax) toolbox = base.Toolbox() toolbox.register("attr_bool", random.randint, 0, 1) toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, n=N_ITEMS) toolbox.register("population", tools.initRepeat, list, toolbox.individual) toolbox.register("evaluate", evaluate_knapsack) toolbox.register("mate", tools.cxTwoPoint) toolbox.register("mutate", tools.mutFlipBit, indpb=1/N_ITEMS) toolbox.register("select", tools.selTournament, tournsize=3) best, log = algorithms.eaSimple(population, toolbox, cxpb=0.8, mutpb=0.2, ngen=50, ...) ``` --- # บทที่ 3 ## Genetic Programming (โปรแกรมพันธุกรรม) --- ## GP คืออะไร? - **Genetic Programming (GP)** เป็นส่วนขยายของ GA - วิวัฒนาการ **โปรแกรมหรือสูตรคณิตศาสตร์** แทนที่จะเป็นค่าพารามิเตอร์ - Chromosome ถูกแทนด้วย **Tree Structure** - เหมาะกับงาน **Symbolic Regression** — ค้นหาสูตรที่ fit กับข้อมูล - พัฒนาโดย **John Koza** (1992) --- ## โครงสร้าง Tree ใน GP ```mermaid %%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#282828', 'primaryTextColor': '#ebdbb2', 'primaryBorderColor': '#fabd2f', 'lineColor': '#83a598', 'secondaryColor': '#3c3836'}}}%% graph TD R(["➕ +"]) A(["✖️ *"]) B(["➗ /"]) C(["x"]) D(["2.5"]) E(["sin"]) F(["y"]) R --> A R --> B A --> C A --> D B --> E B --> F E --> F style R fill:#cc241d,stroke:#fb4934,color:#ebdbb2 style A fill:#d65d0e,stroke:#fe8019,color:#282828 style B fill:#d65d0e,stroke:#fe8019,color:#282828 style C fill:#458588,stroke:#83a598,color:#ebdbb2 style D fill:#458588,stroke:#83a598,color:#ebdbb2 style E fill:#689d6a,stroke:#8ec07c,color:#282828 style F fill:#458588,stroke:#83a598,color:#ebdbb2 ``` --- ## สมการที่ Tree แทน **Tree แสดงสมการ:**
f
(
x
,
y
)
=
(
x
×
2.5
)
+
sin
(
y
)
y
- **Internal nodes** = Operators (+, -, ×, ÷, sin, cos, ...) - **Leaf nodes** = Variables (x, y) หรือ Constants (2.5) - GP วิวัฒนาการ Tree นี้ผ่าน Crossover และ Mutation --- ## ตัวอย่างโค้ด GP — Symbolic Regression ```python import operator from deap import gp # กำหนด Primitive Set pset = gp.PrimitiveSet("MAIN", arity=1) pset.addPrimitive(operator.add, 2) pset.addPrimitive(operator.sub, 2) pset.addPrimitive(operator.mul, 2) pset.addPrimitive(protected_div, 2) pset.renameArguments(ARG0='x') # Fitness: ค่าเป้าหมาย f(x) = x² + x - 6 def evaluate_gp(individual): func = toolbox.compile(expr=individual) y_pred = np.array([func(x) for x in X_data]) mse = np.mean((y_pred - y_data)**2) return (mse,) ``` --- # บทที่ 4 ## Evolution Strategies (กลยุทธ์วิวัฒนาการ) --- ## Evolution Strategies คืออะไร? - พัฒนาโดย **Ingo Rechenberg** และ **Hans-Paul Schwefel** (TU Berlin, 1960-70s) - ออกแบบมาสำหรับ **Continuous Optimization** โดยเฉพาะ - ใช้ **Real-valued vectors** แทน Solution - มี 2 กลยุทธ์หลัก: **(μ + λ)** และ **(μ, λ)** --- ## กลยุทธ์ (μ, λ) และ (μ + λ)
Strategy (μ + λ):
P
t
+
1
=
select_best
(
μ
,
P
t
∪
O
t
)
Strategy (μ, λ):
P
t
+
1
=
select_best
(
μ
,
O
t
)
- **μ** = จำนวนพ่อแม่ (Parents) - **λ** = จำนวนลูกหลาน (Offspring) โดยทั่วไป λ ≥ μ - **(μ + λ)** คัดเลือกจากพ่อแม่ + ลูกหลาน - **(μ, λ)** คัดเลือกจากลูกหลานเท่านั้น --- ## CMA-ES (Covariance Matrix Adaptation ES) **สมการการสร้าง Offspring:**
x
k
~
m
+
σ
·
N
0
(
0
,
C
)
,
k
=
1
,
...
,
λ
- **m** = mean vector (จุดศูนย์กลาง) - **σ** = step-size (ขนาดก้าว) - **C** = Covariance Matrix (เรียนรู้รูปร่างของ Fitness Landscape) - เป็นหนึ่งใน ES ที่**ทรงพลังที่สุด**สำหรับ Black-box Optimization --- ## ตัวอย่างโค้ด CMA-ES ด้วย DEAP ```python from deap import cma, algorithms, base, creator, tools N_DIM = 10 def sphere_function(individual): return (sum(x**2 for x in individual),) creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) creator.create("Individual", list, fitness=creator.FitnessMin) centroid = [5.0] * N_DIM # จุดเริ่มต้นห่างจาก optimal sigma = 3.0 # step-size เริ่มต้น strategy = cma.Strategy(centroid=centroid, sigma=sigma, lambda_=20) toolbox.register("generate", strategy.generate, creator.Individual) toolbox.register("update", strategy.update) toolbox.register("evaluate", sphere_function) ``` --- # บทที่ 5 ## Swarm Intelligence (ความฉลาดของฝูง) --- ## Swarm Intelligence คืออะไร? - ได้รับแรงบันดาลใจจาก **พฤติกรรมรวมกลุ่ม** ของสิ่งมีชีวิต - ตัวอย่าง: ฝูงนก, ฝูงปลา, อาณาจักรมด - แต่ละตัวมีพฤติกรรมง่ายๆ แต่รวมกันสร้างพฤติกรรมที่ฉลาดซับซ้อน - อัลกอริทึมหลัก: **PSO** (Particle Swarm) และ **ACO** (Ant Colony) --- ## Particle Swarm Optimization (PSO) - พัฒนาโดย **Kennedy & Eberhart** (1995) - จำลองพฤติกรรมฝูงนกที่ค้นหาอาหาร - แต่ละ **Particle** แทนคำตอบที่เป็นไปได้ - เรียนรู้จาก 2 แหล่ง: **pbest** (ประสบการณ์ส่วนตัว) และ **gbest** (ประสบการณ์ฝูง) --- ## สมการการเคลื่อนที่ของ Particle **อัปเดต Velocity:**
v
i
,
d
←
ω
v
i
,
d
+
c
1
r
1
(
p
i
best
-
x
i
,
d
)
+
c
2
r
2
(
g
best
-
x
i
,
d
)
**อัปเดต Position:**
x
i
,
d
←
x
i
,
d
+
v
i
,
d
- **ω** = inertia weight (0.4-0.9) **c₁, c₂** = 2.0 --- ## ตัวอย่างการคำนวณ PSO (1 Iteration) **ปัญหา:** minimize f(x) = (x-2)² ค่าต่ำสุด x=2 | Particle | x₀ | v₀ | pbest | f(x) | |---|---|---|---|---| | P1 | 0.0 | 1.0 | 0.0 | 4.0 | | P2 | 5.0 | -1.5 | 5.0 | 9.0 | **gbest = P1 = 0.0** (ω=0.7, c1=c2=2.0, r1=0.6, r2=0.4) - P1: v₁ = **0.7** → x₁ = **0.7** → f(0.7)=1.69 → pbest₁=0.7 - P2: v₂ = **-5.05** → x₂ = **-0.05** → f(-0.05)=4.20 → pbest₂=-0.05 --- ## Ant Colony Optimization (ACO) ```mermaid %%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#282828', 'primaryTextColor': '#ebdbb2', 'primaryBorderColor': '#fabd2f', 'lineColor': '#fabd2f', 'secondaryColor': '#3c3836'}}}%% flowchart LR A(["🐜 มดออกจากรัง"]) B["🔀 เลือกเส้นทาง ตาม Pheromone + Heuristic"] C["🏁 ถึงอาหาร"] D["💧 วาง Pheromone"] E["⬇️ Pheromone ระเหย τ ← (1-ρ)τ"] F{"🔄 รอบถัดไป?"} G(["✅ เส้นทางที่ดีที่สุด"]) A --> B --> C --> D --> E --> F F -- "ยังไม่ครบ" --> A F -- "ครบแล้ว" --> G style A fill:#689d6a,stroke:#8ec07c,color:#282828 style C fill:#458588,stroke:#83a598,color:#ebdbb2 style D fill:#b16286,stroke:#d3869b,color:#ebdbb2 style E fill:#cc241d,stroke:#fb4934,color:#ebdbb2 style G fill:#98971a,stroke:#b8bb26,color:#282828 ``` --- ## สมการ ACO — Probability Rule & Evaporation **Probability Rule:**
P
i
,
j
=
τ
i
,
j
α
·
η
i
,
j
β
∑
k
∈
allowed
τ
i
,
k
α
·
η
i
,
k
β
**Evaporation:**
τ
i
,
j
←
(
1
-
ρ
)
τ
i
,
j
+
Δ
τ
i
,
j
- **τᵢⱼ** = Pheromone **ηᵢⱼ** = Heuristic (1/distance) - **α, β** = น้ำหนัก **ρ** = Evaporation Rate ∈ [0,1] --- ## ตัวอย่างโค้ด PSO — Rastrigin Function ```python class PSO: def __init__(self, func, n_particles=30, n_dims=2, bounds=(-5.12, 5.12), omega=0.729, c1=1.494, c2=1.494, max_iter=100): self.pos = np.random.uniform(*bounds, (n_particles, n_dims)) self.vel = np.random.uniform(-1, 1, (n_particles, n_dims)) self.pbest = self.pos.copy() def optimize(self): for _ in range(self.max_iter): r1, r2 = np.random.rand(...), np.random.rand(...) cognitive = self.c1 * r1 * (self.pbest - self.pos) social = self.c2 * r2 * (self.gbest - self.pos) self.vel = self.omega * self.vel + cognitive + social self.pos = np.clip(self.pos + self.vel, *self.bounds) ``` --- # บทที่ 6 ## การเปรียบเทียบอัลกอริทึม --- ## Algorithm Comparison Table | คุณสมบัติ | GA | ES | GP | PSO | ACO | |---|---|---|---|---|---| | **Solution** | Binary/Real | Real Vector | Tree | Real Vector | Path | | **ปัญหา** | Discrete/Continuous | Continuous | Symbolic | Continuous | Combinatorial | | **จุดเด่น** | ยืดหยุ่นสูง | เก่ง Continuous | ค้นพบโครงสร้าง | รวดเร็ว | เหมาะ Network | | **จุดด้อย** | ต้องออกแบบ Encoding | เฉพาะ Real-valued | Tree ขยายใหญ่ | ติด Local | Convergence ช้า | | **Library** | DEAP, PyGAD | DEAP, CMA | DEAP | pyswarms | ACOpy | --- ## No Free Lunch Theorem > **"ไม่มีอัลกอริทึมใดดีที่สุดสำหรับทุกปัญหา"** > — Wolpert & Macready (1997) - ค่าเฉลี่ยประสิทธิภาพบนปัญหาทุกชนิด **จะเท่ากัน** สำหรับทุก algorithm - **ผลกระทบในทางปฏิบัติ:** ต้องทดสอบหลาย algorithm - เลือกตามลักษณะเฉพาะของปัญหา --- # บทที่ 7 ## การประยุกต์ใช้ EA ในงานจริง --- ## การประยุกต์ใช้ Evolutionary Algorithms ```mermaid %%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#282828', 'primaryTextColor': '#ebdbb2', 'primaryBorderColor': '#fabd2f', 'lineColor': '#83a598', 'secondaryColor': '#3c3836'}}}%% graph LR EA(["🧬 Evolutionary Algorithms"]) subgraph eng["⚙️ วิศวกรรม"] E1["Structural Optimization"] E2["Antenna Design"] E3["Circuit Design"] end subgraph ml["🤖 Machine Learning"] M1["Hyperparameter Tuning"] M2["Feature Selection"] M3["Neural Architecture Search"] end subgraph sched["📅 การจัดการ"] S1["Job Scheduling"] S2["Vehicle Routing"] S3["Resource Allocation"] end subgraph game["🎮 เกมและ AI"] G1["Game AI"] G2["Neuroevolution"] G3["Procedural Content Generation"] end EA --> eng EA --> ml EA --> sched EA --> game style EA fill:#cc241d,stroke:#fb4934,color:#ebdbb2 style eng fill:#3c3836,stroke:#fabd2f,color:#ebdbb2 style ml fill:#3c3836,stroke:#83a598,color:#ebdbb2 style sched fill:#3c3836,stroke:#b8bb26,color:#ebdbb2 style game fill:#3c3836,stroke:#d3869b,color:#ebdbb2 ``` --- ## Hyperparameter Tuning ด้วย GA (1/2) ```python from sklearn.svm import SVC from sklearn.model_selection import cross_val_score # Hyperparameter Space: [C_log, gamma_log] PARAM_RANGES = { 'C_log': (-3.0, 3.0), # log10(C) 'gamma_log': (-4.0, 1.0), # log10(gamma) } def evaluate_svm(individual): C_log, gamma_log = individual C, gamma = 10**C_log, 10**gamma_log clf = SVC(C=C, gamma=gamma, kernel='rbf') scores = cross_val_score(clf, X_scaled, y, cv=cv, scoring='accuracy') return (scores.mean(),) ``` --- ## Hyperparameter Tuning ด้วย GA (2/2) ```python toolbox.register("mate", tools.cxBlend, alpha=0.5) toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=0.5, indpb=0.5) toolbox.register("select", tools.selTournament, tournsize=3) best_params, log = run_ga_hpo(n_gen=20, pop_size=30) # ผลลัพธ์: # Best C : 12.5432 # Best gamma : 0.001234 # CV Accuracy: 98.24% # Default SVC Accuracy: 96.50% # การปรับปรุง: +1.74% ``` --- # บทที่ 8 ## Parameter Tuning และการออกแบบ EA ที่ดี --- ## พารามิเตอร์สำคัญของ GA | พารามิเตอร์ | ค่าแนะนำ | ผลเมื่อมากเกิน | ผลเมื่อน้อยเกิน | |---|---|---|---| | **Population Size** | 50-200 | Computation สูง | Diversity ต่ำ | | **Crossover Rate** | 0.7-0.9 | สูญเสียข้อมูลดี | วิวัฒนาการช้า | | **Mutation Rate** | 1/L – 0.1 | Search แบบ Random | ติด Local optima | | **Tournament Size** | 2-5 | Selection pressure สูง | Weak selection | | **Generations** | 100-1000 | Overcompute | ไม่ converge | --- ## ปัญหาที่พบบ่อยและวิธีแก้ **Premature Convergence (หยุดก่อนเวลา):** - เพิ่ม Mutation Rate - ใช้ Diversity Maintenance (Niching, Crowding) - เพิ่มขนาด Population **Slow Convergence (ช้าเกินไป):** - เพิ่ม Selection Pressure (Tournament Size ใหญ่ขึ้น) - ใช้ **Elitism** (เก็บตัวที่ดีที่สุดไว้เสมอ) --- ## Schema Theorem (ทฤษฎีโครงร่าง)
m
(
H
,
t
+
1
)
≥
m
(
H
,
t
)
·
f
(
H
)
f
¯
·
[
1
-
p
c
δ
(
H
)
L
-
1
-
o
(
H
)
p
m
]
- **m(H,t)** = จำนวน instances ของ Schema H ในรุ่น t - **f(H)/f̄** = อัตราส่วน Fitness ของ Schema ต่อ Fitness เฉลี่ย - **δ(H)** = defining length **o(H)** = order (fixed bits) --- # บทที่ 9 ## สรุป --- ## สรุปภาพรวม Evolutionary Algorithms - **GA** — Discrete Optimization: Encoding → Fitness → Selection → Crossover → Mutation - **Genetic Programming** — วิวัฒนาโปรแกรมผ่าน Tree สำหรับ Symbolic Regression - **CMA-ES** — ตัวเลือกแรกสำหรับ Continuous Black-box Optimization - **PSO** — เรียบง่าย รวดเร็ว Parameters น้อย เหมาะ Continuous มิติสูง - **ACO** — เหมาะกับปัญหา Graph/Network (TSP, VRP) - **No Free Lunch** — ต้องทดสอบหลาย algorithm ตามลักษณะปัญหา --- ## คู่มือการเลือก Algorithm ``` ปัญหา → Algorithm ที่แนะนำ ────────────────────────────────────────────── Discrete (0/1) → Genetic Algorithm (DEAP) Continuous, smooth → CMA-ES หรือ PSO Graph / Path / Route → ACO สูตรคณิตศาสตร์ → Genetic Programming Hyperparameter tuning → GA หรือ CMA-ES Multi-objective → NSGA-II (DEAP) ``` --- ## เอกสารอ้างอิง 1. Holland, J.H. (1975). *Adaptation in Natural and Artificial Systems*. U-Michigan Press. 2. Goldberg, D.E. (1989). *Genetic Algorithms in Search, Optimization, and ML*. Addison-Wesley. 3. Koza, J.R. (1992). *Genetic Programming*. MIT Press. 4. Kennedy, J. & Eberhart, R. (1995). Particle swarm optimization. *ICNN'95*. 5. Dorigo, M. & Stützle, T. (2004). *Ant Colony Optimization*. MIT Press. 6. Hansen, N. (2006). The CMA Evolution Strategy: A Comparing Review. 7. Wolpert & Macready (1997). No free lunch theorems. *IEEE Trans. Evol. Comp.* 8. Fortin et al. (2012). DEAP: Evolutionary Algorithms Made Easy. *JMLR*. --- # คำถาม - ข้อสงสัย