Problem, GP with Island model.

226 views
Skip to first unread message

COMZ

unread,
Jun 5, 2012, 10:58:12 PM6/5/12
to deap-users
I merged two example; gp_symbreg.py and ga_symbreg_multidemic.py. But,
it did not work. How can i solve it?


import array
import random

from deap import algorithms
from deap import base
from deap import creator
from deap import tools

import operator
import math
from deap import gp

def safeDiv(left, right):
try:
return left / right
except ZeroDivisionError:
return 0

pset = gp.PrimitiveSet("MAIN", 1)
pset.addPrimitive(operator.add, 2)
pset.addPrimitive(operator.sub, 2)
pset.addPrimitive(operator.mul, 2)
pset.addPrimitive(safeDiv, 2)
pset.addPrimitive(operator.neg, 1)
pset.addPrimitive(math.cos, 1)
pset.addPrimitive(math.sin, 1)
pset.addEphemeralConstant(lambda: random.randint(-1,1))
pset.renameArguments({"ARG0" : "x"})

creator.create("FitnessMin", base.Fitness, weights=(-1.0,))
creator.create("Individual", gp.PrimitiveTree,
fitness=creator.FitnessMin, pset=pset)

toolbox = base.Toolbox()

toolbox.register("expr", gp.genRamped, pset=pset, min_=1, max_=2)
toolbox.register("individual", tools.initIterate, creator.Individual,
toolbox.expr)
toolbox.register("population", tools.initRepeat, list,
toolbox.individual)
toolbox.register("lambdify", gp.lambdify, pset=pset)

def evalSymbReg(individual):
# Transform the tree expression in a callable function
func = toolbox.lambdify(expr=individual)
# Evaluate the sum of squared difference between the expression
# and the real function : x**4 + x**3 + x**2 + x
values = (x/10. for x in xrange(-10,10))
diff_func = lambda x: (func(x)-(x**4 + x**3 + x**2 + x))**2
diff = sum(map(diff_func, values))
return diff,

toolbox.register("evaluate", evalSymbReg)
toolbox.register("select", tools.selTournament, tournsize=3)
toolbox.register("mate", gp.cxUniformOnePoint)
toolbox.register("expr_mut", gp.genFull, min_=0, max_=2)
toolbox.register('mutate', gp.mutUniform, expr=toolbox.expr_mut)
toolbox.register("migrate", tools.migRing, k=5,
selection=tools.selBest, replacement=tools.selRandom)

def main():
random.seed(64)

NBR_DEMES = 3
MU = 30
NGEN = 40
CXPB = 0.5
MUTPB = 0.2
MIG_RATE = 5

demes = [toolbox.population(n=MU) for _ in xrange(NBR_DEMES)]
hof = tools.HallOfFame(1)
stats = tools.Statistics(lambda ind: ind.fitness.values, 4)
stats.register("avg", tools.mean)
stats.register("std", tools.std)
stats.register("min", min)
stats.register("max", max)

logger = tools.EvolutionLogger(["gen", "evals"] +
stats.functions.keys())
logger.logHeader()

for idx, deme in enumerate(demes):
for ind in deme:
ind.fitness.values = toolbox.evaluate(ind)
stats.update(deme, idx)
hof.update(deme)
logger.logGeneration(gen="0.%d" % idx, evals=len(deme),
stats=stats, index=idx)

stats.update(demes[0]+demes[1]+demes[2], 3)
logger.logGeneration(gen=0, evals="-", stats=stats, index=3)

gen = 1
while gen <= NGEN and stats.min[3][-1][0] > 0 :#stats.max[3][-1]
[0] < 100.0:
# print stats.max[3][-1][0],stats.min[3][-1][0]
for idx, deme in enumerate(demes):
algorithms.varAnd(deme, toolbox, cxpb=CXPB, mutpb=MUTPB)
#algorithms.eaSimple(deme, toolbox, CXPB, MUTPB, 1, stats,
halloffame=hof)
for ind in deme:
ind.fitness.values = toolbox.evaluate(ind)

