我正在試驗關于遺傳演算法的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)在繁殖時創建負突變。幫助我以簡潔的方式撰寫這些函式會對我有很大幫助。
我知道這是一篇不完整的長篇文章,但在這個初始階段幫助我將極大地幫助我。如果這不是高級作業,我很抱歉。
無論如何,提前致謝。
uj5u.com熱心網友回復:
試試這個,你可以對老鼠的初始數量和世代等進行實驗。有一個類 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/336926.html
標籤:Python 蟒蛇-3.x python-2.7 蟒蛇请求
