From 98965aa225df2f476e9a1cc19332ca69b8672f90 Mon Sep 17 00:00:00 2001 From: hamazaki1990 Date: Fri, 26 May 2017 22:41:45 +0900 Subject: [PATCH] approaching deepcopy #22 --- hamazaki1990/individual.py | 15 ++++++++++----- hamazaki1990/population.py | 11 ++++------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/hamazaki1990/individual.py b/hamazaki1990/individual.py index 01ad902..688b678 100644 --- a/hamazaki1990/individual.py +++ b/hamazaki1990/individual.py @@ -1,8 +1,9 @@ import random +import copy class Individual: - mutationrate = 0.001 + mutationrate = 1 def __init__(self, n, f=1.0): self._id = n @@ -20,10 +21,12 @@ def get_genotype(self): def acquire_mutation(self): r = random.random() - next_genotype = self._genotype + next_ind = copy.deepcopy(self) + next_genotype = next_ind._genotype if r < Individual.mutationrate: next_genotype.append(random.random()) - self._genotype = next_genotype + next_ind._genotype = next_genotype + return next_ind def __repr__(self): return str(self._id) @@ -34,11 +37,13 @@ def main(): print(ind.get_id()) print(ind.get_fitness()) - ind2 = Individual(30, 0.8) + ind2 = Individual(30) print(ind2.get_id()) print(ind2.get_fitness()) - ind2.acquire_mutation() print(ind2.get_genotype()) + ind2_1 = ind2.acquire_mutation() + print(ind2.get_genotype()) + print(ind2_1.get_genotype()) ind2.acquire_mutation() print(ind2.get_genotype()) print(ind2.get_id()) diff --git a/hamazaki1990/population.py b/hamazaki1990/population.py index 462d32e..29af423 100644 --- a/hamazaki1990/population.py +++ b/hamazaki1990/population.py @@ -1,5 +1,4 @@ import random -import copy from individual import Individual @@ -34,19 +33,17 @@ def next_genwf(self): cumsum_fitness = [sum(fitness[:i]) for i in range(1, size + 1)] next_generation = [] for x in range(size): - current_inds = copy.deepcopy(self._inds) - next_inds = roulettechoice(current_inds, cumsum_fitness) - next_inds.acquire_mutation() + parent_inds = roulettechoice(self._inds, cumsum_fitness) + next_inds = parent_inds.acquire_mutation() next_generation.append(next_inds) - self._inds = next_generation + return next_generation def next_genmo(self): fitness = [x.get_fitness() for x in self._inds] size = len(self._inds) cumsum_fitness = [sum(fitness[:i]) for i in range(1, size + 1)] i_dying = random.randrange(size) - current_inds = copy.deepcopy(self._inds) - next_inds = roulettechoice(current_inds, cumsum_fitness) + next_inds = roulettechoice(self._inds, cumsum_fitness) next_inds.acquire_mutation() self._inds[i_dying] = next_inds