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

yipeiwu_com6年前Python基础

问题

找图中函数在区间[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进行数据分析的理由和优势

1、python大量的库为数据分析提供了完整的工具集 2、比起MATLAB、R语言等其他主要用于数据分析语言,python语言功能更加健全 3、python库一直在增加,算法的实现采取的...

python实现大战外星人小游戏实例代码

主程序 import pygame from pygame.sprite import Group from settings import Settings from game_...

关于python pycharm中输出的内容不全的解决办法

关于python pycharm中输出的内容不全的解决办法

很多时候我们会发现有的时候输出的结果特别多的时候,会在最后输出时用。。。代替,最后输出一个总长度,那要咋么弄咧? import pandas as pd # 设置显示的最大列、宽等参...

TensorFlow tensor的拼接实例

TensorFlow提供两种类型的拼接: tf.concat(values, axis, name='concat'):按照指定的已经存在的轴进行拼接 tf.stack(values...

Python自定义一个类实现字典dict功能的方法

如下所示: import collections class Mydict(collections.UserDict): def __missing__(self, ke...