启发式算法是一类基于直观或经验构造的算法,旨在在可接受的花费下为组合优化问题提供可行解。这些算法通常不能保证找到最优解,但可以在合理的时间内得到不错的答案。启发式算法的主要应用领域包括:
- 模拟退火算法(SA):模拟退火算法借鉴了固体的退火原理,通过随机生成临域解并计算解的优劣,以概率方式接受新解,并在迭代过程中逐步降低温度,最终找到问题的近似解。
- 遗传算法(GA):遗传算法模拟生物进化过程中的遗传和变异过程,将问题的解编码为染色体(个体),并在群体中进行选择、交叉和变异等操作,通过迭代进化来逐渐找到最优解。
- 蚁群算法(ACO):蚁群算法受到自然界中真实的蚁群集体行为研究成果的启发,通过模拟蚁群的觅食行为来解决组合优化问题。
- 粒子群算法(PSO):粒子群算法是一种基于群体智能的优化算法,通过模拟鸟群觅食行为来解决组合优化问题。
- 禁忌搜索算法(TS):禁忌搜索算法是一种基于启发式搜索的优化算法,通过引入禁忌表来避免搜索过程中的重复操作,从而提高搜索效率。
启发式算法的代码示例:
- 模拟退火算法(SA):
import random
import math
def sa_optimize(func, x0, T_max, T_min, cooling_rate):
x_best = x0
f_best = func(x0)
T = T_max
while T > T_min:
x_new = x_best + random.uniform(-1, 1)
f_new = func(x_new)
if f_new < f_best:
x_best = x_new
f_best = f_new
else:
p = math.exp(-(f_new - f_best) / T)
if random.random() < p:
x_best = x_new
f_best = f_new
T *= cooling_rate
return x_best, f_best
# 示例函数
def func(x):
return x**2
# 初始值
x0 = 10
# 模拟退火参数
T_max = 100
T_min = 1e-6
cooling_rate = 0.9
x_best, f_best = sa_optimize(func, x0, T_max, T_min, cooling_rate)
print("x_best:", x_best)
print("f_best:", f_best)
- 遗传算法(GA):
import random
def ga_optimize(func, n_pop, n_gen, p_crossover, p_mutation):
def create_individual():
return [random.uniform(-10, 10) for _ in range(1)]
def crossover(parent1, parent2):
child1 = [parent1[0], parent2[1]]
child2 = [parent2[0], parent1[1]]
return child1, child2
def mutate(individual):
mutated = individual.copy()
for i in range(len(mutated)):
if random.random() < p_mutation:
mutated[i] = random.uniform(-10, 10)
return mutated
population = [create_individual() for _ in range(n_pop)]
best_individual = min(population, key=func)
for _ in