遗传动态背包模板笔试

import random

pop_size = 1000
pop = []
# 适应度
pop_fitness = []
# n length
chrom_len = 6

itrator = 1

# 总金额
sum_mony = 1000
# 价格列表
price_degree = [200, 600, 100, 180, 300, 450]
# 热度列表
hot_degree = [6, 10, 3, 4, 5, 8]


def cross(p1, p2):
    for i in range(len(p1)):
        if random.random() < 0.3:
            r1 = random.random()
            r2 = 1 - r1
            y1 = r1 * p1[i] + r2 * p2[i]
            y2 = r2 * p1[i] + r1 * p2[i]
            p1[i] = y1
            p2[i] = y2
    return p1, p2


def create():
    gene = []
    for i in range(chrom_len):
        gene.append(random.random())
    return gene


# 计算价格,基因0-1,>0.5选中
def call(gene):
    sum_v = 0
    for i, g in enumerate(gene):
        if g > 0.5:
            sum_v += hot_degree[i]
    return sum_v


def check(gene):
    sum_v = 0
    for i, g in enumerate(gene):
        if g > 0.5:
            sum_v += price_degree[i]
    return sum_v < sum_mony


# 突变
def mutate(p1):
    for i in range(len(p1)):
        if random.random() < 0.05:
            r1 = random.random() * -0.2 + 0.1
            y1 = p1[i] + r1
            if y1 > 1: y1 = 1
            if y1 < 0: y1 = 0
            p1[i] = y1
    return p1


# 进化
def revolution():
    global pop_fitness
    global pop
    global pop_size
    for i in range(pop_size):
        p = create()
        pop.append(p)
        pop_fitness.append(call(p))
    best_gene = []
    max_fitness = 0
    for i in range(itrator):
        pop_fitness = []
        for i in range(pop_size):
            p = pop[i]
            p_fit = call(p)
            pop_fitness.append(p_fit)
            if p_fit > max_fitness and check(p):
                max_fitness = p_fit
                best_gene = p.copy()
                print(i, max_fitness)
        for ii in range(pop_size):
            jj = random.randint(0, pop_size - 1)
            k = random.randint(0, pop_size - 1)
            pj = pop[jj]
            pk = pop[k]
            n_pj, n_pk = cross(pj, pk)
            n_pj = mutate(n_pj)
            n_pk = mutate(n_pk)
            pop[jj] = n_pj[:]
            pop[k] = n_pk[:]

    return best_gene


if __name__ == '__main__':
    gene = revolution()
    print(gene)

 

posted @ 2019-06-04 20:33  jj千寻  阅读(76)  评论(0编辑  收藏  举报