Python 遗传算法:设置函数以供使用

Python Genetic Algorithm: Setting Functions for Usage

我正在试验 python 遗传算法。换句话说,我想制作一个程序来模拟随机过程和控制部分(如实验)来处理变量和结果。

对于我的程序,我正在模拟老鼠繁殖并控制其数量以在最后创造出更好的(在我的例子中,更重的)老鼠。具体来说,我想要老鼠的起始种群,随机配对两只进行繁殖(其中后代将具有两只母鼠的平均体重)并控制后代种群等。简而言之,我将拥有 x 只老鼠(初始和常量),创造后代,按重量列出它们,从底部杀死(最轻的老鼠)以降低后代数量 == 初始数量并重复该过程以最终创造更重的老鼠老鼠.

我知道这个实验并不能反映现实生活中的例子,但我想用这个程序进行初始化,并可能对其他用法进行修改或应用。

抱歉介绍太长了。现在,在编写实际程序之前,我想创建函数(使用 def 命令)以使实际代码更易于编写。到目前为止,我想出了这个:

import random

#Variables (Stop at (1) period of time or (2) above standard)
#number_rats = #initial population (standard)
min_offspring = 2
max_offspring = 10
#weight_rat = #Avg. of parents' weight (consider as single gender)
#mutation = #Randomly reduce the weight of small number of offspring (how many and how 
much)

def breeding(female, male):
    #random # of offspring and random weight for each
    offspring = []
    number_offspring = random.randint(min_offspring, max_offspring)
    for i in range(0, number_offspring, 1):
         offspring.append(random.triangular(female, male))
    return offspring

def #random pair

def # cut offspring population to number_rats (list from highest weight to lowest and 
cut light rats)

def # negative mutation (maybe inside breeding function) 10% chance of mutation that 
decreases weight by 10%.

我已经尝试完成繁殖功能以取 2 只老鼠(我标记为雄性和雌性,但我决定任何 2 只老鼠都可以减少并发症)并且它们会产生随机数量的后代。

但是,我一直在为以下内容创建函数:(1) 从 number_rats 中随机取对,(2) 将大量后代切割成 == number_rat,以及 (3) 创建负数繁殖时突变。帮我把这些函数写的简洁一些,对我有很大的帮助。

我知道这很长 post,工作还未完成,但在这个初始阶段帮助我将对我有很大帮助。如果这不是高级工作,我很抱歉。

无论如何,先谢谢了。

试试这个,您可以对大鼠的初始数量和世代等进行实验。有一个 class Rat 定义了一个带有名称和体重的老鼠,用于追踪体重。

代码

import random
import string


num_rats = 20
min_offspring = 2
max_offspring = 10
init_weight_min = 1
init_weight_max = 10
mutation_chance_rate = 10  # %
mutation_weight_decrease = 10  # %
generations = 4


alphabet = string.ascii_lowercase + string.digits
def random_name():
    """Generates random chars for rat names."""
    return ''.join(random.choices(alphabet, k=8))


def print_population(population):
    for i, r in enumerate(population):
        print(f'no. {i+1:02d}, name: {r.name}, weight: {r.weight}')


class Rat:
    def __init__(self, name, weight):
        self.name = name
        self.weight = weight


def breeding(p1, p2):
    """
    Create offsprings from parents p1 and p2.
    Randomize number of offsprings and weight is based on parents weight.
    """
    offspring = []
    w1 = p1.weight
    w2 = p2.weight
    meanw = (w1+w2)/2

    number_offspring = random.randint(min_offspring, max_offspring)
    for _ in range(1, number_offspring):
        name = random_name()
        weight = meanw
        offspring.append(Rat(name, weight))  # Create Rat object as new pop

    return offspring


def random_pair():
    pass


def cut_offspring_population(population):
    """
    population is a list of rats.
    Cut offsprings to orignal number of rats, preserve heavier rats.
    """
    new_population = sorted(population, key=lambda x: x.weight, reverse=True)  # sort rats weights descending
    return new_population[0:num_rats]  # Cutoff


def negative_mutation(population):
    """
    10% chance of mutation that decreases weight by 10%.
    """
    new_population = []

    for p in population:
        current_name = p.name
        current_weight = p.weight

        if random.randint(1, 100) <= mutation_chance_rate:
            current_weight = current_weight * (100 - mutation_weight_decrease) / 100
            new_population.append(Rat(current_name, current_weight))
        else:
            new_population.append(Rat(current_name, current_weight))

    return new_population


def main():
    # (1) Create rats
    orig_rats = []
    for _ in range(num_rats):
        orig_rats.append(Rat(random_name(), random.randint(init_weight_min, init_weight_max)))

    random.shuffle(orig_rats)

    tmp_rats = orig_rats.copy()

    for i in range(1, generations + 1):
        # (2) Breeding
        new_offs = []

        while tmp_rats:
            # Select 2 rats as parents.
            a = tmp_rats.pop()
            b = tmp_rats.pop()

            offs = breeding(a, b)
            new_offs = new_offs + offs  # save all new offsprings in a list.

        # (3) Reduce population.
        reduced_pop = cut_offspring_population(new_offs)

        # (4) Mutation
        mutated_pop = negative_mutation(reduced_pop)
        print(f'gen: {i}')
        print_population(mutated_pop)
        print()

        tmp_rats = mutated_pop.copy()  # for next gen


