# -*- coding: utf-8 -*-
"""
Created on Wed Jul 14 18:00:24 2021
@author: pony
"""
import numpy as np
#设置参数
w = 0.8 #惯性因子
c1 = 2 #自身认知因子
c2 = 2 #社会认知因子
r1 = 0.6 #自身认知学习率
r2 = 0.3 #社会认知学习率
pN = 50 #粒子数量
dim = 1 #搜索维度
max_iter = 300 #最大迭代次数
#定义适应度函数
def get_fitness(x):
y = -x**2 + 20*x + 10
return y
#初始化粒子群
X = np.zeros((pN, dim)) #初始粒子的位置和速度
V = np.zeros((pN, dim))
p_best = np.zeros((pN, dim), dtype = float) #粒子历史最佳位置
g_best = np.zeros((1, dim), dtype = float) #全局最佳位置
p_bestfit = np.zeros(pN) #每个个体的历史最佳适应值
g_bestfit = -1e15 #全局最佳适应值
for i in range(pN):
#初始化每一个粒子的位置和速度
X[i] = np.random.uniform(0,5,[1, dim])
V[i] = np.random.uniform(0,5,[1, dim])
p_best[i] = X[i] #初始化历史最佳位置
p_bestfit[i] = get_fitness(X[i]) #得到对应的fit值
if p_bestfit[i] > g_bestfit:
g_bestfit = p_bestfit[i]
g_best = X[i] #得到全局最佳
#迭代更新粒子群
fitness = [] #计算适应度
for _ in range(max_iter):
for i in range(pN): #更新g_best\p_best
temp = get_fitness(X[i]) #获得当前位置的适应值
if temp > p_bestfit[i]: #更新个体最优
p_bestfit[i] = temp
p_best[i] = X[i]
if p_bestfit[i] > g_bestfit: #更新全局最优
g_best = X[i]
g_bestfit = p_bestfit[i]
for i in range(pN): #更新权重
V[i] = w*V[i] + c1*r1*(p_best[i] - X[i]) + c2*r2*(g_best - X[i])
X[i] = X[i] + V[i]
fitness.append(g_bestfit)
print(g_best, g_bestfit)
12-05
4191
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)