遗传算法解决函数最大化问题的完整Python实现

发布时间:2024年01月12日

遗传算法(Genetic Algorithm,简称GA)是一种模拟生物进化过程的启发式优化算法。它通过模拟自然选择、交叉和变异等基因操作,来搜索问题的最优解。

遗传算法的基本思想是通过模拟生物的遗传机制来搜索解空间。算法维护一个种群,其中每个个体都代表问题的一个可能解。通过不断进行选择、交叉和变异操作,优秀的个体逐渐被筛选出来,并且逐代进化,最终找到问题的最优解。

下面是一个使用遗传算法解决函数最大化问题的Python代码示例:

import numpy as np

class GeneticAlgorithm:
    def __init__(self, population_size, num_generations, crossover_rate, mutation_rate):
        self.population_size = population_size
        self.num_generations = num_generations
        self.crossover_rate = crossover_rate
        self.mutation_rate = mutation_rate

    def optimize(self, fitness_func, num_variables, variable_range):
        population = self.initialize_population(num_variables, variable_range)

        for generation in range(self.num_generations):
            fitness_values = self.calculate_fitness_values(population, fitness_func)
            best_individual = population[np.argmax(fitness_values)]
            print("Generation:", generation, "Best Fitness:", fitness_func(best_individual))

            new_population = [best_individual]

            while len(new_population) < self.population_size:
                parent1 = self.select_individual(population, fitness_values)
                parent2 = self.select_individual(population, fitness_values)
                child1, child2 = self.crossover(parent1, parent2)
                child1 = self.mutate(child1, variable_range)
                child2 = self.mutate(child2, variable_range)
                new_population.extend([child1, child2])

            population = new_population

        best_individual = population[np.argmax(fitness_values)]
        best_fitness = fitness_func(best_individual)

        return best_individual, best_fitness

    def initialize_population(self, num_variables, variable_range):
        population = []

        for _ in range(self.population_size):
            individual = np.random.uniform(low=variable_range[0], high=variable_range[1], size=num_variables)
            population.append(individual)

        return population

    def calculate_fitness_values(self, population, fitness_func):
        fitness_values = []

        for individual in population:
            fitness_values.append(fitness_func(individual))

        return np.array(fitness_values)

    def select_individual(self, population, fitness_values):
        probabilities = fitness_values / np.sum(fitness_values)
        selected_index = np.random.choice(range(len(population)), p=probabilities)
        return population[selected_index]

    def crossover(self, parent1, parent2):
        if np.random.rand() < self.crossover_rate:
            crossover_point = np.random.randint(1, len(parent1))
            child1 = np.concatenate((parent1[:crossover_point], parent2[crossover_point:]))
            child2 = np.concatenate((parent2[:crossover_point], parent1[crossover_point:]))
        else:
            child1 = parent1
            child2 = parent2

        return child1, child2

    def mutate(self, individual, variable_range):
        for i in range(len(individual)):
            if np.random.rand() < self.mutation_rate:
                individual[i] = np.random.uniform(low=variable_range[0], high=variable_range[1])

        return individual

# Example usage
def fitness_func(x):
    return -np.sum(x**2)

ga = GeneticAlgorithm(population_size=50, num_generations=100, crossover_rate=0.8, mutation_rate=0.1)
best_individual, best_fitness = ga.optimize(fitness_func, num_variables=5, variable_range=(-5, 5))

print("Best Individual:", best_individual)
print("Best Fitness:", best_fitness)

示例中使用一个简单的函数?fitness_func?来评估个体的适应度。遗传算法的参数包括种群大小(population_size)、迭代代数(num_generations)、交叉率(crossover_rate)和变异率(mutation_rate),可以根据具体问题进行调整。

程序输出如下:

