Критерий остановки по дисперсии фитнеса
This commit is contained in:
26
lab1/gen.py
26
lab1/gen.py
@@ -145,6 +145,9 @@ class GARunConfig:
|
||||
None # индексы поколений для сохранения графиков
|
||||
)
|
||||
results_dir: str = "results" # папка для сохранения графиков
|
||||
variance_threshold: float | None = (
|
||||
None # порог дисперсии для остановки (если None - не используется)
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -194,6 +197,27 @@ def genetic_algorithm(
|
||||
history_populations_x.append(xs[:])
|
||||
history_populations_f.append(fits[:])
|
||||
|
||||
# Проверка критерия остановки по дисперсии
|
||||
if config.variance_threshold is not None:
|
||||
fitness_variance = np.var(fits)
|
||||
if fitness_variance < config.variance_threshold:
|
||||
print(
|
||||
f"Остановка на поколении {generation}: дисперсия {fitness_variance:.6f} < {config.variance_threshold}"
|
||||
)
|
||||
# Сохраняем график последнего поколения
|
||||
if config.save_generations:
|
||||
plot_generation_snapshot(
|
||||
history_best_x,
|
||||
history_best_f,
|
||||
history_populations_x,
|
||||
history_populations_f,
|
||||
generation,
|
||||
config.x_min,
|
||||
config.x_max,
|
||||
config.results_dir,
|
||||
)
|
||||
break
|
||||
|
||||
# Сохранение графика для указанных поколений
|
||||
if config.save_generations and generation in config.save_generations:
|
||||
plot_generation_snapshot(
|
||||
@@ -224,7 +248,7 @@ def genetic_algorithm(
|
||||
return GARunResult(
|
||||
best_x,
|
||||
best_f,
|
||||
config.max_generations,
|
||||
len(history_best_x), # реальное количество поколений
|
||||
history_best_x,
|
||||
history_best_f,
|
||||
history_populations_x,
|
||||
|
||||
Reference in New Issue
Block a user