【智能优化算法及代码例】粒子群算法

部分算法解释

本粒子群优化算法完整的算法流程解释下载链接
【智能优化算法及代码例】粒子群算法_第1张图片

全局最优适应度值寻优结果

【智能优化算法及代码例】粒子群算法_第2张图片

完整代码

# -*- coding:utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import math

def getweight():
    # print("\n")
    # print(" ========== func ============= ")
    # 惯性权重
    weight = 1
    return weight

def getlearningrate():
    # print("\n")
    # print(" ========== func ============= ")
    # 分别是粒子的个体和社会的学习因子,也称为加速常数
    lr = (0.49445,1.49445)
    return lr

def getmaxgen():
    # print("\n")
    # print(" ========== func ============= ")
    # 最大迭代次数 300
    maxgen = 300
    return maxgen

def getsizepop():
    # print("\n")
    # print(" ========== func ============= ")
    # 种群规模 50
    sizepop = 50
    return sizepop

def getrangepop():
    # print("\n")
    # print(" ========== func ============= ")
    # 粒子的位置的范围限制,x、y方向的限制相同
    # rangepop 为元组
    rangepop = (-2*math.pi , 2*math.pi) #  (-6.283185307179586, 6.283185307179586)
    #rangepop = (-2pi,2pi)
    return rangepop

def getrangespeed():
    # print("\n")
    # print(" ========== func ============= ")
    # 粒子的速度范围限制
    rangespeed = (-0.5,0.5)
    return rangespeed

# 计算适应度值
def func(x):
    # print("\n")
    # print(" ========== func =============")
    # x输入粒子位置
    # y 粒子适应度值
    # print("x:\n",x)
    # 适应度值计算函数
    if (x[0]==0)&(x[1]==0):
        # print("x[0]:\n",x[0])
        # print("x[1]:\n",x[1])
        y = np.exp((np.cos(2*np.pi*x[0])+np.cos(2*np.pi*x[1]))/2)-2.71289
        # print("y:\n",y)
    else:
        y = np.sin(np.sqrt(x[0]**2+x[1]**2))/np.sqrt(x[0]**2+x[1]**2)+np.exp((np.cos(2*np.pi*x[0])+np.cos(2*np.pi*x[1]))/2)-2.71289
        # print("y:\n",y)
    return y

def initpopvfit(sizepop):
    # print("\n")
    # print(" =============initpopvfit============== ")
    # sizepop = 50
    # pop 是一个粒子,pop中的每一行都是一个微粒
    pop = np.zeros((sizepop,2)) # 0 矩阵,50 * 2
    # print("pop:\n", pop)
    v = np.zeros((sizepop,2)) # 0 矩阵,50 * 2
    # print("v:\n", v)
    fitness = np.zeros(sizepop)
    # print("fitness.shape:\n",fitness.shape)
    # print("fitness:\n", fitness)

    for i in range(sizepop):
        # print("rangepop:\n",rangepop) # 元组
        # print("rangepop[0]:",rangepop[0]) # 元组的第一个数
        # print("rangepop[1]:",rangepop[1]) # 元组的第二个数
        # print("np.random.rand():",np.random.rand()) # 随机一个数
        pop[i] = [(np.random.rand()-0.5)*rangepop[0]*2,(np.random.rand()-0.5)*rangepop[1]*2]
        # print("i:",i,"pop[i]:\n", pop[i])
        v[i] = [(np.random.rand()-0.5)*rangespeed[0]*2,(np.random.rand()-0.5)*rangespeed[1]*2]
        # print("i:",i,"v[i]:\n", v[i])
        fitness[i] = func(pop[i]) # pop[i] 为 x 的值
        # print("i:",i,"fitness[i]:\n", fitness[i])
    return pop,v,fitness

