import numpy as np
# 目标函数
def objective_function(x):
return x ** 2
# 模拟退火算法主函数
def simulated_annealing(initial_solution, initial_temperature, cooling_rate, max_iter):
current_solution = initial_solution
current_energy = objective_function(current_solution)
best_solution = current_solution
best_energy = current_energy
temperature = initial_temperature
for _ in range(max_iter):
new_solution = current_solution + np.random.uniform(-1, 1)
new_energy = objective_function(new_solution)
if new_energy < current_energy or np.random.rand() < np.exp((current_energy - new_energy) / temperature):
current_solution = new_solution
current_energy = new_energy
if new_energy < best_energy:
best_solution = new_solution
best_energy = new_energy
temperature *= cooling_rate
return best_solution
# 运行模拟退火算法
best_solution = simulated_annealing(initial_solution=5, initial_temperature=100, cooling_rate=0.95, max_iter=1000)
print("模拟退火算法找到的最优解:", best_solution)
1. 三种启发式算法的示例代码:遗传算法、粒子群算法、退火算法
2. 学习优化算法的思路(避免浪费无效时间)
作业:今天以自由探索的思路为主,尝试检索资料、视频、文档,用尽可能简短但是清晰的语言看是否能说清楚这三种算法每种算法的实现逻辑,帮助更深入的理解。
遗传
import numpy as np
# 目标函数
def fitness_function(x):
return x ** 2
# 初始化种群
def initialize_population(pop_size, gene_length):
return np.random.randint(0, 2, size=(pop_size, gene_length))
# 解码染色体
def decode_chromosome(chromosome):
decimal_value = 0
power = len(chromosome) - 1
for gene in chromosome:
decimal_value += gene * (2 ** power)
power -= 1
return decimal_value
# 选择操作
def selection(population, fitness_values):
total_fitness = np.sum(fitness_values)
probabilities = fitness_values / total_fitness
indices = np.random.choice(len(population), size=len(population), p=probabilities)
return population[indices]
# 交叉操作
def crossover(parent1, parent2):
crossover_point = np.random.randint(1, len(parent1))
child1 = np.concatenate((parent1[:crossover_point], parent2[crossover_point:]))
child2 = np.concatenate((parent2[:crossover_point], parent1[crossover_point:]))
return child1, child2
# 变异操作
def mutation(chromosome, mutation_rate):
for i in range(len(chromosome)):
if np.random.rand() < mutation_rate:
chromosome[i] = 1 - chromosome[i]
return chromosome
# 遗传算法主函数
def genetic_algorithm(pop_size, gene_length, generations, mutation_rate):
population = initialize_population(pop_size, gene_length)
for _ in range(generations):
fitness_values = np.array([fitness_function(decode_chromosome(chromosome)) for chromosome in population])
new_population = selection(population, fitness_values)
children = []
for i in range(0, pop_size, 2):
child1, child2 = crossover(new_population[i], new_population[i + 1])
child1 = mutation(child1, mutation_rate)
child2 = mutation(child2, mutation_rate)
children.extend([child1, child2])
population = np.array(children)
best_chromosome = population[np.argmax([fitness_function(decode_chromosome(chromosome)) for chromosome in population])]
return decode_chromosome(best_chromosome)
# 运行遗传算法
best_solution = genetic_algorithm(pop_size=100, gene_length=5, generations=100, mutation_rate=0.01)
print("遗传算法找到的最优解:", best_solution)
退火
import numpy as np
# 目标函数
def fitness_function(x):
return x ** 2
# 初始化种群
def initialize_population(pop_size, gene_length):
return np.random.randint(0, 2, size=(pop_size, gene_length))
# 解码染色体
def decode_chromosome(chromosome):
decimal_value = 0
power = len(chromosome) - 1
for gene in chromosome:
decimal_value += gene * (2 ** power)
power -= 1
return decimal_value
# 选择操作
def selection(population, fitness_values):
total_fitness = np.sum(fitness_values)
probabilities = fitness_values / total_fitness
indices = np.random.choice(len(population), size=len(population), p=probabilities)
return population[indices]
# 交叉操作
def crossover(parent1, parent2):
crossover_point = np.random.randint(1, len(parent1))
child1 = np.concatenate((parent1[:crossover_point], parent2[crossover_point:]))
child2 = np.concatenate((parent2[:crossover_point], parent1[crossover_point:]))
return child1, child2
# 变异操作
def mutation(chromosome, mutation_rate):
for i in range(len(chromosome)):
if np.random.rand() < mutation_rate:
chromosome[i] = 1 - chromosome[i]
return chromosome
# 遗传算法主函数
def genetic_algorithm(pop_size, gene_length, generations, mutation_rate):
population = initialize_population(pop_size, gene_length)
for _ in range(generations):
fitness_values = np.array([fitness_function(decode_chromosome(chromosome)) for chromosome in population])
new_population = selection(population, fitness_values)
children = []
for i in range(0, pop_size, 2):
child1, child2 = crossover(new_population[i], new_population[i + 1])
child1 = mutation(child1, mutation_rate)
child2 = mutation(child2, mutation_rate)
children.extend([child1, child2])
population = np.array(children)
best_chromosome = population[np.argmax([fitness_function(decode_chromosome(chromosome)) for chromosome in population])]
return decode_chromosome(best_chromosome)
# 运行遗传算法
best_solution = genetic_algorithm(pop_size=100, gene_length=5, generations=100, mutation_rate=0.01)
print("遗传算法找到的最优解:", best_solution)
粒子群
import numpy as np
# 目标函数
def fitness_function(x):
return np.sum(x ** 2)
# 粒子群算法主函数
def particle_swarm_optimization(num_particles, dimensions, max_iter, w, c1, c2):
particles = np.random.uniform(-10, 10, size=(num_particles, dimensions))
velocities = np.random.uniform(-1, 1, size=(num_particles, dimensions))
personal_best_positions = particles.copy()
personal_best_fitness = np.array([fitness_function(p) for p in particles])
global_best_index = np.argmin(personal_best_fitness)
global_best_position = personal_best_positions[global_best_index]
global_best_fitness = personal_best_fitness[global_best_index]
for _ in range(max_iter):
for i in range(num_particles):
r1, r2 = np.random.rand(2)
velocities[i] = (w * velocities[i] +
c1 * r1 * (personal_best_positions[i] - particles[i]) +
c2 * r2 * (global_best_position - particles[i]))
particles[i] += velocities[i]
fitness = fitness_function(particles[i])
if fitness < personal_best_fitness[i]:
personal_best_fitness[i] = fitness
personal_best_positions[i] = particles[i]
if fitness < global_best_fitness:
global_best_fitness = fitness
global_best_position = particles[i]
return global_best_position
# 运行粒子群算法
best_solution = particle_swarm_optimization(num_particles=50, dimensions=2, max_iter=100, w=0.5, c1=1.5, c2=1.5)
print("粒子群算法找到的最优解:", best_solution)
@浙大疏锦行