粒子群算法的Python简单实现

需要优化的目标函数

$$target = x^2+y^2+z^2$$

1
2
def target(nparray):
return nparray[0]**2 + nparray[1]**2 + nparray[2]**2

初始化条件

1
2
3
4
5
6
N = 30 #个体数量
D = 3 #目标函数的维数
M = 1000 #迭代次数
c1 = 0.5 #加速常数1
c2 = 0.5 #加速常数2
w = 0.6 #惯性因子

初始化每个粒子的位置和速度

1
2
3
4
5
6
7
8
9
10
11
import numpy as np
import random

X = np.zeros((N, D))
V = np.zeros((N, D))
y = np.zeros((N, D))

for i in range(N): #行
for j in range(D): #列
X[i][j] = random.random()
V[i][j] = random.random()

计算每个粒子的适应度

1
P = np.zeros(N) #P为个体历史最优解
1
2
3
4
for i in range(N):
P[i] = target(X[i])
y[i] = X[i]
#print(target(X[i]))

初始化pg,pg为全局最优解

1
2
3
4
pg = X[0]
for i in range(1,N):
if float(target(X[i])) < float(target(pg)):
pg = X[i]

算法主要循环

1
2
3
4
5
6
7
8
9
10
for t in range(M):
for i in range(N):
V[i] = w*V[i] + c1*random.random()*(y[i]-X[i]) + c2*random.random()*(pg-X[i])
X[i] = X[i] + V[i]
if target(X[i])<P[i]:
P[i] = target(X[i])
y[i] = X[i]
if P[i]<target(pg):
pg = y[i]
#Pbest[t] = target(pg)
1
pg
array([ 9.74182970e-163, -1.51205792e-162, -5.62277013e-163])
1
target(pg)
0.0
If you like my blog, please donate for me.