import numpy as np
def calculate_fitness(solution):
return np.array(solution).dot(parameters)
parameters = np.array([4,-2,3.5,5,-11,-4.7])
## initializae solution pool
current_solution_pool = [list(np.random.normal(0, 1, 6)) for i in range(0, 8)]
for i in range(0, 10):
## 현재 솔루션 중에서 가장 성과가 좋은 놈만 남기고 모두 버림
new_parents = sorted(current_solution_pool, key=calculate_fitness, reverse=True)[:4]
print(f"optimal fitness in {i:0>2d} generation: {calculate_fitness(new_parents[0])}")
## 간단하게 크로스오버 세팅
crossovers = [
new_parents[0][:3]+new_parents[1][3:],
new_parents[1][:3]+new_parents[0][3:],
]
## 뮤테이션 세팅
mutations = [
list(np.array(new_parents[0])+np.random.normal(0, 1, 6)),
list(np.array(new_parents[0])+np.random.normal(0, 1, 6)),
]
current_solution_pool = new_parents + crossovers + mutations
optimal fitness in 00 generation: 16.114142824605693
optimal fitness in 01 generation: 20.34874446758479
optimal fitness in 02 generation: 20.34874446758479
optimal fitness in 03 generation: 28.49241685227758
optimal fitness in 04 generation: 30.992930681221885
optimal fitness in 05 generation: 33.93284270330889
optimal fitness in 06 generation: 33.93284270330889
optimal fitness in 07 generation: 51.41840381571125
optimal fitness in 08 generation: 69.02581331815482
optimal fitness in 09 generation: 75.52541422895794
댓글남기기