需要优化的目标函数
1 2
| def target(nparray): return nparray[0]**2 + nparray[1]**2 + nparray[2]**2
|
初始化条件
1 2 3 4 5 6 7
| N = 30 D = 3 M = 1000 c1 = 0.5 c2 = 0.5 w = 0.6
|
初始化每个粒子的位置和速度
1 2 3 4 5 6 7 8 9 10 11 12 13
| 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 2 3 4
| for i in range(N): P[i] = target(X[i]) y[i] = 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]
|
array([ 9.74182970e-163, -1.51205792e-162, -5.62277013e-163])
0.0