import numpy as np
# Inisialisasi populasi awal
def initialize_population(population_size, chromosome_length):
population = np.random.randint(2, size=(population_size, chromosome_length))
return population
# Evaluasi fitness individu
def fitness_function(chromosome):
# Misalkan kita ingin memaksimalkan jumlah bit yang bernilai 1
return np.sum(chromosome)
# Evaluasi fitness populasi
def evaluate_population(population):
fitness_values = np.zeros(len(population))
for i in range(len(population)):
fitness_values[i] = fitness_function(population[i])
return fitness_values
# Seleksi orangtua menggunakan turnamen
def tournament_selection(population, fitness_values, tournament_size):
selected_parents = np.zeros((2, len(population[0])))
for i in range(2):
tournament_indices = np.random.choice(len(population), tournament_size, replace=False)
tournament_fitness = fitness_values[tournament_indices]
winner_index = tournament_indices[np.argmax(tournament_fitness)]
selected_parents[i] = population[winner_index]
return selected_parents
# Crossover menggunakan satu titik potong
def crossover(parents):
crossover_point = np.random.randint(1, len(parents[0]))
child1 = np.concatenate((parents[0][:crossover_point], parents[1][crossover_point:]))
child2 = np.concatenate((parents[1][:crossover_point], parents[0][crossover_point:]))
return child1, child2
# Mutasi dengan probabilitas mutasi
def mutation(chromosome, mutation_rate):
for i in range(len(chromosome)):
if np.random.rand() < mutation_rate:
chromosome[i] = 1 - chromosome[i] # Flip the bit
return chromosome
# Algoritma genetika
def genetic_algorithm(population_size, chromosome_length, tournament_size, mutation_rate, num_generations):
population = initialize_population(population_size, chromosome_length)
best_fitness = np.zeros(num_generations)
for generation in range(num_generations):
fitness_values = evaluate_population(population)
best_fitness[generation] = np.max(fitness_values)
selected_parents = tournament_selection(population, fitness_values, tournament_size)
new_population = np.zeros((population_size, chromosome_length))
for i in range(0, population_size, 2):
child1, child2 = crossover(selected_parents)
new_population[i] = mutation(child1, mutation_rate)
new_population[i+1] = mutation(child2, mutation_rate)
population = new_population
best_chromosome = population[np.argmax(fitness_values)]
return best_chromosome, best_fitness
# Pengaturan parameter
population_size = 100
chromosome_length = 20
tournament_size = 5
mutation_rate = 0.01
num_generations = 100
# Menjalankan algoritma genetika
best_chromosome, best_fitness = genetic_algorithm(population_size, chromosome_length, tournament_size, mutation_rate, num_generations)
# Output hasil
print("Best Chromosome:", best_chromosome)
print("Best Fitness:", np.max(best_fitness))
Tidak ada komentar:
Posting Komentar