欢迎光临散文网 会员登陆 & 注册

【计算智能】什么是遗传算法?如何用Python实现?

2023-08-22 21:49 作者:不学到抽搐岂敢入眠  | 我要投稿
import random

num_items=6#物品数量
capacity=80#容量大小
weight=[25,15,20,30,20,15]
value=[15,5,10,20,10,10]
pop_size=50#种群大小
num_generations=1000#迭代次数

#考虑选择变异有一个选择率
selection_rate=0.5
#变异率
mutation_rate=0.01

def swap(t1, t2):
     t1,t2=t2, t1
     return

#初始化种群函数
def init_population():
    population=[]#种群是一个数组,其中有一些染色体
    for i in range(pop_size):
        chromosome=[]
        for j in range(num_items):
            chromosome.append(random.randint(0,1))#随机初始化染色体
        population.append(chromosome) #pop_size个染色体形成一个种群
    return population

#计算适应度
def fitness(chromosome):
    total_weight=0
    total_value=0
    for i in range(num_items):
        if(chromosome[i]==1):
            total_weight+=weight[i]
            total_value+=value[i]
    if total_weight>capacity:
        return 0
    else :
        return total_value

#选择函数
def selection(population):
    population_fitness=[]#组成适应度数组
    for chromosome in population:
        population_fitness.append(fitness(chromosome))
    #下方是根据适应度排序的数组
    sorted_population=[x for _,x in sorted(zip(population_fitness,population),reverse= True)]
    cutoff=int(selection_rate*len(sorted_population))
    return sorted_population[:cutoff]

#交换函数
def crossover(parent1,parent2):
    crossover_point=random.randint(0,num_items-1)#0-5之间选择一个交叉点
    child1=parent1[:crossover_point]+parent2[crossover_point:]
    child2=parent2[:crossover_point]+parent1[crossover_point:]
    return child1,child2

#变异函数
def mutation(chromosome):
    #模拟变异的过程,任何时候都可能变异
    for i in range(num_items):
        if random.random()<mutation_rate:
            j=random.randint(0,num_items-1)
            swap(chromosome[i],chromosome[j])
    return chromosome

#遗传算法的主函数
def genetic_algorithm():
    population=init_population()
    for i in range(num_generations):
        selected_population=selection(population)
        offspring_population=[]
        for j in range(pop_size-len(selected_population)):
            #体现选择的随机性
            parent1=random.choice(selected_population)
            parent2=random.choice(selected_population)
            child1,child2=crossover(parent1,parent2)
            child1=mutation(child1)
            child2=mutation(child2)
            offspring_population.append(child1)
            offspring_population.append(child2)
        population=selected_population+offspring_population
        best_chromosome=max(population,key=fitness)
        best_fitness=fitness(best_chromosome)
    print("Best Solution: ",best_chromosome)
    print("Best Fitness : ",best_fitness)

# def __init__():

genetic_algorithm()


【计算智能】什么是遗传算法?如何用Python实现?的评论 (共 条)

分享到微博请遵守国家法律