import random
import math
import matplotlib.pyplot as plt
import numpy as np
import time
def init(b_=700,xSize_=200,iteration_=1000,c1_=0.5,c2_=0.5,w_=0.8):
global a,c,b,Dim,xSize,iteration,c1,c2,w,A,C,x,v,xbest,fxbest,gbest,fgbest
a = [90, 33, 94, 69, 77, 91, 39, 74, 24, 34, 14, 89, 98, 37, 32, 45, 15, 98, 40, 16, 17, 4, 3, 5, 94, 3, 64, 47, 85, 9, 6, 39, 44, 67, 33, 59, 17, 16, 55, 95, 69, 88, 91, 28, 66, 54, 85, 82, 24, 17, 30, 66, 96, 8, 74, 20, 84, 35, 53, 19, 25, 64, 98, 93, 86, 24, 30, 68, 56, 37, 6, 98, 48, 76, 61, 9, 29, 76, 55, 41, 93, 19, 56, 85, 20, 84, 12, 64, 94, 29, 26, 93, 83, 72, 76, 86, 4, 99, 29, 4]
c = [68, 20, 125, 85, 113, 109, 19, 93, 17, 19, 18, 79, 92, 39, 45, 50, 12, 77, 53, 16, 8, 2, 2, 7, 47, 4, 67, 9, 62, 6, 8, 51, 61, 93, 33, 35, 14, 15, 34, 136, 87, 72, 121, 28, 84, 54, 110, 44, 15, 23, 36, 95, 77, 11, 74, 14, 75, 50, 63, 26, 34, 56, 67, 77, 73, 34, 41, 59, 84, 44, 7, 112, 70, 65, 54, 6, 20, 92, 56, 21, 125, 24, 83, 113, 14, 99, 18, 49, 70, 15, 34, 88, 105, 48, 61, 128, 3, 110, 19, 4]
b = b_ #背包容量
#初始化种群
Dim = 100 #维度
xSize = xSize_ #种群数
iteration = iteration_ #迭代次数
c1 = c1_
c2 = c2_ #加速因子
w = w_ #定义惯性因子
A = np.array([a]*xSize) #将a扩展成种群数*维度的矩阵
C = np.array([c]*xSize) #将c扩展为种群数*维度的矩阵
x = np.random.randint(0,2,(xSize,Dim)) #随机生成一个种群数*维度的矩阵
v = np.random.rand(xSize,Dim) #随机生成一个种群数*维度的速度矩阵
xbest = np.zeros((xSize,Dim)) #单个粒子的初始最佳位置
fxbest = np.zeros((xSize,1)) #xbext的适应度
gbest = np.zeros((1,Dim)) #全局最优解
fgbest = 0 #全局最优解的适应度 def solve():
#寻找粒子群最优位置和单个粒子
global x,fgbest,v
fx = np.sum(np.multiply(C,x), axis=1) # 粒子适应度,即背包内物品的价格
sx = np.sum(np.multiply(A,x), axis=1) # 限制函数,即背包内物品的体积
#print(sx)
for i in range(xSize):
if list(sx)[i] > b:
fx[i] = 0
for i in range(xSize):
if fxbest[i] < fx[i]: # 当粒子适应度大于最佳适应度时,替代
fxbest[i] = fx[i]
xbest[i] = x[i] # 替换矩阵第i行
if fgbest <= max(fxbest):
fgbest = max(fxbest)
g = list(fxbest).index(fgbest)
gbest = xbest[g] #当存在粒子的最佳适应度fxbext(i)大于种群最佳适应度fgbext(i)时,替代
for i in range(xSize):
if (x[i]==gbest).all():
x[i] = np.random.randint(0,2,(1,Dim)) #随机生成一个种群数*维度的矩阵
R1 = np.random.rand(xSize,Dim)
R2 = np.random.rand(xSize,Dim)
v = v * w + c1 * np.multiply(R1,xbest-x) + c2 * np.multiply(R2,(np.array([gbest]*xSize)-x))#速度迭代公式产生新的速度
x = x + v
for i in range(xSize): #更新粒子群的位置
for j in range(Dim):
if x[i][j] < 0.5:
x[i][j] = 0
else:
x[i][j] = 1 #粒子的位置只有(0,1)两种状态 if __name__ == "__main__":
k = 2
if(k==1):
'''在不同种群规模下的算法性能表现'''
tmp = []
y = []
for scale in range(50,200,20):
tmp.append(scale)
print(scale)
init(xSize_=scale,iteration_=1500)
for i in range(iteration):
solve()
y.append(fgbest[0])
plt.plot(tmp,y)
plt.xlabel('population scale')
plt.ylabel('value')
plt.title('the effect of population scale')
elif(k==2):
'''在不同惯性因子下的算法性能表现'''
tmp = []
y = []
for w in range(4,9):
w = w / 10
tmp.append(w)
print(w)
init(w_=w,iteration_=1500)
for i in range(iteration):
solve()
y.append(fgbest[0])
plt.plot(tmp,y)
plt.xlabel('inertia factor')
plt.ylabel('value')
plt.title('the effect of inertia factor')
elif(k==3):
'''在不同加速因子下的算法性能表现'''
tmp = []
y = []
for c in range(1,20,2):
c = c / 10
tmp.append(c)
print(c)
init(c1_=c,c2_=c,iteration_=1500)
for i in range(iteration):
solve()
y.append(fgbest[0])
plt.plot(tmp,y)
plt.xlabel('acceleration factor')
plt.ylabel('value')
plt.title('the effect of acceletation factor')
elif(k==4):
'''在不同背包容量下的算法最佳迭代次数'''
tmp = []
y = []
for capacity in range(500,3501,500):
tmp.append(capacity)
best = []
print(capacity)
init(b_=capacity,iteration_=5000)
for i in range(iteration):
solve()
best.append(fgbest[0])
print(best)
for i in range(len(best)):
if(best[len(best)-i-1] != best[len(best)-i-2]):
print(4)
y.append(len(best)-i)
break plt.xlabel('capacity')
plt.ylabel('epochs')
plt.plot(tmp,y)
elif(k==5):
'''禁忌搜索算法与微粒群算法的性能比较'''
from TSA import TSA_bag
i = 500
tmp = [x for x in range(i)]
pso = []
init(iteration_=i)
for i in range(iteration):
solve()
pso.append(fgbest[0])
plt.plot(tmp,pso,color='red',label='PSO')
plt.plot(tmp,TSA_bag(interation=i),color='blue',label='TSA')
plt.xlabel('interation')
plt.ylabel('value')
plt.title('the comparison between PSA and TSA')
elif(k==6):
'''在不同背包容量下,禁忌搜索算法与微粒群算法的性能比较'''
#import TSA
tmp = []
pso = []
tsa = []
for i in range(500,3501,250):
import TSA
TSA_tmp = TSA.main(capacity_=i,interation=300)
tmp.append(i)
print(i)
init(b_=i,iteration_=1000)
for i in range(iteration):
solve()
pso.append(fgbest[0])
tsa.append(TSA_tmp)
plt.plot(tmp,pso,color='red',label='PSO')
plt.plot(tmp,tsa,color='blue',label='TSA')
plt.xlabel('capacity')
plt.ylabel('value')
plt.title('the comparison between PSA and TSA') plt.legend()
plt.show()

