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()




posted @ 2017-10-16 20:59  FontTian  阅读(200)  评论(0编辑  收藏  举报