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实现爬山算法的思路详解,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

相关文章

MNIST数据集转化为二维图片的实现示例

本文介绍了MNIST数据集转化为二维图片的实现示例,分享给大家,具体如下: #coding: utf-8 from tensorflow.examples.tutorials.mni...

python中关于时间和日期函数的常用计算总结(time和datatime)

1.获取当前时间的两种方法: 复制代码 代码如下:import datetime,timenow = time.strftime("%Y-%m-%d %H:%M:%S")print no...

Python使用到第三方库PyMuPDF图片与pdf相互转换

使用 Python 进行图片和pdf之间的相互转换 使用到第三方库 PyMuPDF 在 python 环境下对 PDF 文件的操作。 PDF 转为图片 需新建文件夹 pdf2png...

Pyinstaller打包.py生成.exe的方法和报错总结

Pyinstaller 打包.py生成.exe的方法和报错总结 简介 有时候自己写了个python脚本觉得挺好用想要分享给小伙伴,但是每次都要帮他们的电脑装个python环境。虽然说装一...

Python日志模块logging简介

Python日志模块logging简介

logging分为4个模块: loggers, handlers, filters, and formatters. ●loggers: 提供应用程序调用的接口 ●handlers: 把...