def getinitbest(fitness,pop):
    # 群体最优的粒子位置及其适应度值
    # print("\n")
    # print(" ============ getinitbest ============ ")
    # print("群体最优的粒子位置及其适应度值")
    # print("fitness:\n",fitness)
    gbestpop,gbestfitness = pop[fitness.argmax()].copy(),fitness.max()
    # print("全局最优位置:\n",gbestfitness)
    #个体最优的粒子位置及其适应度值,使用copy()使得对pop的改变不影响pbestpop,pbestfitness类似
    pbestpop,pbestfitness = pop.copy(),fitness.copy()

    return gbestpop,gbestfitness,pbestpop,pbestfitness  

# ++++++++ 1、自定义参数:+++++++++
# 惯性权重
w = getweight() # w1: 1
# print("w1:",w)
# 分别是粒子的个体和社会的学习因子,也称为加速常数
lr = getlearningrate()  # lr: (0.49445, 1.49445)
# print("lr:",lr)
# 最大迭代次数
maxgen = getmaxgen() # maxgen: 300 ,即会产生 300 个粒子
# print("maxgen:",maxgen)
# 种群规模
sizepop = getsizepop() # 50
# print("sizepop:",lr)
# 粒子的位置的范围限制,x、y方向的限制相同
rangepop = getrangepop() # rangepop: (-6.283185307179586, 6.283185307179586)
# print(rangepop)
# print("rangepop:",rangepop)
# 粒子的速度范围限制
rangespeed = getrangespeed() # rangespeed: (-0.5, 0.5)
# print("rangespeed:",rangespeed)

# ++++++++++ 2、初始化粒子的位置pop、速度v、适应度值fitness +++++++++++
# pop 存储粒子的位置,v 为粒子速度,fitness 为适应度值
pop,v,fitness = initpopvfit(sizepop)  # 初始化 pop ,
# print("pop:\n",pop)
# print("v:\n",v)
# print("fitness:\n",fitness)
# +++++++++++ 3、计算全局最优位置,全局最优适应度值,局部最优位置,局部最优适应度值 ++++++++
gbestpop,gbestfitness,pbestpop,pbestfitness = getinitbest(fitness,pop)

result = np.zeros(maxgen)
for i in range(maxgen):
    t=0.5
    #速度更新
    # print("\n")
    # print(" ========== 速度更新 ============= ")
    for j in range(sizepop):
        v[j] += lr[0]*np.random.rand()*(pbestpop[j]-pop[j])+lr[1]*np.random.rand()*(gbestpop-pop[j])
    v[v<rangespeed[0]] = rangespeed[0]
    v[v>rangespeed[1]] = rangespeed[1]

    #粒子位置更新
    # print("\n")
    # print(" ========== 粒子位置更新 ============= ")
    for j in range(sizepop):
        #pop[j] += 0.5*v[j]
        pop[j] = t*(0.5*v[j])+(1-t)*pop[j]
        # print("j:",j,"pop[j]:\n",pop[j])
    pop[pop<rangepop[0]] = rangepop[0]
    pop[pop>rangepop[1]] = rangepop[1]
    # print("pop:\n",pop)

    #适应度更新
    # print("\n")
    # print(" ========== 适应度更新 ============= ")
    for j in range(sizepop):
        fitness[j] = func(pop[j])
    #     print("j:",j,"fitness[j]",fitness[j])
    # print("fitness:\n",fitness)

    for j in range(sizepop):
        if fitness[j] > pbestfitness[j]:
            pbestfitness[j] = fitness[j]
            pbestpop[j] = pop[j].copy()
            # print("j:",j,"pbestfitness[j]:\n",pbestfitness[j])
            # print("j:",j,"pbestpop[j]:\n",pbestpop[j])

    if pbestfitness.max() > gbestfitness :
        gbestfitness = pbestfitness.max()
        gbestpop = pop[pbestfitness.argmax()].copy()
        # print("gbestfitness:\n", gbestfitness)
        # print("gbestpop:\n", gbestpop)

    result[i] = gbestfitness
# print(result)

plt.plot(result)
plt.show()

你可能感兴趣的:(数学与算法)