How can I create a list with random numbers in different ranges for deap package in python

删除回忆录丶 提交于 2019-12-24 03:25:11

问题


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

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

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)

That I got from here.


回答1:


To create individuals that have five float genes in five different ranges, you could do the following

low = [1, 0, 0, -10, 3] #lower bound for each of the ranges
high = [1234, 1024, 1, 0, 42] #upper bound for each of the ranges

functions = []
for i in range(5):
    def fun(_idx=i):
        return random.uniform(low[_idx], high[_idx])
    functions.append(fun)

toolbox.register("individual", tools.initCycle, creator.Individual,
                 functions,
                 n=1)

toolbox.individual()



回答2:


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)

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.



来源:https://stackoverflow.com/questions/42841985/how-can-i-create-a-list-with-random-numbers-in-different-ranges-for-deap-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!