如何在python中的deap包中创建一个具有不同范围内随机数的列表 [英] How can I create a list with random numbers in different ranges for deap package in python

查看:150
本文介绍了如何在python中的deap包中创建一个具有不同范围内随机数的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python中的DEAP软件包编写一个程序,专门针对遗传算法使用进化算法进行优化.

I am using DEAP package in Python to write a program for optimization with evolutionary algorithm specifically with Genetic.

我需要通过使用python中的列表类型来创建染色体.该染色体应具有五个在不同范围内的float基因(等位基因).

I need to create chromosomes by using list type in python. This chromosome should have five float genes (alleles) in different ranges.

我的主要问题是创建这样的染色体.但是,如果我可以为此使用deap包的tools.initRepeat函数会更好.

My main problem is to create such a chromosome. However, it would be better if I could use tools.initRepeat function of deap package for this.

对于所有基因都在相同范围内的情况,我们可以使用以下代码:

For the cases in which all the genes are in the same range we could use the following code:

import random

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

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

IND_SIZE=10

toolbox = base.Toolbox()
toolbox.register("attr_float", random.random)
toolbox.register("individual", tools.initRepeat, creator.Individual,
                 toolbox.attr_float, n=IND_SIZE)

我从此处得到的

推荐答案

我发现了一个很好的建议

I found a good recommendation here.

def genFunkyInd(icls, more_params):
    genome = list()
    param_1 = random.uniform(...)
    genome.append(param_1)
    param_2 = random.randint(...)
    genome.append(param_2)
    # etc...

    return icls(genome)

icls(代表单个类)参数应该接收使用创建者创建的类型,而配置范围的所有其他参数可以像more_params参数一样传递,也可以在脚本中使用定义的常量传递.这是它在工具箱中的注册方式.

The icls (standing for individual class) parameter should receive the type created with the creator, while all other parameters configuring your ranges can be passed like the more_params argument or with defined constants in your script. Here is how it is registered in the toolbox.

toolbox.register('individual', genFunkyInd, creator.Individual, more_params)

它为染色体手动创建一个类.我不知道这是否是最佳选择,但可以用来解决我的问题.

It manually creates a class for chromosome. I don't know if it is the best choice but it can be used to solve my problem.

这篇关于如何在python中的deap包中创建一个具有不同范围内随机数的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