粒子群算法PSO python简单实现

import random

# y= -(400-x)*(400-x)+160000的最大值
# 初始化种群
def creat(number, min_pos, max_pos):
    population = []
    for i in range(number):
        population.append([])# 定义一个二维数组
    for i in range(number): # 四个参数:当前位置,速度,适应度,个体最优解
        population[i].append(random.randint(min_pos, max_pos))
        population[i].append(0)
        population[i].append(0)
        population[i].append(random.randint(min_pos, max_pos))
    return population
# 适应度计算
def fitness(population, number):
    for i in range(number):
        y = -(400-population[i][0])*(400-population[i][0])+160000
        population[i][2] = y
    return population
# 速度改变
# v_next = wv_old +  c1r1(pbest - x_old) +  c2r2(gbest - x_old)
def speep_change(population, w, r1, r2, number, speed_limit):
    gbest = 0
    temp = 0
    for i in range(number):
        if temp < population[i][2]:
                temp = population[i][2] # 通过最有适应度找到个体
                gbest = population[i][0] # 找到群体最优解
    # print(gbest)
    for i in range(number):
        c1 = random.random()
        c2 = random.random()
        v_next = w*population[i][1] + c1*r1*(population[i][3] - population[i][0]) + c2*r2*(gbest - population[i][0])
        if v_next > speed_limit:
            v_next = speed_limit
        if v_next < -speed_limit:
            v_next = -speed_limit
        population[i][1] = v_next
    return population
# 位置改变
def loc_change(population, number):
    for i in range(number):
        population[i][0] = population[i][0] + population[i][1]
    return population

number = 20
min_pos = 0
max_pos = 1000
w = r1 = r2 = 1
train_times = 200
speed_limit = 0.2*(max_pos - min_pos)
population = creat(number, min_pos, max_pos)
for i in range(train_times):
    population = fitness(population, number)
    population = speep_change(population, w, r1, r2, number, speed_limit)
    population = loc_change(population, number)
    # print(population)
population = fitness(population, number)
print(population)
best = 0
temp = 0
for i in range(number):
    if temp < population[i][2]:
            temp = population[i][2]
            best = population[i][0]
print(best)

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值