手推差分进化算法(多目标函数)

import numpy as np
import time


# 定义目标函数(这里以一个简单的二维函数为例)
def objective_function(x):
    return x[0] ** 2 + x[1] ** 2


# 差分进化算法
def differential_evolution(objective_function, bounds, population_size=100, max_generations=50, crossover_rate=0.7,
                           mutation_factor=0.5):
    dimension = len(bounds)
    best_solution = float('inf')

    # 初始化种群
    population = np.random.rand(population_size, dimension)
    # population = bounds[:, 0] + population * (bounds[:, 1] - bounds[:, 0])

    for generation in range(max_generations):
        for i in range(population_size):
            # 随机选择三个不同的个体
            candidates = [index for index in range(population_size) if index != i]
            selected_indices = np.random.choice(candidates, 3, replace=False)
            a, b, c = population[selected_indices]

            # 生成变异个体
            mutant = a + mutation_factor * (b - c)

            # 交叉操作
            crossover_mask = np.random.rand(dimension) < crossover_rate
            trial_vector = np.where(crossover_mask, mutant, population[i])

            # 评估目标函数
            if objective_function(trial_vector) < objective_function(population[i]):
                population[i] = trial_vector

        # 输出当前代的最优解
        best_index = np.argmin([objective_function(individual) for individual in population])
        best_solution = population[best_index]
        # print(
        #     f"Generation {generation + 1}, Best Solution: {best_solution}, Best Objective Value: {objective_function(best_solution)}")

    return best_solution


# 定义搜索空间范围
start = time.time()
bounds = np.array([[-10, 10], [-10, 10]])

# 运行差分进化算法
best_solution = differential_evolution(objective_function, bounds)

# print("\nOptimization Result:")
print(f"Best Solution: {best_solution}")
print(f"Best Objective Value: {objective_function(best_solution)}")
print("time", time.time() - start)

你可能感兴趣的:(算法,算法,python)