PSOIndividual.py

 import numpy as np
import ObjFunction
import copy class PSOIndividual: '''
individual of PSO
''' def __init__(self, vardim, bound):
'''
vardim: dimension of variables
bound: boundaries of variables
'''
self.vardim = vardim
self.bound = bound
self.fitness = 0. def generate(self):
'''
generate a rondom chromsome
'''
len = self.vardim
rnd = np.random.random(size=len)
self.chrom = np.zeros(len)
self.velocity = np.random.random(size=len)
for i in xrange(0, len):
self.chrom[i] = self.bound[0, i] + \
(self.bound[1, i] - self.bound[0, i]) * rnd[i]
self.bestPosition = np.zeros(len)
self.bestFitness = 0. def calculateFitness(self):
'''
calculate the fitness of the chromsome
'''
self.fitness = ObjFunction.GrieFunc(
self.vardim, self.chrom, self.bound)

PSO.py

 import numpy as np
from PSOIndividual import PSOIndividual
import random
import copy
import matplotlib.pyplot as plt class ParticleSwarmOptimization: '''
the class for Particle Swarm Optimization
''' def __init__(self, sizepop, vardim, bound, MAXGEN, params):
'''
sizepop: population sizepop
vardim: dimension of variables
bound: boundaries of variables
MAXGEN: termination condition
params: algorithm required parameters, it is a list which is consisting of[w, c1, c2]
'''
self.sizepop = sizepop
self.vardim = vardim
self.bound = bound
self.MAXGEN = MAXGEN
self.params = params
self.population = []
self.fitness = np.zeros((self.sizepop, 1))
self.trace = np.zeros((self.MAXGEN, 2)) def initialize(self):
'''
initialize the population of pso
'''
for i in xrange(0, self.sizepop):
ind = PSOIndividual(self.vardim, self.bound)
ind.generate()
self.population.append(ind) def evaluation(self):
'''
evaluation the fitness of the population
'''
for i in xrange(0, self.sizepop):
self.population[i].calculateFitness()
self.fitness[i] = self.population[i].fitness
if self.population[i].fitness > self.population[i].bestFitness:
self.population[i].bestFitness = self.population[i].fitness
self.population[i].bestIndex = copy.deepcopy(
self.population[i].chrom) def update(self):
'''
update the population of pso
'''
for i in xrange(0, self.sizepop):
self.population[i].velocity = self.params[0] * self.population[i].velocity + self.params[1] * np.random.random(self.vardim) * (
self.population[i].bestPosition - self.population[i].chrom) + self.params[2] * np.random.random(self.vardim) * (self.best.chrom - self.population[i].chrom)
self.population[i].chrom = self.population[
i].chrom + self.population[i].velocity def solve(self):
'''
the evolution process of the pso algorithm
'''
self.t = 0
self.initialize()
self.evaluation()
best = np.max(self.fitness)
bestIndex = np.argmax(self.fitness)
self.best = copy.deepcopy(self.population[bestIndex])
self.avefitness = np.mean(self.fitness)
self.trace[self.t, 0] = (1 - self.best.fitness) / self.best.fitness
self.trace[self.t, 1] = (1 - self.avefitness) / self.avefitness
print("Generation %d: optimal function value is: %f; average function value is %f" % (
self.t, self.trace[self.t, 0], self.trace[self.t, 1]))
while self.t < self.MAXGEN - 1:
self.t += 1
self.update()
self.evaluation()
best = np.max(self.fitness)
bestIndex = np.argmax(self.fitness)
if best > self.best.fitness:
self.best = copy.deepcopy(self.population[bestIndex])
self.avefitness = np.mean(self.fitness)
self.trace[self.t, 0] = (1 - self.best.fitness) / self.best.fitness
self.trace[self.t, 1] = (1 - self.avefitness) / self.avefitness
print("Generation %d: optimal function value is: %f; average function value is %f" % (
self.t, self.trace[self.t, 0], self.trace[self.t, 1])) print("Optimal function value is: %f; " % self.trace[self.t, 0])
print "Optimal solution is:"
print self.best.chrom
self.printResult() def printResult(self):
'''
plot the result of pso algorithm
'''
x = np.arange(0, self.MAXGEN)
y1 = self.trace[:, 0]
y2 = self.trace[:, 1]
plt.plot(x, y1, 'r', label='optimal value')
plt.plot(x, y2, 'g', label='average value')
plt.xlabel("Iteration")
plt.ylabel("function value")
plt.title("Particle Swarm Optimization algorithm for function optimization")
plt.legend()
plt.show()

运行程序:

 if __name__ == "__main__":

     bound = np.tile([[-600], [600]], 25)
pso = PSO(60, 25, bound, 1000, [0.7298, 1.4962, 1.4962])
pso.solve()

ObjFunction见简单遗传算法-python实现

