快捷搜索:  汽车  科技

python典型算法(python实现爬山算法)

python典型算法(python实现爬山算法)实现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 retu

问题

python典型算法(python实现爬山算法)(1)

找图中函数在区间[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典型算法(python实现爬山算法)(2)

记得关注小编后私信【学习】领取python学习教程哦。

python典型算法(python实现爬山算法)(3)

猜您喜欢: