Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python DEAP:使突变概率依赖于代数_Python_Genetic Algorithm_Deap - Fatal编程技术网

Python DEAP:使突变概率依赖于代数

Python DEAP:使突变概率依赖于代数,python,genetic-algorithm,deap,Python,Genetic Algorithm,Deap,我使用的是一种遗传算法,它是用Python的DEAP库实现的。为了避免过早收敛,并强制探索特征空间,我希望第一代中的变异概率较高。但为了防止它们一旦被识别就偏离极值,我希望最后几代的突变概率更低。我如何使突变概率在几代人中降低?DEAP中是否有任何内置函数来完成此操作 例如,当我注册一个变异函数时 toolbox.register('mutate', tools.mutPolynomialBounded, eta=.6, low=[0,0], up=[1,1], indpb=0.1) indp

我使用的是一种遗传算法,它是用Python的DEAP库实现的。为了避免过早收敛,并强制探索特征空间,我希望第一代中的变异概率较高。但为了防止它们一旦被识别就偏离极值,我希望最后几代的突变概率更低。我如何使突变概率在几代人中降低?DEAP中是否有任何内置函数来完成此操作

例如,当我注册一个变异函数时

toolbox.register('mutate', tools.mutPolynomialBounded, eta=.6, low=[0,0], up=[1,1], indpb=0.1)
indpb
参数是一个浮点数。如何使它成为其他函数?

听起来像是每次调用函数参数时都要对其求值的作业。我添加了一个简单的例子,修改了官方的DEAP 使突变率设置为
2/N_GENS
(只是为了说明这一点而任意选择)

请注意,Callbackproxy接收lambda,因此必须将突变率参数作为函数传递(使用完全成熟的函数或仅使用lambda)。不管怎样,结果是每次计算
indpb
参数时,都会调用这个lambda,如果lambda包含对全局变量生成计数器的引用,那么您就得到了想要的结果

#    This file is part of DEAP.
#
#    DEAP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Lesser General Public License as
#    published by the Free Software Foundation, either version 3 of
#    the License, or (at your option) any later version.
#
#    DEAP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#    GNU Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public
#    License along with DEAP. If not, see <http://www.gnu.org/licenses/>.

import random
from objproxies import CallbackProxy
import numpy

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

# Problem parameter
NB_QUEENS = 20
N_EVALS = 0
N_GENS = 1

def evalNQueens(individual):
    global N_EVALS, N_GENS
    """Evaluation function for the n-queens problem.
    The problem is to determine a configuration of n queens
    on a nxn chessboard such that no queen can be taken by
    one another. In this version, each queens is assigned
    to one column, and only one queen can be on each line.
    The evaluation function therefore only counts the number
    of conflicts along the diagonals.
    """
    size = len(individual)
    # Count the number of conflicts with other queens.
    # The conflicts can only be diagonal, count on each diagonal line
    left_diagonal = [0] * (2 * size - 1)
    right_diagonal = [0] * (2 * size - 1)

    # Sum the number of queens on each diagonal:
    for i in range(size):
        left_diagonal[i + individual[i]] += 1
        right_diagonal[size - 1 - i + individual[i]] += 1

    # Count the number of conflicts on each diagonal
    sum_ = 0
    for i in range(2 * size - 1):
        if left_diagonal[i] > 1:
            sum_ += left_diagonal[i] - 1
        if right_diagonal[i] > 1:
            sum_ += right_diagonal[i] - 1

    N_EVALS += 1
    if N_EVALS % 300 == 0:
        N_GENS += 1
    return sum_,


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

# Since there is only one queen per line,
# individual are represented by a permutation
toolbox = base.Toolbox()
toolbox.register("permutation", random.sample, range(NB_QUEENS), NB_QUEENS)

# Structure initializers
# An individual is a list that represents the position of each queen.
# Only the line is stored, the column is the index of the number in the list.
toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.permutation)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)

toolbox.register("evaluate", evalNQueens)
toolbox.register("mate", tools.cxPartialyMatched)
toolbox.register("mutate", tools.mutShuffleIndexes, indpb=CallbackProxy(lambda: 2.0 / N_GENS))
toolbox.register("select", tools.selTournament, tournsize=3)





def main(seed=0):
    random.seed(seed)

    pop = toolbox.population(n=300)
    hof = tools.HallOfFame(1)
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("Avg", numpy.mean)
    stats.register("Std", numpy.std)
    stats.register("Min", numpy.min)
    stats.register("Max", numpy.max)

    algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=1, ngen=100, stats=stats,
                        halloffame=hof, verbose=True)

    return pop, stats, hof


