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. UVA 10405 Longest Common Subsequence --经典DP

    最长公共子序列,经典问题.算是我的DP开场题吧. dp[i][j]表示到s1的i位置,s2的j位置为止,前面最长公共子序列的长度. 状态转移: dp[i][j] = 0                 ...

  2. c查漏补缺

    restrict 要理解什么是restrict,首先要知道Pointer aliasing:指两个或以上的指针指向同一数据,例如: ; int *a = &i; int *b = &i ...

  3. box unboxing(装箱 拆箱) C#编程指南

    box(装箱)消耗大 box在堆栈中创建一个新的对象,性能消耗大 int i = 123; // Boxing copies the value of i into object o. object ...

  4. QC学习二:QC使用中问题点汇总

    QC 使用中问题点汇总,包括以下方面: 1.不兼容IE7,IE8的问题(服务器端设置) 2.无法在Win 7下正常下载页面(客户端设置) 3.在QC中填写中文内容后无法正常提交到数据库(客户端设置) ...

  5. Hibernate入门注解笔记

    @Entity 代表实体 映射一张表 @Table 定义表的属性 @Embeddable 定义类级别可以被嵌入 @Id 指定主键 @GeneratedValue 指定主键生成策略 @Column指定列 ...

  6. 23Spring_JdbcTemplate来实现单表的增删改查

    第一步建表:

  7. Socket Programming in C#--Introduction

    This is the second part of the previous article about the socket programming. In the earlier article ...

  8. 挂多个class还是新建class —— 多用组合,少用继承

    用css实现下面的效果图. 方案一 <style type="text/css"> .myList1 { border: 1px solid #333; padding ...

  9. 优化Hibernate所鼓励的7大措施

    优化Hibernate所鼓励的7大措施: 1.尽量使用many-to-one,避免使用单项one-to-many2.灵活使用单向one-to-many3.不用一对一,使用多对一代替一对一4.配置对象缓 ...

  10. [CareerCup] 8.7 Chat Server 聊天服务器

    8.7 Explain how you would design a chat server. In particular, provide details about the various bac ...