粒子群优化算法 (PSO) Python 实现:寻找函数最小值
速度更新公式
new_v = w * v + c1 * rand() * (pbest - position) + c2 * rand() * (gbest - position)
v 为粒子当前的速度,w 为惯性因子(有速度就有运动惯性)。rand() 为随机数生成函数,能够生成 0-1 之间的随机数。
position 为粒子当前的位置,pbest 为本粒子历史上最好的位置,gbest 为种群中所有粒子中当前最好的位置。c1 和 c2 表示学习因子
分别向本粒子历史最好位置和种群中当前最好位置进行学习。
位置更新公式
new_position = position + new_v * t
import random
import time
import numpy as np
# 初始参数设置
# 惯性权重
w = 0.6
# 学习因子
c1 = c2 = 1
# 空间维度
n = 1
# 粒子群数量
N = 20
# 迭代次数
iteration = 100
k0 = -10
k1 = 10
# 适应度函数设计
def get_fitness(x):
return x + 10 * np.sin(5 * x) + 7 * np.cos(4 * x)
# 第一次种群初始化
def getinitialPopulation(N):
'''
:param populationSize:种群规模
:return:
'''
chromsomes = []
for popusize in range(N):
a = random.uniform(k0, k1)
chromsomes.append(a)
return chromsomes
# 初始速度的分配
def getinitialV(P):
velocity0 = []
for v in range(0, N):
aa = 0
velocity0.append(aa)
return velocity0
# 更新(迭代的开始)
def updateV(v,P,gbest,pbest):
for i in range(0,N):
v[i] = w * v[i] + c1 * np.random.random() * (pbest[i]- P[i]) + c2 * np.random.random() * (gbest - P[i])
P[i] = P[i] + v[i]
# 边界控制
for i in range(N):
if P[i] < k0:
P[i] = k0
elif P[i]> k1:
P[i] = k1
## 最优pbest
# ********** Begin **********#
for i in range(N):
if get_fitness(P[i]) < get_fitness(pbest[i]):
pbest[i] = P[i]
## 全局最优的寻找
for i in range(N):
if get_fitness(P[i]) < get_fitness(gbest):
gbest = P[i]
globalBestCost.append(get_fitness(gbest))
# ********** End **********#
return v, P
## 全局最优的寻找
def g_best(P,gbest,globalBestCost):
# 在各个局部最优中找到全局最优
# ********** Begin **********#
# ********** End **********#
return gbest, globalBestCost
##主函数的设计
def main():
## 种群的初始化
P = getinitialPopulation(N)
gbest = 0
pbest = P.copy()
# v的初始化
velocity = getinitialV(P)
# 迭代计数器
iter = 0
iteration = 50
# 全局最优值的存储
globalBestCost = []
globalBestCost.append(get_fitness(gbest))
while iter < iteration:
## 种群的更新
velocity, P = updateV(velocity, P, gbest, pbest)
gbest, globalBestCost = g_best(P, gbest, globalBestCost)
### 更新种群中的当前最优和全局最优
iter = iter + 1
return iter,gbest,globalBestCost[-1]
原文地址: https://www.cveoy.top/t/topic/nvr4 著作权归作者所有。请勿转载和采集!