if __name__ == "__main__":
    main()
#此文件是DEAP的一部分。
#
#DEAP是自由软件:您可以重新发布和/或修改它
#根据GNU Lesser通用公共许可证的条款
由自由软件基金会发布的版本3
#许可证,或(由您选择)任何更高版本。
#
#分发DEAP的目的是希望它有用,
#但无任何保证;甚至没有任何关于
#适销性或适合某一特定目的。见
#GNU Lesser通用公共许可证了解更多详细信息。
#
#您应该已经收到GNU Lesser General Public的副本
#与DEAP一起获得许可证。如果没有,请参阅。
随机输入
从objproxies导入CallbackProxy
进口numpy
从deap导入算法
来自deap进口基地
来自deap导入创建者
来自deap导入工具
#问题参数
注意:皇后区=20
N_EVALS=0
N_GENS=1
def EVALNQUENS(个人):
全球N_EVALS,N_GENS
“”“n皇后问题的求值函数。”。
问题是确定n个皇后的配置
在nxn棋盘上,这样就不会有任何女王被
在这个版本中,每个皇后都被分配
到一列,并且每行只能有一个皇后。
因此,求值函数只计算数字
对角线上的冲突。
"""
尺寸=透镜(单个)
#计算与其他皇后的冲突数。
#冲突只能是对角线,在每条对角线上计数
左对角线=[0]*(2*大小-1)
右对角线=[0]*(2*大小-1)
#将每个对角线上的皇后数相加:
对于范围内的i(尺寸):
左对角[i+单个[i]]+=1
右对角[size-1-i+单个[i]]+=1
#计算每个对角线上的冲突数
和=0
对于范围内的i(2*尺寸-1):
如果左对角[i]>1:
和=左对角线[i]-1
如果右对角[i]>1:
和=右对角[i]-1
N_EVALS+=1
如果N_EVALS%300==0:
N_GENS+=1
返回和,
create(“FitnessMin”,base.Fitness,weights=(-1.0,))
creator.create(“个人”,列表,fitness=creator.FitnessMin)
#因为每条线只有一个女王,
#个体由排列表示
toolbox=base.toolbox()
工具箱寄存器(“排列”、随机样本、范围(NB_皇后)、NB_皇后)
#结构初始值设定项
#“个人”是一个列表,代表每个女王的位置。
#只存储行,列是列表中数字的索引。
注册表(“个人”,tools.initIterate,creator.individual,toolbox.permutation)
toolbox.register(“填充”,tools.initRepeat,list,toolbox.individual)
工具箱注册(“评估”,evalNQueens)
toolbox.register(“mate”,tools.cxPartialyMatched)
register(“mutate”,tools.mutshuffleIndex,indpb=CallbackProxy(lambda:2.0/N_GENS))
toolbox.register(“选择”,tools.self,tournsize=3)
def主(种子=0):
随机。种子(种子)
pop=工具箱。人口(n=300)
hof=工具。哈洛夫名称(1)
stats=tools.Statistics(lambda ind:ind.fitness.values)
统计寄存器(“平均值”,numpy.mean)
统计寄存器(“标准”,numpy.Std)
统计寄存器(“Min”,numpy.Min)
stats.register(“Max”,numpy.Max)
eaSimple(pop,工具箱,cxpb=0.5,mutpb=1,ngen=100,stats=stats,
halloffame=hof,verbose=True)
返回流行音乐,统计,霍夫
如果名称=“\uuuuu main\uuuuuuuu”:
main()

我不太确定DEAP是如何变异的,但我确信它是在您的程序中调用的,即DEAP.tools.mut(xx)。你能不能用每一代步骤减少1-prob来确定何时触发突变步骤?你怎么计算每一代有300次评估?好吧,这是一个很好的观点。我假设每一个人每一代都会被评估,但事实并非如此。更好的选择是直接从进化循环中更新全局N_GENS变量,但这需要编辑eaSimple函数或创建自己的函数。找不到更好的方法。eaSimple在运行时会在屏幕上打印出评估的数量。也许有一种方法可以访问并使用该信息?您可以将sys.stdout重新分配给一个文件,然后跟踪该文件上打印的行,尽管这听起来像是一种真正的过度使用。我只需复制eaSimple函数并进行必要的修改。