当前位置: 移动技术网 > IT编程>脚本编程>Python > python实现爬山算法的思路详解

python实现爬山算法的思路详解

2019年06月10日  | 移动技术网IT编程  | 我要评论

张满泉,k1191,sdupdateext.dll

问题

找图中函数在区间[5,8]的最大值 

重点思路

爬山算法会收敛到局部最优,解决办法是初始值在定义域上随机取乱数100次,总不可能100次都那么倒霉。

实现

import numpy as np
import matplotlib.pyplot as plt
import math
# 搜索步长
delta = 0.01
# 定义域x从5到8闭区间
bound = [5,8]
# 随机取乱数100次
generation = 100
def f(x):
  return math.sin(x*x)+2.0*math.cos(2.0*x)
def hillclimbing(x):
  while f(x+delta)>f(x) and x+delta<=bound[1] and x+delta>=bound[0]:
    x = x+delta
  while f(x-delta)>f(x) and x-delta<=bound[1] and x-delta>=bound[0]:
    x = x-delta
  return x,f(x)
def findmax():
  highest = [0,-1000]
  for i in range(generation):
    x = np.random.rand()*(bound[1]-bound[0])+bound[0]
    currentvalue = hillclimbing(x)
    print('current value is :',currentvalue)
    
    if currentvalue[1] > highest[1]:
      highest[:] = currentvalue
  return highest
[x,y] = findmax()
print('highest point is x :{},y:{}'.format(x,y))

运行结果:

总结

以上所述是小编给大家介绍的python实现爬山算法的思路详解,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网