Generation: 0 Best Fitness: -10.995211741266354
Generation: 1 Best Fitness: -10.995211741266354
Generation: 2 Best Fitness: -10.995211741266354
Generation: 3 Best Fitness: -10.995211741266354
Generation: 4 Best Fitness: -10.995211741266354
Generation: 5 Best Fitness: -10.995211741266354
Generation: 6 Best Fitness: -10.995211741266354
Generation: 7 Best Fitness: -10.995211741266354
Generation: 8 Best Fitness: -10.995211741266354
Generation: 9 Best Fitness: -10.995211741266354
Generation: 10 Best Fitness: -10.995211741266354
Generation: 11 Best Fitness: -10.995211741266354
Generation: 12 Best Fitness: -10.995211741266354
Generation: 13 Best Fitness: -10.995211741266354
Generation: 14 Best Fitness: -10.995211741266354
Generation: 15 Best Fitness: -10.995211741266354
Generation: 16 Best Fitness: -10.995211741266354
Generation: 17 Best Fitness: -10.995211741266354
Generation: 18 Best Fitness: -10.995211741266354
Generation: 19 Best Fitness: -10.995211741266354
Generation: 20 Best Fitness: -10.995211741266354
Generation: 21 Best Fitness: -10.995211741266354
Generation: 22 Best Fitness: -10.995211741266354
Generation: 23 Best Fitness: -10.995211741266354
Generation: 24 Best Fitness: -10.995211741266354
Generation: 25 Best Fitness: -10.995211741266354
Generation: 26 Best Fitness: -10.995211741266354
Generation: 27 Best Fitness: -10.995211741266354
Generation: 28 Best Fitness: -10.995211741266354
Generation: 29 Best Fitness: -10.995211741266354
Generation: 30 Best Fitness: -10.995211741266354
Generation: 31 Best Fitness: -10.995211741266354
Generation: 32 Best Fitness: -10.995211741266354
Generation: 33 Best Fitness: -10.995211741266354
Generation: 34 Best Fitness: -10.995211741266354
Generation: 35 Best Fitness: -10.995211741266354
Generation: 36 Best Fitness: -10.995211741266354
Generation: 37 Best Fitness: -10.995211741266354
Generation: 38 Best Fitness: -10.995211741266354
Generation: 39 Best Fitness: -10.995211741266354
Generation: 40 Best Fitness: -10.995211741266354
Generation: 41 Best Fitness: -10.995211741266354
Generation: 42 Best Fitness: -10.995211741266354
Generation: 43 Best Fitness: -10.995211741266354
Generation: 44 Best Fitness: -10.995211741266354
Generation: 45 Best Fitness: -10.995211741266354
Generation: 46 Best Fitness: -10.995211741266354
Generation: 47 Best Fitness: -10.995211741266354
Generation: 48 Best Fitness: -10.995211741266354
Generation: 49 Best Fitness: -10.995211741266354
Generation: 50 Best Fitness: -10.995211741266354
Generation: 51 Best Fitness: -10.995211741266354
Generation: 52 Best Fitness: -10.995211741266354
Generation: 53 Best Fitness: -10.995211741266354
Generation: 54 Best Fitness: -10.995211741266354
Generation: 55 Best Fitness: -10.995211741266354
Generation: 56 Best Fitness: -10.995211741266354
Generation: 57 Best Fitness: -10.995211741266354
Generation: 58 Best Fitness: -10.995211741266354
Generation: 59 Best Fitness: -10.995211741266354
Generation: 60 Best Fitness: -10.995211741266354
Generation: 61 Best Fitness: -10.995211741266354
Generation: 62 Best Fitness: -10.995211741266354
Generation: 63 Best Fitness: -10.995211741266354
Generation: 64 Best Fitness: -10.995211741266354
Generation: 65 Best Fitness: -10.995211741266354
Generation: 66 Best Fitness: -10.995211741266354
Generation: 67 Best Fitness: -10.995211741266354
Generation: 68 Best Fitness: -10.995211741266354
Generation: 69 Best Fitness: -10.995211741266354
Generation: 70 Best Fitness: -10.995211741266354
Generation: 71 Best Fitness: -10.995211741266354
Generation: 72 Best Fitness: -10.995211741266354
Generation: 73 Best Fitness: -10.995211741266354
Generation: 74 Best Fitness: -10.995211741266354
Generation: 75 Best Fitness: -10.995211741266354
Generation: 76 Best Fitness: -10.995211741266354
Generation: 77 Best Fitness: -10.995211741266354
Generation: 78 Best Fitness: -10.995211741266354
Generation: 79 Best Fitness: -10.995211741266354
Generation: 80 Best Fitness: -7.064365256135209
Generation: 81 Best Fitness: -7.064365256135209
Generation: 82 Best Fitness: -7.064365256135209
Generation: 83 Best Fitness: -7.064365256135209
Generation: 84 Best Fitness: -7.064365256135209
Generation: 85 Best Fitness: -7.064365256135209
Generation: 86 Best Fitness: -7.064365256135209
Generation: 87 Best Fitness: -7.064365256135209
Generation: 88 Best Fitness: -7.064365256135209
Generation: 89 Best Fitness: -7.064365256135209
Generation: 90 Best Fitness: -7.064365256135209
Generation: 91 Best Fitness: -7.064365256135209
Generation: 92 Best Fitness: -7.064365256135209
Generation: 93 Best Fitness: -7.064365256135209
Generation: 94 Best Fitness: -7.064365256135209
Generation: 95 Best Fitness: -7.064365256135209
Generation: 96 Best Fitness: -7.064365256135209
Generation: 97 Best Fitness: -7.064365256135209
Generation: 98 Best Fitness: -7.064365256135209
Generation: 99 Best Fitness: -7.064365256135209
Best Individual: [-0.03032724  1.23763913 -1.2927741   0.5056739   1.89861105]
Best Fitness: -7.064365256135209

文章来源:https://blog.csdn.net/qq_38563206/article/details/135502962
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。