0%

使用简单的遗传算法求解函数的最大值

人工智能课上学了点遗传算法,记录搓的一段比较简单的实现代码,实现求解
$$
f(x)=xe^{sin(2\pi x)}
$$
在区间 $[0,5]$ 的最大值
(参数和算法设计不一定合理)

计算适应度函数,在此直接以 $f(x)$ 的值作为适应度

1
2
3
4
5
6
7
def fitness_function(solution):
fitness = 0
for i in range(chromosome_length):
fitness = fitness + solution[i] * 2**i
# Return the fitness of a solution
fitness = fitness/(2**chromosome_length-1)*5
return fitness*math.exp(math.sin(2*math.pi*fitness))

染色体单点交叉函数

1
2
3
4
5
6
7
8
def one_point_crossover(chromosome1, chromosome2):
# Select a random crossover point
crossover_point = random.randint(1, len(chromosome1) - 1)
# Create two new offspring chromosomes by swapping genetic information
offspring1 = chromosome1[:crossover_point] + chromosome2[crossover_point:]
offspring2 = chromosome2[:crossover_point] + chromosome1[crossover_point:]
# Return the two new offspring chromosomes
return offspring1, offspring2

参数定义,以及初始化种群

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Define the genetic algorithm parameters
population_size = 200
chromosome_length = 17
mutation_rate = 0.01
crossover_rate = 0.5
generations = 300

# Initialize the population
population = []
for i in range(population_size):
chromosome = []
for j in range(chromosome_length):
chromosome.append(random.randint(0, 1))
population.append(chromosome)

算法主体

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
import random
import math
# Run the genetic algorithm
for generation in range(generations):
# Evaluate the fitness of each solution in the population
fitness_scores = []
for chromosome in population:
fitness_scores.append(fitness_function(chromosome))

# Select the fittest individuals for reproduction
selected_population = []
for i in range(population_size//3):
chromosome1 = random.choices(population, weights=fitness_scores)[0]
chromosome2 = random.choices(population, weights=fitness_scores)[0]
selected_population.append(chromosome1)
selected_population.append(chromosome2)
if random.random() < crossover_rate:
offspring1, offspring2 = one_point_crossover(
chromosome1, chromosome2)
selected_population.append(offspring1)
selected_population.append(offspring2)

# Apply mutations to the selected population
mutated_population = []
for chromosome in selected_population:
for i in range(chromosome_length):
if random.random() < mutation_rate:
chromosome[i] = 1 - chromosome[i]
mutated_population.append(chromosome)

# Replace the old population with the new population
population = mutated_population

# Print the fittest solution for each generation
print("Generation:", generation, "Fittest solution:", max(fitness_scores))

输出示例(部分)

1
2
3
4
5
Generation: 295 Fittest solution: 11.560699289395993
Generation: 296 Fittest solution: 11.560699289395993
Generation: 297 Fittest solution: 11.560720015712006
Generation: 298 Fittest solution: 11.560790129849646
Generation: 299 Fittest solution: 11.560790129849646

可见准确度在误差允许的范围内