能否提供一个遗传算法在课程调度问题中的具体实现代码示例?
时间: 2024-12-20 11:17:20 浏览: 6
遗传算法是一种模拟自然选择过程的优化算法,适用于解决复杂的优化问题。在课程调度问题中,目标通常是找到一种最优的时间表安排,使得学生可以满足所有必修课和选修课的需求,并尽量避免冲突。这里给出一个简单的Python代码示例,使用DEAP库来实现遗传算法求解课程调度问题:
```python
from deap import base, creator, tools, algorithms
# 定义课程和时间表结构
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
def eval_course_conflict(individual):
# 模拟课程冲突检查函数,实际应用中需要根据具体课程时间表数据
conflicts = count_conflicts(individual)
return -conflicts, # 越少冲突,优先级越高
toolbox = base.Toolbox()
toolbox.register("individual", tools.initRepeat, creator.Individual, range(1, len(courses)+1))
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("evaluate", eval_course_conflict)
toolbox.register("mate", tools.cxTwoPoint) # 遗传操作:交叉
toolbox.register("mutate", tools.mutShuffleIndexes, indpb=0.05) # 遗传操作:突变
toolbox.register("select", tools.selTournament, tournsize=3) # 选择操作:锦标赛选择
def main():
pop = toolbox.population(n=50)
for gen in range(100): # 迭代次数
offspring = algorithms.varAnd(pop, toolbox, cxpb=0.9, mutpb=0.1)
fits = [toolbox.evaluate(i) for i in offspring]
offspring = [ind for ind, fit in zip(offspring, fits) if fit[0] < 0] + toolbox.select(offspring, len(pop))
pop[:] = offspring
best_ind = max(pop, key=lambda ind: ind.fitness.values[0])
print(f"Best individual (fitness: {best_ind.fitness.values[0]}): {best_ind}")
if __name__ == "__main__":
main()
阅读全文