Python自定义:粒子群优化算法

Python中的粒子群算法

例子算法又被称作飞鸟觅食算法,是一种常见的现代启发式优化算法。在Python中,处于不同的情况考虑,我们都可能使用到该算法。在这里我给出三种情况下的解决方案或者替代方案。

  1. 编程练习-用Python自己实现粒子群算法,请见下文
  2. 使用该优化算法的高效版本-,我们使用Deap中的类库实现,参考Deap: 粒子群优化算法
  3. 超参数自动调参-超参数的自动调参,个人更建议使用Hyperopt代替粒子群算法,有关文章请参考本人专栏自动化的机器学习,以及相应文章如Hyperopt 入门指南或者Hyperopt中文文档导读

编程练习-用Python自己实现粒子群算法

#!usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:fonttian 
@file: 粒子群优化算法.py
@time: 2017/10/15
"""

# References from : http://blog.csdn.net/kunshanyuz/article/details/63683145

import numpy as np
import random
import matplotlib.pyplot as plt
#----------------------PSO参数设置---------------------------------
class PSO():
    def __init__(self,pN,dim,max_iter,min_bl = True):
        self.w = 0.8
        self.c1 = 2   
        self.c2 = 2   
        self.r1= 0.6
        self.r2=0.3
        self.pN = pN                #粒子数量
        self.dim = dim              #搜索维度
        self.max_iter = max_iter    #迭代次数
        self.min_bl = min              #是否为最小化适应度函数
        self.X = np.zeros((self.pN,self.dim))       #所有粒子的位置和速度
        self.V = np.zeros((self.pN,self.dim))
        self.pbest = np.zeros((self.pN,self.dim))   #个体经历的最佳位置和全局最佳位置
        self.gbest = np.zeros((1,self.dim))
        self.p_fit = np.zeros(self.pN)              #每个个体的历史最佳适应值
        self.fit = 1e10             #全局最佳适应值
        self.init_Population()      # 初始化种群
        
#---------------------目标函数Sphere函数-----------------------------
    def function(self,x):
        sum = 0
        length = len(x)
        x = x**2
        for i in range(length):
            sum += x[i]

        if self.min_bl == True:
            return sum
        else:
            return -sum
#---------------------初始化种群----------------------------------
    def init_Population(self):
        for i in range(self.pN):
            for j in range(self.dim):
                self.X[i][j] = random.uniform(0,1)
                self.V[i][j] = random.uniform(0,1)
            self.pbest[i] = self.X[i]
            tmp = self.function(self.X[i])
            self.p_fit[i] = tmp
            if(tmp < self.fit):
                self.fit = tmp
                self.gbest = self.X[i]
    
#----------------------更新粒子位置----------------------------------
    def iterator(self):
        fitness = []
        for t in range(self.max_iter):
            for i in range(self.pN):         #更新gbest\pbest
               temp = self.function(self.X[i])
               if(temp<self.p_fit[i]):      #更新个体最优
                   self.p_fit[i] = temp
                   self.pbest[i] = self.X[i]
                   if(self.p_fit[i] < self.fit):  #更新全局最优
                       self.gbest = self.X[i]
                       self.fit = self.p_fit[i]
            for i in range(self.pN):
                self.V[i] = self.w*self.V[i] + self.c1*self.r1*(self.pbest[i] - self.X[i])\
                       + self.c2*self.r2*(self.gbest - self.X[i])
                self.X[i] = self.X[i] + self.V[i]
            fitness.append(self.fit)
            # print("输出当前最优值",self.fit)                #输出最优值
        return fitness

#----------------------绘图----------------------------------
    def ShowData(self,pltarg,line=["b",3]):
        plt.figure(1)
        plt.title(pltarg[0])
        plt.xlabel("iterators", size=pltarg[1][0])
        plt.ylabel("fitness", size=pltarg[1][1])
        t = np.array([t for t in range(pltarg[2][0],pltarg[2][1])])
        fitness = np.array(self.iterator())
        plt.plot(t, self.iterator(), color=line[0], linewidth=line[1])
        plt.show()

        return self.fit

#----------------------获取数据----------------------------------
    def GetResult(self,pltarg = ["Figure1",[14,14],[0,100]] ,line = ["b",3],show_bl = True,):
        if show_bl == True:
            return self.ShowData(pltarg,line=["b",3])
        else:
            return self.iterator()

#----------------------定义参数-----------------------

pltarg = ["Figure1",[14,14],[0,100]]
line = ["b",3]

#----------------------程序执行---输出结果----------------------------------

print("全局最优值 : ",PSO(pN=30,dim=5,max_iter=100).GetResult(pltarg,line,True))

#----------------------程序执行-----------------------

# my_pso = PSO(pN=30,dim=5,max_iter=100)
# fitness = my_pso.GetResult(pltarg)

#----------------------输出结果----------------------------------

# print("全局最优值 : ",fitness)

# 原来的程序
#----------------------程序执行-----------------------
# my_pso = PSO(pN=30,dim=5,max_iter=100)
# fitness = my_pso.GetResult(pltarg)
# my_pso.init_Population()
# fitness = my_pso.iterator()

# -------------------画图--------------------
# plt.figure(1)
# plt.title("Figure1")
# plt.xlabel("iterators", size=14)
# plt.ylabel("fitness", size=14)
# t = np.array([t for t in range(0,100)])
# fitness = np.array(fitness)
# plt.plot(t,fitness, color='b',linewidth=3)
# plt.show()





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Font Tian

写的很好,请给我钱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值