人工智能粒子群算法简易版

头歌人工智能平台下的粒子群算法集锦,以下是本人对算法的补充

"""
1.速度更新公式
new_v = w*v + c1 * rand() * (pbest - position) + c2 * rand() * (gbest-position)

    v为粒子当前的速度,w为惯性因子(有速度就有运动惯性)。rand()为随机数生成函数,能够生成0-1之间的随机数。
    position为粒子当前的位置,pbest为本粒子历史上最好的位置,gbest为种群中所有粒子中当前最好的位置。c1和c2表示学习因子
    分别向本粒子历史最好位置和种群中当前最好位置进行学习。
2.位置更新公式
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]
    # ********** End **********#
    return v, P

## 全局最优的寻找
def g_best(P,gbest,globalBestCost):
    # 在各个局部最优中找到全局最优
    # ********** Begin **********#
    for i in range(N):
        if get_fitness(P[i]) < get_fitness(gbest):
            gbest = P[i]
    globalBestCost.append(get_fitness(gbest))
    # ********** 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]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值