遗传算法可以搜索多个执行者的任务分配,但个体通常是一份完整方案,不是一个语言模型代理。下面让两个执行者分配三件独立任务,以最大负载最小为目标,跑一个 Python 标准库实现,并用八种可能方案的穷举做对照。
编码、目标与算子
三个任务工时为 2、3、5,染色体长度 3,每个基因只能是 0 或 1,表示这件任务给执行者 0 或 1。方案 (0,0,1) 的负载是 5 和 5,目标值 5;(0,0,0) 的目标值是 10。本例假设执行者速度相同、任务不能拆、没有前后依赖。

DEAP 官方资料解释了个体、适应度以及选择、交叉、变异等职责。这里不用 DEAP API,直接写透明的小实现:锦标赛选父代,单点交叉,逐基因小概率翻转,并保留一名最佳个体。目标值越小越好,比较方向不能写反。
运行搜索,同时保留穷举基线
保存 assignment_ga.py,执行 python assignment_ga.py。固定随机种子用于复现这次演示,不代表所有问题都能找到全局最优。
import random
from itertools import product
rng = random.Random(7)
jobs = (2, 3, 5)
def cost(individual):
return max(sum(t for t, who in zip(jobs, individual) if who == a) for a in (0, 1))
population = [tuple(rng.randrange(2) for _ in jobs) for _ in range(12)]
def select():
return min(rng.sample(population, 3), key=cost)
for generation in range(20):
offspring = [min(population, key=cost)]
while len(offspring) < len(population):
father, mother = select(), select()
cut = rng.randrange(1, len(jobs))
child = father[:cut] + mother[cut:]
child = tuple(1-v if rng.random() < 0.15 else v for v in child)
offspring.append(child)
population = offspring
best = min(population, key=cost)
exact = min(product((0, 1), repeat=3), key=cost)
print("genetic:", best, cost(best), "enumerated:", exact, cost(exact))
assert cost(exact) == 5
assert cost(best) >= cost(exact)
穷举最优成本必须是 5;遗传搜索的成本应不低于穷举最优。本文脚本的断言不强行假定随机搜索永远达到最优,读者应看实际输出。遗传结果与穷举一致,只验证这个很小的实例,不是复杂调度问题的保证。
约束和结果怎么验收
检查染色体长度、每件任务恰好分给一人,以及两人负载和等于 10。若有任务依赖、不同速度或不可达执行者,要先修改目标与可行性检查,不能只加大迭代次数。交叉和变异产生不可行方案时,应采用明确修复规则或惩罚,并避免修复把所有方案变成同一个。
这只是集中搜索一个分配方案,没有各代理独立决策或强化学习更新。真实任务交付还需要列出分配清单、约束是否满足、基线成本和多随机种子结果;用找到的一次好结果宣传通用最优是不成立的。
资料与核对依据
- https://deap.readthedocs.io/en/master/tutorials/basic/part1.html
- https://deap.readthedocs.io/en/master/api/algo.html
Ai菜鸟网。发布者:AI小管家,转载请注明出处:https://www.alyyhw.com/33000.html