-
Population create
import random from ch3.selection_tournament import selection_tournament from ch3.individual import Individual # 초기 설정 POPULATION_SIZE = 5 # 유전 알고리즘 흐름 random.seed(18) # 첫 번째 개체군 생성 population = Individual.create_random_population(POPULATION_SIZE) # 선택 selected = selection_tournament(population, group_size=3) # 결과 출력 print(f"Population: {population}") print(f"Selected: {selected}")
-
ch3
-
selection_tournament
import random def selection_tournament(population, group_size): selected = [] for _ in range(len(population)): candidates = [random.choice(population) for _ in range(group_size)] selected.append(max(candidates, key = lambda ind: ind.fitness)) return selected
-
-
-
Visualization
import random import pandas as pd import matplotlib.pyplot as plt from ch3.individual import Individual # 개체군 크기 POPULATION_SIZE = 10 # 서브그룹 크기? TOURNAMENT_SIZE = 3 # 개체군 생성 population = Individual.create_random_population(POPULATION_SIZE) # 토너먼트 후보 선택 candidates = [random.choice(population) for _ in range(TOURNAMENT_SIZE)] # 후보 중 최고 개체 선택 best = [max(candidates, key=lambda ind: ind.fitness)] # 개체 시각화 함수 def plot_individuals(individual_set): df = pd.DataFrame({ 'name': [ind.name for ind in individual_set], 'fitness': [ind.fitness for ind in individual_set] }) df.plot.bar(x='name', y='fitness', rot=0) plt.show() # 개체군, 후보군, 최고 개체 시각화 plot_individuals(population) plot_individuals(candidates) plot_individuals(best)
-
Pros, Cons
장점 단점 직관적이고 구현이 쉬움 크기를 잘못 설정하면 다양성이 감소 선택 압력 조절 용이 무작위성으로 인한 편향 발생 가능 병렬 프로세싱 가능 매개변수 설정에 민감 피트니스 값에 둔감 조기 수렴 방지 가능