stats.update(deme, idx)
hof.update(deme)
logger.logGeneration(gen="%d.%d" % (gen, idx),
evals=len(deme), stats=stats, index=idx)

if gen % MIG_RATE == 0:
toolbox.migrate(demes)
stats.update(demes[0]+demes[1]+demes[2], 3)
logger.logGeneration(gen="%d" % gen, evals="-", stats=stats,
index=3)
gen += 1

print hof
return demes, stats, hof

if __name__ == "__main__":
main()




ERROR MESG:

File "island.py", line 130, in <module>
main()
File "island.py", line 121, in main
toolbox.migrate(demes)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/
lib/python2.7/site-packages/deap/tools.py", line 1786, in migRing
indx = populations[to_deme].index(immigrant)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/
lib/python2.7/site-packages/deap/base.py", line 279, in __eq__
return self.obj == other.obj
AttributeError: 'Individual' object has no attribute 'obj'

Félix-Antoine Fortin

unread,
Jun 6, 2012, 3:06:05 PM6/6/12
to deap-...@googlegroups.com
Hi,

Following your message, we found two problems, on in deap.base and 
the other and the multidemic example. So first, thank you for your bug
report ;).

Second, to get your code working, you will need to modifiy deap/base.py,
more specifically, you will need to replace the __eq__ of NodeProxy by
the following code :

        def __eq__(self, other):
            if isistance(other, self.__class__):
                return self.obj == other.obj
            else:
                return False

Basically, the problem was that a Tree can be composed of Node, but
also other trees. Since a tree is a list, Python use the __eq__ of list to
determine if two trees are equals. However, the __eq__ operator was 
not conceived to compare a Node with anything else than a Node. 
With the preceding patch, if the other object is not a Node, the function
now returns false.

As to why this error only surfaces when using migration, it is because 
we almost never use check if two trees are equal. However, in migRing,
we use the list.index operation to find the index associated to an Individual
in a list of Individual, and list.index use the __eq__ operator to compare
every Individual of the list with the argument. That concludes the problem
you reported with migRing.

We however found a second problem in the configuration of ga_onemax_multidemic.
It is explicited clearly in the documentation that : 
the replacement strategy must select k 
different individuals. For example, using a traditional tournament for 
replacement strategy will thus give undesirable effects, two individuals 
will most likely try to enter the same slot.

However in our own example, we used selRandom as a replacement strategy,
which contradicts the preceding quotes since this operator can return the same
individual multiple times. Therefore, in your code instead of using selRandom,
you should use random.sample :
toolbox.register("migrate", tools.migRing, k=5, 
selection=tools.selBest, replacement=random.sample) 

Both of this problems have been fixed on the default branch of the Mercurial
repository, and will be part of the next release, 0.8.2, which should come 
out soon.

Thanks again for the bug report.
Félix-Antoine Fortin

Jongseong KIM

unread,
Jun 6, 2012, 3:35:23 PM6/6/12
to deap-...@googlegroups.com
Hi,

Thank you for answer.

Always, I think DEAP is really awesome.

Jongseong Kim

Ph.d Candidate
Department of Industrial Engineering
Sungkyunkwan Univ.

Jongseong KIM

unread,
Jun 6, 2012, 3:44:42 PM6/6/12
to deap-...@googlegroups.com
Hi,

I checkout repository. It occur bug.
You missed. 
Correct following,please.
isistance ----> isinstance


Jongseong Kim

Ph.d Candidate
Department of Industrial Engineering
Sungkyunkwan Univ.

On 2012. 6. 7., at 4:06, "Félix-Antoine Fortin" <felix.anto...@gmail.com> wrote:

Félix-Antoine Fortin

unread,
Jun 6, 2012, 3:50:16 PM6/6/12
to deap-...@googlegroups.com
Oups, sorry about that.
It is now fixed.

Thanks again.
Félix-Antoine Fortin

On Tuesday, June 5, 2012 10:58:12 PM UTC-4, COMZ wrote:
Reply all
Reply to author
Forward
0 new messages