使用遗传算法解决CVRP问题数据随机生成用deap库写出程序
以下是使用遗传算法解决CVRP问题的Python代码,使用deap库:
import random
from deap import base, creator, tools
# 定义问题
NUM_CUSTOMERS = 20 # 客户数量
CAPACITY = 10 # 车辆容量
MIN_COORD = 0 # 坐标最小值
MAX_COORD = 100 # 坐标最大值
CUSTOMER_DEMANDS = [random.randint(1, 5) for _ in range(NUM_CUSTOMERS)] # 客户需求量
DEPOT_COORDS = (50, 50) # 仓库坐标
# 定义遗传算法参数
POPULATION_SIZE = 50 # 种群大小
P_CROSSOVER = 0.9 # 交叉概率
P_MUTATION = 0.1 # 变异概率
MAX_GENERATIONS = 100 # 最大迭代次数
# 定义遗传算法框架
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
toolbox = base.Toolbox()
toolbox.register("attr_customer", random.randint, 0, NUM_CUSTOMERS - 1)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_customer, n=NUM_CUSTOMERS)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("mate", tools.cxOrdered)
toolbox.register("mutate", tools.mutShuffleIndexes, indpb=1.0/NUM_CUSTOMERS)
toolbox.register("select", tools.selTournament, tournsize=3)
def distance(coord1, coord2):
"""计算两点之间的距离"""
return ((coord1[0] - coord2[0])**2 + (coord1[1] - coord2[1])**2)**0.5
def evaluate(individual):
"""评估个体适应度"""
routes = []
route = [0] # 当前路线,初始为从仓库出发
current_capacity = 0 # 当前车辆容量
total_distance = 0 # 总行驶距离
# 将客户按照个体中的顺序加入路线中
for customer_index in individual:
customer_demand = CUSTOMER_DEMANDS[customer_index]
if current_capacity + customer_demand > CAPACITY:
# 如果当前车辆容量无法满足当前客户需求,则新开一辆车
route.append(0) # 先回到仓库
routes.append(route)
route = [0, customer_index]
current_capacity = customer_demand
else:
route.append(customer_index)
current_capacity += customer_demand
# 将最后一辆车的路线加入路线列表
route.append(0)
routes.append(route)
# 计算总行驶距离
for route in routes:
for i in range(1, len(route)):
distance_between_customers = distance(
(coords[route[i-1]][0], coords[route[i-1]][1]),
(coords[route[i]][0], coords[route[i]][1])
)
total_distance += distance_between_customers
return (total_distance,)
# 注册适应度评估函数
toolbox.register("evaluate", evaluate)
# 生成坐标
coords = [random.sample(range(MIN_COORD, MAX_COORD), 2) for _ in range(NUM_CUSTOMERS)]
# 生成初始种群
population = toolbox.population(n=POPULATION_SIZE)
# 开始进化
for generation in range(MAX_GENERATIONS):
# 评估种群适应度
fitnesses = list(map(toolbox.evaluate, population))
for ind, fit in zip(population, fitnesses):
ind.fitness.values = fit
# 打印最优解
best_individual = tools.selBest(population, k=1)[0]
print("Generation {}: Best distance = {}".format(generation, best_individual.fitness.values[0]))
# 选择下一代
offspring = toolbox.select(population, len(population))
# 交叉
for child1, child2 in zip(offspring[::2], offspring[1::2]):
if random.random() < P_CROSSOVER:
toolbox.mate(child1, child2)
del child1.fitness.values
del child2.fitness.values
# 变异
for mutant in offspring:
if random.random() < P_MUTATION:
toolbox.mutate(mutant)
del mutant.fitness.values
# 更新种群
population = offspring
# 打印最终结果
best_individual = tools.selBest(population, k=1)[0]
print("Best distance = {}".format(best_individual.fitness.values[0]))
print("Best route = {}".format(best_individual))
原文地址: https://www.cveoy.top/t/topic/bVje 著作权归作者所有。请勿转载和采集!