微粒群算法PSO 01背包问题 python的更多相关文章

  1. C语言实现粒子群算法(PSO)一

    最近在温习C语言,看的书是<C primer Plus>,忽然想起来以前在参加数学建模的时候,用过的一些智能算法,比如遗传算法.粒子群算法.蚁群算法等等.当时是使用MATLAB来实现的,而 ...

  2. 算法(三)粒子群算法PSO的介绍

    一.引言 在讲算法之前,先看两个例子: 例子一:背包问题,一个书包,一堆物品,每个物品都有自己的价值和体积,装满书包,使得装的物品价值最大. 例子二:投资问题,n个项目,第i个项目投资为ci 收益为p ...

  3. 【比较】粒子群算法PSO 和 遗传算法GA 的相同点和不同点

    目录 PSO和GA的相同点 PSO和GA不同点 粒子群算法(PSO)和遗传算法(GA)都是优化算法,都力图在自然特性的基础上模拟个体种群的适应性,它们都采用一定的变换规则通过搜索空间求解. PSO和G ...

  4. 粒子群算法-PSO

    粒子群优化算法 1. 背景知识 1995年美国社会心理学家Kennedy和电气工程师Eberhart共同提出粒子群优化算法(Particle Swarm Optimization, PSO).PSO算 ...

  5. 01背包问题python 2.7实现

    版权声明:本文为博主原创文章,转载请注明转自 http://www.cnblogs.com/kdxb/p/6140625.html #!/usr/bin/env python # -*- coding ...

  6. 0-1背包问题python解决

    def f(i,j): while i>=0: if i==0 and j>=l[i][0]: return l[i][1] elif i==0 and j<l[i][0]: ret ...

  7. 【CI】CN.一种多尺度协同变异的微粒群优化算法

    [论文标题]一种多尺度协同变异的微粒群优化算法 (2010) [论文作者]陶新民,刘福荣, 刘  玉 , 童智靖 [论文链接]Paper(14-pages // Single column) [摘要] ...

  8. C语言实现粒子群算法(PSO)二

    上一回说了基本粒子群算法的实现,并且给出了C语言代码.这一篇主要讲解影响粒子群算法的一个重要参数---w.我们已经说过粒子群算法的核心的两个公式为: Vid(k+1)=w*Vid(k)+c1*r1*( ...

  9. 粒子群优化算法(PSO)的基本概念

    介绍了PSO基本概念,以及和遗传算法的区别: 粒子群算法(PSO)Matlab实现(两种解法)

随机推荐

  1. 笃情开源:我和 Apache DolphinScheduler 社区的故事

    背景 本文的主人翁是 2 次飞机参会现场交流,四天研究就把 DolphinScheduler 用上生产的来自车联网行业的大数据 boy - 黄立同学.怎么样,听起来是不是有点 crazy?下面就来看看 ...

  2. React报错之Functions are not valid as a React child

    正文从这开始~ 总览 产生"Functions are not valid as a React child. This may happen if you return a Compone ...

  3. 解决使用 Eruda 绑定 dom 未在指定位置显示问题

    前言 开发项目中,使用到 Eruda 打印控制台信息显示 文档:https://github.com/liriliri/eruda 安装 Eruda npm install eruda --save ...

  4. SpringBoot整合Redis实现常用功能

    SpringBoot整合Redis实现常用功能 建议大小伙们,在写业务的时候,提前画好流程图,思路会清晰很多. 文末有解决缓存穿透和击穿的通用工具类. 1 登陆功能 我想,登陆功能是每个项目必备的功能 ...

  5. C++ 运行单个实例,防止程序多次启动

    利用内核对象 封装的类,使用运行单个实例,防止多次启动Demo 例子下载地址:http://pan.baidu.com/share/link?shareid=3202369154&uk=303 ...

  6. 一、JDK和JRE

    JDK和JRE JDK=JRE+开发工具包: JRE=JVM+核心类库 如果只是运行Java程序,安装JRE即可:开发Java程序并运行则需要安装JDK.目前最稳定版本是JDK8.0,并且马上部分企业 ...

  7. Vmware虚拟主机启动卡死问题解决

    记录一次虚拟主机开机卡死,黑屏,无法操作的问题 一.问题现象 1.在vmware上新建数台主机后,第一次启动都正常,部分主机出现关机后再开机(或直接重启)卡死的情况: 2.在vmware上右键菜单栏均 ...

  8. C++ | unordered_map 自定义键类型

    C++ unordered_map 使用自定义类作为键类型 C++ unordered_map using a custom class type as the key

  9. 使用ESP8266nodeMCU 向微信推送模板数据

    使用HTTPS协议向微信公众号推送消息,(使用ESP8266的低成本实现) 前几天被朋友问到这个东西的实现方式,花了一下午时间研究一下,特此记录.没有排版比较乱. 一丶前往微信公众平台注册微信微信公众 ...

  10. kibana配置文件kibana.yml参数详解

    server.port: 默认值: 5601 Kibana 由后端服务器提供服务,该配置指定使用的端口号. server.host: 默认值: "localhost" 指定后端服务 ...