【问题标题】:Python Genetic Algorithm: Setting Functions for UsagePython 遗传算法:设置函数以供使用
【发布时间】:2021-12-11 12:01:06
【问题描述】:

我正在用 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) 在繁殖时产生负突变。帮助我以简洁的方式编写这些函数对我有很大帮助。

我知道这篇文章很长,工作不完整,但在这个初始阶段帮助我会极大地帮助我。如果这不是高级工作,我很抱歉。

无论如何,提前致谢。

【问题讨论】:

    标签: python python-3.x python-2.7 python-requests


    【解决方案1】:

    试试这个,你可以对老鼠的初始数量和世代等进行实验。有一个 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代后输出

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

    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()
    
    

    【讨论】:

    • 哇,这将帮助我进行如此多的实验并使用该程序。非常感谢这个人。干杯!
    • 不客气。
    • 嘿伙计,我不太习惯 python 中的 init(self) 命令。如果你有空,你能帮我理解一下“类鼠”这个功能吗?另外,如果我要对每一代的所有权重进行平均(例如,在第 1 代之后,从第 1 代开始平均权重:#),哪个函数最好妥协?干杯人
    • 一个类就像一个普通变量,但可以取 2 个或更多值。示例 x=45,x 是一个可以取单个值的变量。 r = Rat("name", 10), r 是一个变量,但有两个值,即r.namer.weightr.name 中的名称来自 self.name。 Have a look here。稍后我将发布一个示例代码,说明如何获取每代的 ave wt。
    • 添加的代码见Code to print average weight per generation.
    猜你喜欢
    • 2023-02-20
    • 2021-03-04
    • 2013-11-01
    • 2011-04-07
    • 2017-04-16
    • 2019-12-26
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多