import numpy as np
import matplotlib.pyplot as plt
from numpy.random import rand,randint
from math import cos,sqrt,pow
def func(x):
y = (cos(x[0]*x[0]+x[1]*x[1])-0.1)/(1+0.3*pow(x[0]*x[0]+x[1]*x[1],2))+3
return y
path = []
xu = 5 # 上界
xl = -5 # 下界
tb_len = randint(5,11) # 5-11之间的随机数,禁忌表长度
nerb_count = 20 # 邻域解个数
max_iter = 200 # 最大迭代次数
w = 1 # 自适应权重
tabu = [] # 禁忌表
xnow = rand(2)*(xu-xl+xl) #随机产生初始值
xnow_value = 0
bestsofar = np.zeros(2)
bestsofar_value = 0
# 准备开始迭代过程
bestsofar = xnow
bestsofar_value = func(xnow)
xnow_value = bestsofar_value
g = 0
while g<max_iter:
x_nears = []
w = w*0.998
for i in range(nerb_count): # 产生邻域解
x_near = []
x_temp = xnow
x1 = x_temp[0]
x2 = x_temp[1]
x_near.append(x1+(2*rand()-1)*w*(xu-xl)) # 产生第一维
if x_near[0]<xl:
x_near[0] = xl
if x_near[0]>xu:
x_near[0] = xu
x_near.append(x2+(2*rand()-1)*w*(xu-xl)) # 产生第二维
if x_near[1]<xl:
x_near[1] = xl
if x_near[1]>xu:
x_near[1] = xu
x_nears.append(x_near)
fitvalues = [] # 计算邻域函数值
for key in x_nears:
fitvalues.append(func(key))
indx = np.argmax(fitvalues) # 判断最大值的索引
candidate = x_nears[indx]
candidate_value = fitvalues[indx]
delta1 = candidate_value - xnow_value # 当前值和最好值比较
delta2 = candidate_value - bestsofar_value
if delta1 <= 0: # 策略:比当前劣势直接接受,利于跳出局部;比最优更优也直接接受;比当前优但比最优劣势,考虑是否在禁忌表内,避免局部循环。
xnow_value = candidate_value
xnow = candidate
tabu.append(xnow_value) # 更新禁忌表
if len(tabu)>tb_len:
tabu.pop(0)
else:
if delta2 > 0:
xnow_value = candidate_value
xnow = candidate
tabu.append(xnow_value) # 更新禁忌表
if len(tabu)>tb_len:
tabu.pop(0)
bestsofar_value = candidate_value # 赋给最优,包含蔑视准则
bestsofar = candidate
else: # 判断是否在禁忌表内
if candidate not in tabu:
xnow_value = candidate_value
xnow = candidate
tabu.append(xnow_value) # 更新禁忌表
if len(tabu)>tb_len:
tabu.pop(0)
else:
pass
path.append(bestsofar_value)
g = g+1
print(max(path))
plt.plot(path)
plt.pause(10000)
参考:《智能优化算法及MATLAB实例》