python实现一个遗传算法

###################

 

 

import random

# 染色体长度
CHROMO_LENGTH = 20
# 种群大小
POP_SIZE = 50
# 交叉概率
CROSS_RATE = 0.8
# 变异概率
MUTATE_RATE = 0.01
# 最大迭代次数
N_GENERATIONS = 200


# 适应度函数
def fitness_function(chromosome):
    return sum(chromosome)


# 创建初始种群
def create_population():
    population = []
    for i in range(POP_SIZE):
        chromosome = [random.randint(0, 1) for _ in range(CHROMO_LENGTH)]
        population.append(chromosome)
    return population


# 选择函数
def select(population, fitness):
    fitness_sum = sum(fitness)
    p = [f / fitness_sum for f in fitness]
    index = random.choices(range(POP_SIZE), p=p)
    return population[index[0]]


# 交叉函数
def crossover(parent1, parent2):
    if random.random() < CROSS_RATE:
        crossover_point = random.randint(0, CHROMO_LENGTH)
        offspring1 = parent1[:crossover_point] + parent2[crossover_point:]
        offspring2 = parent2[:crossover_point] + parent1[crossover_point:]
    else:
        offspring1, offspring2 = parent1, parent2
    return offspring1, offspring2


# 变异函数
def mutate(chromosome):
    for i in range(CHROMO_LENGTH):
        if random.random() < MUTATE_RATE:
            chromosome[i] = 1 - chromosome[i]
    return chromosome


# 遗传算法主函数
def genetic_algorithm():
    population = create_population()
    for generation in range(N_GENERATIONS):
        fitness = [fitness_function(chromosome) for chromosome in population]
        new_population = []
        for _ in range(POP_SIZE // 2):
            parent1 = select(population, fitness)
            parent2 = select(population, fitness)
            offspring1, offspring2 = crossover(parent1, parent2)
            offspring1 = mutate(offspring1)
            offspring2 = mutate(offspring2)
            new_population.append(offspring1)
            new_population.append(offspring2)
        population = new_population
    return max(population, key=fitness_function)


if __name__ == '__main__':
    print(genetic_algorithm())

 

 

##############

 

###################

posted @ 2023-03-20 09:47  igoodful  阅读(89)  评论(0编辑  收藏  举报