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

相关文章

Ubuntu 14.04+Django 1.7.1+Nginx+uwsgi部署教程

具体环境: Ubuntu 14.04 Python 2.7.6 Django 1.7.1 Virtualenv name:test Nginx uwsgi 假设 项目文件夹位于 /dat...

Python获取apk文件URL地址实例

工作中经常需要提取apk文件的特定URL地址,如是想到用Python脚本进行自动处理。需要用到的Python基础知识如下:os.walk()函数声明:os.walk(top,topdow...

TensorFlow绘制loss/accuracy曲线的实例

TensorFlow绘制loss/accuracy曲线的实例

1. 多曲线 1.1 使用pyplot方式 import numpy as np import matplotlib.pyplot as plt x = np.arange(1,...

python tensorflow基于cnn实现手写数字识别

一份基于cnn的手写数字自识别的代码,供大家参考,具体内容如下 # -*- coding: utf-8 -*- import tensorflow as tf from tenso...

Python中新式类与经典类的区别详析

1.新式类与经典类 在Python 2及以前的版本中,由任意内置类型派生出的类(只要一个内置类型位于类树的某个位置),都属于“新式类”,都会获得所有“新式类”的特性;反之,即不由任意内置...