feat(ga): tournament selection + elitism
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
|
||||
from ..genome.hypothesis import HypothesisAgentGenome
|
||||
|
||||
|
||||
def tournament_select(
|
||||
population: list[HypothesisAgentGenome],
|
||||
fitnesses: dict[str, float],
|
||||
k: int,
|
||||
rng: random.Random,
|
||||
) -> HypothesisAgentGenome:
|
||||
"""Estrae k individui random e restituisce il migliore."""
|
||||
if k < 1:
|
||||
raise ValueError("k must be >= 1")
|
||||
if not population:
|
||||
raise ValueError("empty population")
|
||||
candidates = rng.sample(population, k=min(k, len(population)))
|
||||
return max(candidates, key=lambda g: fitnesses.get(g.id, 0.0))
|
||||
|
||||
|
||||
def elite_select(
|
||||
population: list[HypothesisAgentGenome],
|
||||
fitnesses: dict[str, float],
|
||||
k: int,
|
||||
) -> list[HypothesisAgentGenome]:
|
||||
"""Restituisce i k genomi con fitness più alta."""
|
||||
sorted_pop = sorted(population, key=lambda g: fitnesses.get(g.id, 0.0), reverse=True)
|
||||
return sorted_pop[:k]
|
||||
Reference in New Issue
Block a user