python - Python DEAP mutFlipBit 的类型错误

标签 python genetic-programming mutation deap

我正在使用 DEAP 编写我的第一个进化算法。 一切正常,但 MultiFlipBit 变异运算符除外。 当我尝试改变树(个体)时,出现以下错误:

File "Genetic_Programming.py", line 92, in main
    halloffame=hof, verbose=True)

    offspring = varOr(population, toolbox, lambda_, cxpb, mutpb)
File "/Users/anaconda/lib/python2.7/site-packages/deap/algorithms.py", line 235, in varOr
    ind, = toolbox.mutate(ind)
File "/Users/anaconda/lib/python2.7/site-packages/deap/tools/mutation.py", line 132, in mutFlipBit
    individual[i] = type(individual[i])(not individual[i])
TypeError: __init__() takes exactly 4 arguments (2 given)

这是代码:

pset = gp.PrimitiveSet("MAIN", 8)
pset.addPrimitive(operator.and_, 2)
pset.addPrimitive(operator.or_, 2)
pset.addPrimitive(operator.xor, 2)
pset.addPrimitive(operator.not_, 1)

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

toolbox = base.Toolbox()
toolbox.register("expr", gp.genGrow, pset=pset, min_=1, max_=8)
toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.expr)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("compile", gp.compile, pset=pset)

def evalSymbReg(individual):
    # Transform the tree expression in a callable function
    print individual
    ind = toolbox.compile(expr=individual)
    # Evaluate the mean squared error between the expression
    # and the real function : x**4 + x**3 + x**2 + x
    performance=Genetic_V0.genetic_backtest(ind)
    return performance,

toolbox.register("evaluate", evalSymbReg)
toolbox.register("select", tools.selTournament, tournsize=50)
toolbox.register("mate", gp.cxOnePoint)
#toolbox.register("expr_mut", gp.genGrow, min_=1, max_=4)
#toolbox.register("mutate", tools.mutFlipBit, expr=toolbox.expr_mut, pset=pset)
toolbox.register("mutate", tools.mutFlipBit, indpb=0.95)

def main():
    nu=50 
    pop = toolbox.population(n=nu)
    hof = tools.HallOfFame(3)

    stats_fit = tools.Statistics(lambda ind: ind.fitness.values)
    stats_size = tools.Statistics(len)
    mstats = tools.MultiStatistics(fitness=stats_fit, size=stats_size)
    mstats.register("avg", numpy.mean)
    mstats.register("std", numpy.std)
    mstats.register("min", numpy.min)
    mstats.register("max", numpy.max)
    pop, log = algorithms.eaMuPlusLambda(pop, toolbox, nu/2, nu/2, 0.85, 0.15, 200,stats=mstats,
                                   halloffame=hof, verbose=True)

    # print log
    return pop, log, hof

if __name__ == "__main__":
    main()

预先感谢您的帮助。

Python版本:2.7

编辑: 在提出如何解决问题的建议后,我在 DEAP 突变库中添加了一些“打印”,以更好地理解正在发生的情况。根据原始问题,这是相同的错误,但有一些额外的信息:

individual is  not_(ARG7)
individual[i] is  <deap.gp.Primitive object at 0x10746c158>
(not individual[i]) is  False
type(individual[i]) is  <class 'deap.gp.Primitive'>
type(individual[i])(not individual[i]) is 
Traceback (most recent call last):
  File "Genetic_Programming.py", line 98, in <module>
    main()
  File "Genetic_Programming.py", line 92, in main
    halloffame=hof, verbose=True)
  File "/Users/giorgio/anaconda/lib/python2.7/site-packages/deap/algorithms.py", line 317, in eaMuPlusLambda
    offspring = varOr(population, toolbox, lambda_, cxpb, mutpb)
  File "/Users/giorgio/anaconda/lib/python2.7/site-packages/deap/algorithms.py", line 235, in varOr
    ind, = toolbox.mutate(ind)
  File "/Users/giorgio/anaconda/lib/python2.7/site-packages/deap/tools/mutation.py", line 136, in mutFlipBit
    print "type(individual[i])(not individual[i]) is ", type(individual[i])(not individual[i])
TypeError: __init__() takes exactly 4 arguments (2 given)

再次感谢您的贡献

最佳答案

该错误提示您正在尝试使用 deap.tools.mutFlipBit 函数作为作为 deap.gp.PrimitiveTree 实例的个体的更改器(mutator)。来自 mutFlipBit 的文档:

The individual is expected to be a sequence and the values of the attributes shall stay valid after the not operator is called on them.

因此,如果代码决定改变 individual 的元素 i,它会尝试评估 deap.dp.Primitive(不是 ind[i]) 。该错误提示 Primitive 的构造函数采用 4 个参数,self, name, args, ret 而不是传递的 self(不是 ind[1]) .

错误的原因有两个,

  1. mutBitFlip 更改器(mutator)应用于由“符号值”和“运算符”列表组成的个体,而不是列表符合预期的 bool 值。因此代码可以尝试否定运算符,例如翻转,未定义。但是,该代码将产生 False,因为对象在 bool 上下文中被评估为 True,并且最终会尝试创建一个新的 Primitive来自一个 bool 值的参数。

  2. 即使 mutFlipBit 函数可以区分 Primitive和一个Terminal ,并且只会尝试否定 Terminaldeap 将使用符号终端,因为 PrimitiveTree 的主要目标> 不是找到一个等价于某个值(即常量)的单个表达式,而是找到一个带有参数的表达式,相当于一个函数。

您应该重新审视您想要发展的内容,即映射到 bool 方程的表达式或 bool 函数的一组参数。并在此基础上重新设计您的代码。

初步答案:

您的代码不完整,因为未显示 offspring = varOr(population, toolbox, lambda_, cxpb, mutpb) 行。

但是,问题是由 population 变量中的某个个体的类型引起的。该代码假设您的个体是 bool 值列表,因此代码 individual[i] = type(individual[i])(not individual[i]) 可以工作:

x = True
print type(x)(not x)  # Equivalent of bool(True) => False

该错误表明,type(individual[i]) 获取了需要 3 个参数的类的 init,例如self + 其他 3 个参数。

关于python - Python DEAP mutFlipBit 的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34077888/

相关文章:

javascript - 如何计算神经网络的输出?

java - 进程分配的遗传算法

javascript - child 变异一个 Vue Prop 有多危险?

vuex - "vue js dev tools"测试版如何记录突变和 Action ?

python - 来自字符串列表的子数组

python - 如何在 SHAP 汇总图上绘制特定特征?

python - 将列表列表的输出格式化为列

python - 如何在 Django 服务器启动时打印 ascii 横幅?

genetic-algorithm - 遗传算法中的最优种群规模、变异率和交配率

r - 遗传算法 - 交叉和变异无法正常工作