如何在DEAP Python中创建个人城市列表?

时间:2017-11-22 08:15:22

标签: python genetic-algorithm deap

我从Python开始使用DEAP,我假装实现一个GA来解决TSP problem

我想知道是否可以创建一个名为city(Strings)的列表作为Individual。例如,个人可以是:["Madrid","Paris","London","Rome"]

此时,我用整数代表城市:

creator.create("Individual", list, fitness=creator.FitnessMin)

    IND_SIZE=8

    toolbox = base.Toolbox()
    toolbox.register("indices", random.sample, range(IND_SIZE), IND_SIZE) 
    toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.indices)

1 个答案:

答案 0 :(得分:1)

我找到了一种可行的方法。我声明了一个新函数,如下所示:

def generate_individual():
    return ["Almeria","Cadiz","Cordoba","Granada","Huelva","Jaen","Malaga", "Seville"]

申报个人:

toolbox = base.Toolbox()
toolbox.register("indices", generate_individual) # Gen, in this case, a number which represents a city.
toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.indices) # Define a route of cities. A chromosome.
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
POP_SIZE = 50
pop = toolbox.population(n=POP_SIZE)

输出如下:

[['Almeria', 'Cadiz', 'Cordoba', 'Granada', 'Huelva', 'Jaen', 'Malaga', 'Seville'], ..., ['Almeria', 'Cadiz', 'Cordoba', 'Granada', 'Huelva', 'Jaen', 'Malaga', 'Seville']]