1

我从 Python 中的 DEAP 开始,我假装实现一个 GA 来解决TSP 问题

我想知道是否可以创建一个城市名称(字符串)作为个人的列表。例如,一个人可以是:["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)
4

1 回答 1

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']]
于 2017-11-22T08:42:54.490 回答