CODE组合差分进化算法(python实现)

一、 概述:

差分进化算法(Differential Evolution,DE)由Storn和Price于1995年首次提出。主要用于求解实数优化问题。该算法是一类基于群体的自适应全局优化算法,属于演化算法的一种,由于其具有结构简单、容易实现、收敛快速、鲁棒性强等特点,因而被广泛应用在数据挖掘、模式识别、数字滤波器设计、人工神经网络、电磁学等各个领域。1996年在日本名古屋举行的第一届国际演化计算(ICEO)竞赛中,差分进化算法被证明是速度最快的进化算法

二、算法流程

其具体进化流程如下:
(1)确定差分进化算法控制参数,确定适应度函数。差分进化算法控制参数包括:种群大小NP、缩放因子F与杂交概率CR。
(2)随机产生初始种群。
(3)对初始种群进行评价,即计算初始种群中每个个体的适应度值。
(4)判断是否达到终止条件或进化代数达到最大。若是,则终止进化,将得到最佳个体作为最优解输出;若否,继续。
(5)进行变异和交叉操作,得到中间种群。
(6)在原种群和中间种群中选择个体,得到新一代种群。
(7)进化代数g=g+1,转步骤(4).

三、 经典差分进化算法:

此处可看经典差分进化算法

四、组合差分进化算法代码部分

import random
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm


# 计算f(x) = x_1**2+x_2**2+x_3**2+...+x_30**2 的最小值, -100

class CoDE(object):
    def __init__(self):
        self.Max_epoch = 2000  # 最大迭代次数
        self.F_CR_pool = [(1.0, 0.1), (1.0, 0.9), (0.8, 0.2)]
        self.population_size = 40

        self.Min = -100
        self.Max = 100
        self.dim = 30
        self.population = np.array(
            [[random.random() * (self.Max - self.Min) + self.Min for i in range(self.dim)] for j in
             range(self.population_size)])
        print(self.population)
        # 初始化种群
        self.fig = None
        self.ax = None

    # 选择操作
    def choose(self, pX_ori, pU_new):
        if np.min(self.cal_fitness(pX_ori)) < np.min(self.cal_fitness(pU_new)):
            return pX_ori
        else:
            return pU_new

    # 变异操作,交叉操作
    def mutation_cross1(self, F_CR):
        F, CR = F_CR[0], F_CR[1]
        V = np.zeros_like(self.population)
        # 每次选三个随机变异
        for i in range(self.population_size):
            xr1_index, xr2_index, xr3_index = random.sample(list(range(self.population_size)), 3)
            V[i, :] = self.population[xr1_index, :] + F * (
                    self.population[xr2_index, :] - self.population[xr3_index, :])
            for j in range(len(V[i, :])):
                if V[i, j] < self.Min or V[i, j] > self.Max:
                    V[i, j] = random.random() * (self.Max - self.Min) + self.Min
        for i in range(V.shape[0]):
            for j in range(V.shape[1]):
                if random.random() < CR:
                    V[i, j] = self.population[i, j]
        return V

    def mutation_cross2(self, F_CR):
        F, CR = F_CR[0], F_CR[1]
        V = np.zeros_like(self.population)
        # 每次选五个随机变异
        for i in range(self.population_size):
            xr1_index, xr2_index, xr3_index, xr4_index, xr5_index = random.sample(list(range(self.population_size)), 5)
            V[i, :] = self.population[xr1_index, :] + F * (
                    self.population[xr2_index, :] - self.population[xr3_index, :]) + F * (
                              self.population[xr4_index, :] - self.population[xr5_index, :])
            for j in range(len(V[i, :])):
                if V[i, j] < self.Min or V[i, j] > self.Max:
                    V[i, j] = random.random() * (self.Max - self.Min) + self.Min
        for i in range(V.shape[0]):
            for j in range(V.shape[1]):
                if random.random() < CR:
                    V[i, j] = self.population[i, j]
        return V

    def mutation_cross3(self, F_CR):
        F, CR = F_CR[0], F_CR[1]
        V = np.zeros_like(self.population)
        # 每次选三个随机变异
        for i in range(self.population_size):
            xr1_index, xr2_index, xr3_index = random.sample(list(range(self.population_size)), 3)
            V[i, :] = self.population[i, :] + F * (
                    self.population[xr1_index, :] - self.population[i, :]) + F * (
                              self.population[xr2_index, :] - self.population[xr3_index, :])
            for j in range(len(V[i, :])):
                if V[i, j] < self.Min or V[i, j] > self.Max:
                    V[i, j] = random.random() * (self.Max - self.Min) + self.Min
        for i in range(V.shape[0]):
            for j in range(V.shape[1]):
                if random.random() < CR:
                    V[i, j] = self.population[i, j]
        return V

    def cross_mutation(self):
        # 初始化产生种群
        best_V = np.zeros_like(self.population)
        # 选择最好的策略
        V1 = self.mutation_cross1(self.F_CR_pool[random.randint(0, 2)])
        V2 = self.mutation_cross2(self.F_CR_pool[random.randint(0, 2)])
        V3 = self.mutation_cross3(self.F_CR_pool[random.randint(0, 2)])
        best_V = self.select_best((V1, V2, V3, self.population))
        return best_V

    def select_best(self, list_p):
        best_p = list_p[0]
        for p in list_p:
            best_p = self.choose(best_p, p)
        return best_p

    def func(self, p, dim=0):
        return np.sum(p ** 2, axis=dim, keepdims=True)

    # 计算适应度
    def cal_fitness(self, population=None, dim=1):
        if population is None:
            population = self.population

        return self.func(population, dim=dim)

    # 总体程序实现
    def run(self):
        best_fit = []
        for epoch in range(self.Max_epoch):
            # plt.cla()
            V = self.cross_mutation()
            # U = self.cross(self.population, V)
            # Good = self.cmp_fitness(self.population, V)
            # self.population = Good
            # # self.show_result()
            # # plt.pause(0.1)
            self.population = V
            best_fit.append(min(self.cal_fitness(V, dim=1)))
        plt.xlabel('epoch')
        plt.ylabel('fitness')
        plt.plot(best_fit)
        plt.show()

        print(self.population)
        print('fitness')
        print(self.cal_fitness(dim=1))

        # self.show_result()
        # plt.ioff()
        # plt.show()

    def show_result(self):
        self.ax.scatter(self.population[0, :], self.population[1, :], self.cal_fitness(), color='black',
                        label='population_point')
        x1 = np.arange(self.Min, self.Min, 0.25)
        x2 = np.arange(self.Min, self.Max, 0.25)
        x1, x2 = np.meshgrid(x1, x2)
        z = np.array(self.cal_fitness(np.array([x1, x2])))
        self.ax.plot_surface(x1, x2, z, cmap=cm.coolwarm)
        self.ax.legend()


if __name__ == '__main__':
    de = CoDE()
    de.run()

如果觉得写得好,复制的时候请点个赞吧!

点个赞
点个赞
点个赞
点个赞
点个赞
点个赞
重要的事情说六遍!

如果你是为了完成作业可以复制完再慢慢理解。

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