博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
《集体智慧编程》-优化算法
阅读量:4043 次
发布时间:2019-05-24

本文共 1932 字,大约阅读时间需要 6 分钟。

chapter3优化算法

随机搜索

#随机搜索domain是序列,costf是定义的成本函数def randomoptimize(domain,costf):  best=999999999  bestr=None  for i in range(0,1000):    # 创建一个随机解    r=[float(random.randint(domain[i][0],domain[i][1])) for i in range(len(domain))]    # Get the cost    cost=costf(r)    # Compare it to the best one so far    if cost

容易陷入局部最小值)*

#爬山法,从一个随机解开始,到临近找更好的方法,不会随机浪费时间def hillclimb(domain,costf):  # Create a random solution  sol=[random.randint(domain[i][0],domain[i][1])      for i in range(len(domain))]  # Main loop  while 1:    # Create list of neighboring solutions    neighbors=[]    for j in range(len(domain)):      # One away in each direction      if sol[j]>domain[j][0]:        neighbors.append(sol[0:j]+[sol[j]+1]+sol[j+1:])      if sol[j]

模拟退火:

(开始阶段可以接受较差的解,随着温度减少,只会接受更好的解)

#模拟退火算法,爬山法可能只是局部最优解,退火会接受较差的解,但是差异越大,概率越低,最后抛弃**

#模拟退火算法,爬山法可能只是局部最优解,退火会接受较差的解,但是差异越大,概率越低,最后抛弃def annealingoptimize(domain,costf,T=10000.0,cool=0.95,step=1):  # Initialize the values randomly  vec=[float(random.randint(domain[i][0],domain[i][1]))       for i in range(len(domain))]  while T>0.1:    # Choose one of the indices    i=random.randint(0,len(domain)-1)    # Choose a direction to change it    dir=random.randint(-step,step)    # Create a new list with one of the values changed    vecb=vec[:]    vecb[i]+=dir    if vecb[i]
domain[i][1]: vecb[i]=domain[i][1] # Calculate the current cost and the new cost ea=costf(vec) eb=costf(vecb) p=pow(math.e,(-eb-ea)/T) # Is it better, or does it make the probability # cutoff? if (eb

遗传算法:

先随机生成一组解,称为种群。计算整个种群的成本函数。创建新种群:1精英选拔最好的解;2修改题解(变异:微小变化)(交叉配对:题解组合)

#遗传算法def geneoptimize(domain,costf,popsize=50,step=1,mutprob=0.2,elite=0.2,maxiter=100):#maxiter代数,mutprob变异的概率,elite遗传概率  # Mutation Operation  def mutate(vec):    i=random.randint(0,len(domain)-1)    if random.random()<0.5 and vec[i]>domain[i][0]:      return vec[0:i]+[vec[i]-step]+vec[i+1:]    elif vec[i]

转载地址:http://rlhdi.baihongyu.com/

你可能感兴趣的文章
带WiringPi库的交叉编译如何处理一
查看>>
带WiringPi库的交叉笔译如何处理二之软链接概念
查看>>
Spring事务的七种传播行为
查看>>
ES写入找不到主节点问题排查
查看>>
Java8 HashMap集合解析
查看>>
欢迎使用CSDN-markdown编辑器
查看>>
Android计算器实现源码分析
查看>>
Android系统构架
查看>>
Android 跨应用程序访问窗口知识点总结
查看>>
各种排序算法的分析及java实现
查看>>
SSH框架总结(框架分析+环境搭建+实例源码下载)
查看>>
js弹窗插件
查看>>
自定义 select 下拉框 多选插件
查看>>
js判断数组内是否有重复值
查看>>
js获取url链接携带的参数值
查看>>
gdb 调试core dump
查看>>
gdb debug tips
查看>>
arm linux 生成火焰图
查看>>
linux和windows内存布局验证
查看>>
linux insmod error -1 required key invalid
查看>>