差分进化算法DE的python3实现

差分进化算法DE的python3实现

差分进化算法的内容具体看https://www.cnblogs.com/babyfei/p/9552418.html
这篇博客讲的很详细,我也用的是这篇博客里的一个测试函数。

现在还是python的初学者,参考了https://blog.csdn.net/qq_42167293/article/details/82927154这一篇,对里边的一些细节以及最后运行做了一些改动(原文效果还是很好的,只是有些地方我进行了简化)

代码

import math
import random
import numpy as np

#测试函数
def object_function(x_list):
    f = 0
    for i in range(0, len(x_list)):
        f = f + (x_list[i] ** 2 - (10 * math.cos(2 * np.pi * x_list[i])) + 10)
    return f

#参数变量集
def initpara():
    NP = 100 #种群大小
    F = 0.5
    CR = 0.3
    generation = 1000 #迭代次数
    D = 10 #决策变量的维数
    value_down_range = -5.12  #函数上下界
    value_up_range = 5.12
    return NP, F, CR, generation, D, value_down_range, value_up_range

#种群初始化
def initialtion(NP):
    np_list = []
    for i in range(0, NP):
        x_list = []
        for j in range(0, D):
            x_list.append(value_down_range + random.random() * (value_up_range - value_down_range))
        np_list.append(x_list)
    return np_list


def substract(a_list, b_list):
    new_list = []
    for i in range(len(a_list)):
        new_list.append(a_list[i] - b_list[i])
    return new_list


def add(a_list, b_list):
    new_list = []
    for i in range(len(a_list)):
        new_list.append(a_list[i] + b_list[i])
    return new_list


def multiply(a_list, b):
    new_list = []
    for i in range(len(a_list)):
        new_list.append(b * a_list[i])
    return new_list

#变异操作
def mutation(np_list):
    v_list = []
    for i in range(NP):
        r1, r2, r3 = 0, 0, 0
        while r1 == r2 or r2 == r3 or r3 == i or r1 == r3 or i == r1 or i == r2:
            r1 = random.randint(0, NP - 1)
            r2 = random.randint(0, NP - 1)
            r3 = random.randint(0, NP - 1)
        v_list.append(add(multiply(substract(np_list[r2], np_list[r3]), F), np_list[r1]))
    return v_list

#交叉操作
def crossover(v_list, np_list):
    u_list = []
    for i in range(NP):
        uu_list = []
        jrand = random.randint(0, D - 1)
        r = random.random()
        for j in range(D):
            if r <= CR or j == jrand:
                uu_list.append(v_list[i][j])
            else:
                uu_list.append(np_list[i][j])
        u_list.append(uu_list)
    return u_list

#选择操作
def selection(u_list, np_list):
    for i in range(NP):
        if object_function(u_list[i]) <= object_function(np_list[i]):
            np_list[i] = u_list[i]
        else:
            np_list[i] = np_list[i]
    return np_list

#算法运行
NP, F, CR, generation, D, value_down_range, value_up_range = initpara()
np_list = initialtion(NP)
for i in range(generation):
    v_list = mutation(np_list)
    u_list = crossover(v_list, np_list)
    np_list = selection(u_list, np_list)
object_function_values = [object_function(v) for v in np_list]
m = min(object_function_values)
i = object_function_values.index(m)
print('最佳个体:' + str(np_list[i]))
print('目标函数值:' + str(m))

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