粒子群优化算法-python实现的更多相关文章

  1. [Algorithm] 群体智能优化算法之粒子群优化算法

    同进化算法(见博客<[Evolutionary Algorithm] 进化算法简介>,进化算法是受生物进化机制启发而产生的一系列算法)和人工神经网络算法(Neural Networks,简 ...

  2. 粒子群优化算法PSO及matlab实现

    算法学习自:MATLAB与机器学习教学视频 1.粒子群优化算法概述 粒子群优化(PSO, particle swarm optimization)算法是计算智能领域,除了蚁群算法,鱼群算法之外的一种群 ...

  3. MATLAB粒子群优化算法(PSO)

    MATLAB粒子群优化算法(PSO) 作者:凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/ 一.介绍 粒子群优化算法(Particle Swarm Optim ...

  4. ARIMA模型--粒子群优化算法(PSO)和遗传算法(GA)

    ARIMA模型(完整的Word文件可以去我的博客里面下载) ARIMA模型(英语:AutoregressiveIntegratedMovingAverage model),差分整合移动平均自回归模型, ...

  5. 计算智能(CI)之粒子群优化算法(PSO)(一)

    欢迎大家关注我们的网站和系列教程:http://www.tensorflownews.com/,学习更多的机器学习.深度学习的知识! 计算智能(Computational Intelligence , ...

  6. 粒子群优化算法(PSO)之基于离散化的特征选择(FS)(二)

    欢迎大家关注我们的网站和系列教程:http://www.tensorflownews.com/,学习更多的机器学习.深度学习的知识! 作者:Geppetto 前面我们介绍了特征选择(Feature S ...

  7. 粒子群优化算法(PSO)之基于离散化的特征选择(FS)(一)

    欢迎大家关注我们的网站和系列教程:http://www.tensorflownews.com/,学习更多的机器学习.深度学习的知识! 作者:Geppetto 在机器学习中,离散化(Discretiza ...

  8. 粒子群优化算法对BP神经网络优化 Matlab实现

    1.粒子群优化算法 粒子群算法(particle swarm optimization,PSO)由Kennedy和Eberhart在1995年提出,该算法模拟鸟集群飞行觅食的行为,鸟之间通过集体的协作 ...

  9. 数值计算:粒子群优化算法(PSO)

    PSO 最近需要用上一点最优化相关的理论,特地去查了些PSO算法相关资料,在此记录下学习笔记,附上程序代码.基础知识参考知乎大佬文章,写得很棒! 传送门 背景 起源:1995年,受到鸟群觅食行为的规律 ...

随机推荐

  1. linux启动jmeter,执行./jmeter.sh报错解决方法

    1.l-bash: ./jmeter.sh: Permission denied解决办法:jmeter.sh的执行权限改改,是权限不够chmod 777 jmeter.sh 2.An error oc ...

  2. JMeter学习参数化User Defined Variables与User Parameters

    偶然发现JMeter中有两个元件(User Defined Variables与User Parameters)很相近,刚开始时我也没注意,两者有什么不同.使用时却发现两者使用场景有些不同,现在小结一 ...

  3. jira与readmine区别

    JIRA适合多人的团队(100+),而Readmine适合中小型团队. Redmine是用ruby开发的基于web的项目管理软件,免费.JIRA收费Redmine可以创建子任务,而jira不易创建子任 ...

  4. 22Mybatis_订单商品数据模型_多对多查询以及对多对多查询的总结

    之前讲了一对一,一对多查询,这篇文章讲的是多对多. 先给出需求:查询用户及用户购买商品信息. 我们由之前的文章知道,这个需求是多对多的. 还是那个终止我们的mybatis所做的不管是之前的一对一还是一 ...

  5. High Performance Animations

    http://www.html5rocks.com/zh/tutorials/speed/high-performance-animations/

  6. [vm]exsi的名词

    早上想了想高可用.昨晚想学学虚拟vmware的一些东西. 物理机---exsi---vm 物理机-win7-vmware-vm   服务器高可用:   一 名词 1,虚拟网络 2,虚拟交换机 3,vm ...

  7. 完成一个MVC+Nhibernate+Jquery-EasyUI信息发布系统

    一.最近学习了Jquery-EasyUI框架,结合之前用过的MVC3+Nhibernate做一个信息发布系统,对工作一年半的自己做一个总结吧!(也正好 供初学者学习!) 二.先上截图(系统简介),让大 ...

  8. [WEB API] CLIENT 指定请求及回应格式(XML/JSON)

    [Web API] Client 指定请求及响应格式(xml/json) Web API 支持的格式请参考 http://www.asp.net/web-api/overview/formats-an ...

  9. 测试驱动开发实践 - Test-Driven Development(转)

    一.前言 不知道大家有没听过“测试先行的开发”这一说法,作为一种开发实践,在过去进行开发时,一般是先开发用户界面或者是类,然后再在此基础上编写测试. 但在TDD中,首先是进行测试用例的编写,然后再进行 ...

  10. [CareerCup] 6.2 Dominos on Chess Board 棋盘上的多米诺

    6.2 There is an 8x8 chess board in which two diagonally opposite corners have been cut off. You are ...