0-1背包问题

#背包容量一定 规划放置方案 价值最大
#0-1背包问题
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 = 100
selection_rate = 0.5
mutation_rate = 0.01

#初始化种群函数
def init_population():
    population = []
    for i in range(pop_size):
        chromosome = []
        for j in range(num_items):
            chromosome.append(random.randint(0,1))#随机初始化染色体填充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,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)
    child1 = parent1[:crossover_point] + parent2[crossover_point:]
    child2 = parent2[:crossover_point] + parent1[crossover_point:]
    return child1, child2

def mutatuion(charomose):
    for i in range(num_items):
        if random.random() < selection_rate:
            j = random.randint(0,num_items - 1)
            charomose[i] , charomose[j] = charomose[j], charomose[i]
    return charomose

#主函数
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 = mutatuion(child1)
            child2 = mutatuion(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("Bset Solution :",best_chromosome)
    print("Best Fitness :",best_fitness)
genetic_algorithm()

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值