-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirstGA.py
More file actions
45 lines (35 loc) · 1.55 KB
/
firstGA.py
File metadata and controls
45 lines (35 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import random
#parametreler
population_size = 50 #popülasyon büyüklüğü
gene_length = 20 #gen uzunluğu
mutation_rate = 0.1 #mutasyon oranı
generations = 100 #maksimum nesil sayısı
#fitness fonksiyonu
def get_fitness(individual):
#bir bireyin ne kadar başarılı olduğunu hesaplar (1'lerin sayısı)
return sum(individual)
#başlangıç popülasyonunu oluşturma
population = [[random.randint(0,1) for _ in range(gene_length)] for _ in range(population_size)]
#evrim döngüsü
for gen in range(generations):
#fitness değerlerine göre popülasyonu sırala (en iyi olan en üstte)
population = sorted(population, key=get_fitness, reverse=True)
current_best = population[0]
print(f"Generation {gen}: Best Fitness = {get_fitness(current_best)} | {current_best}")
#hedefe ulaşıldı mı kontrol et
if get_fitness(current_best) == gene_length:
print("Optimal solution found!")
break
#yeni popülasyonu oluşturma ve seçilim (elitizm, en iyi %10 korunur)
new_population = population[:5]
while len(new_population) < population_size:
#crossover, iki ebeveynden parçalar alarak yeni birey oluşturma
parent1, parent2 = random.sample(population[:20], 2)
cut = gene_length // 2
child = parent1[:cut] + parent2[cut:]
#mutasyon, rastgele genleri değiştirme
if random.random() < mutation_rate:
idx = random.randint(0, gene_length - 1)
child[idx] = 1 if child[idx] == 0 else 0
new_population.append(child)
population = new_population