if __name__ == "__main__":
    main()

4代后的输出

后代体重是parents体重的平均值。老鼠的名字是随机的。

gen: 1
no. 01, name: gzqru5c7, weight: 10.0
no. 02, name: ngpqx75q, weight: 10.0
no. 03, name: 3f2f8ua9, weight: 10.0
no. 04, name: uitaftbs, weight: 9.0
no. 05, name: dkr2dmyg, weight: 9.0
no. 06, name: lq350zck, weight: 8.0
no. 07, name: 4l08ks0t, weight: 8.0
no. 08, name: 1sl64mzl, weight: 7.5
no. 09, name: 88umsinn, weight: 7.5
no. 10, name: 3f30jp8m, weight: 7.5
no. 11, name: y1gbmbyn, weight: 7.5
no. 12, name: j7w7fr9y, weight: 7.5
no. 13, name: 3x5gl7zt, weight: 7.5
no. 14, name: 7mus480j, weight: 7.5
no. 15, name: 8yaifbuf, weight: 7.5
no. 16, name: t14n1qyq, weight: 7.5
no. 17, name: pqtieh8h, weight: 7.0
no. 18, name: 2eb1rhax, weight: 7.0
no. 19, name: ekfhcwye, weight: 7.0
no. 20, name: gdmeu1td, weight: 7.0

gen: 2
no. 01, name: nod75vx3, weight: 10.0
no. 02, name: pbe2z04b, weight: 10.0
no. 03, name: 1gn30dch, weight: 9.0
no. 04, name: txj11vza, weight: 10.0
no. 05, name: eonla5xu, weight: 9.0
no. 06, name: kwh5uffh, weight: 10.0
no. 07, name: pcvw8djm, weight: 10.0
no. 08, name: 7upmw4bu, weight: 9.0
no. 09, name: 3yb36bfr, weight: 10.0
no. 10, name: sjp0m8n8, weight: 10.0
no. 11, name: yj5oyuwd, weight: 9.5
no. 12, name: hsnbhyy7, weight: 9.5
no. 13, name: 40bpj2jw, weight: 9.5
no. 14, name: 4cdsgb4l, weight: 9.5
no. 15, name: 4lutoxh7, weight: 9.5
no. 16, name: s1111jrc, weight: 9.5
no. 17, name: le2m1x6w, weight: 7.65
no. 18, name: m2t9tfas, weight: 8.5
no. 19, name: r1gzn6a7, weight: 8.5
no. 20, name: lmvntp28, weight: 8.5

gen: 3
no. 01, name: 6g42b95g, weight: 10.0
no. 02, name: end7366f, weight: 10.0
no. 03, name: ccivuw0g, weight: 9.0
no. 04, name: rpf9pd51, weight: 10.0
no. 05, name: 94qkveea, weight: 10.0
no. 06, name: x1p9rd00, weight: 10.0
no. 07, name: v4d39x6t, weight: 10.0
no. 08, name: z3miwqoy, weight: 10.0
no. 09, name: vmkkrkqt, weight: 10.0
no. 10, name: ii8is1xp, weight: 10.0
no. 11, name: uadfjnng, weight: 10.0
no. 12, name: 5349eie7, weight: 10.0
no. 13, name: ikpoyce6, weight: 10.0
no. 14, name: yqqgsm9p, weight: 10.0
no. 15, name: ykkq03jv, weight: 10.0
no. 16, name: i3zzdab2, weight: 10.0
no. 17, name: 1m7kjzom, weight: 9.0
no. 18, name: vqatmrar, weight: 10.0
no. 19, name: 6ddudyf7, weight: 9.5
no. 20, name: 5b9dhzwp, weight: 9.5

gen: 4
no. 01, name: mm0iggdw, weight: 10.0
no. 02, name: u6evuhn8, weight: 9.0
no. 03, name: e0jo12tu, weight: 9.0
no. 04, name: wbage11q, weight: 10.0
no. 05, name: 4zlf1gvx, weight: 10.0
no. 06, name: 1c2hr5dd, weight: 10.0
no. 07, name: hbyzhpfn, weight: 10.0
no. 08, name: avf5ptk5, weight: 10.0
no. 09, name: hgurh5l0, weight: 10.0
no. 10, name: crqyuao0, weight: 10.0
no. 11, name: vjxkf3qf, weight: 10.0
no. 12, name: myzdj95e, weight: 9.0
no. 13, name: 8v4g3wxz, weight: 10.0
no. 14, name: l0z17ijw, weight: 10.0
no. 15, name: 1z3brmra, weight: 10.0
no. 16, name: r261q7pr, weight: 10.0
no. 17, name: ovl7vla5, weight: 10.0
no. 18, name: f2mvcvyw, weight: 10.0
no. 19, name: u1x8b7il, weight: 9.0
no. 20, name: l5k43dut, weight: 10.0

打印每代平均重量的代码

从代码来看,变异后完成了一代。所以我把代码放在突变之后。

从 # Print average 开始插入以下代码..

        tmp_rats = mutated_pop.copy()  # for next gen

        # Print average.
        rwt = []
        for p in tmp_rats:  # [Rat('aaa', 10), Rat('bbb', 8) ...]
            rwt.append(p.weight)
        aw = sum(rwt) / len(rwt)
        print(f'average weight: {aw:0.2f}')  # :0.2f is up to 2 decimal places
        print()