模拟退火示例
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
模擬退火是種尋找全局最優(yōu)解的過程,在逐步尋找更優(yōu)的時(shí)候按某種概率接受變差一點(diǎn)的情況,而且開始的時(shí)候探索的步子比較大,容忍變差的概率也大,最后步子變小,容忍變差的概率也變小。
import random import math import matplotlib.pyplot as plt import matplotlib.animation as animationLIMIT = 100000def func(x):return -math.sin((4 * math.pi / LIMIT) * x) * math.sin((3 * math.pi / LIMIT) * x + math.pi / 1.5)def initialize(L):return map(func, range(0, L))def update_temperature(T, k):return T - 0.001def make_move(x, A, T):nhb = random.choice(range(0, len(A))) # choose from all pointsdelta = A[nhb] - A[x]if delta < 0:return nhbelse:p = math.exp(-delta / T)return nhb if random.random() < p else xdef simulated_annealing(A):L = len(A)x0 = random.choice(range(0, L))T = 1.k = 1x = x0x_best = x0while T > 1e-3:yield x, T, x_best, x0x = make_move(x, A, T)if(A[x] < A[x_best]):x_best = xT = update_temperature(T, k)k += 1print("iterations:", k)while True:yield x, T, x_best, x0#動(dòng)畫模擬 A = list(initialize(LIMIT)) sa = simulated_annealing(A) x, T, x_best, x0 = next(sa)def update_animation(frame_number):x, T, x_best, x0 = next(sa)line.set_data([x,x], [0,A[x]])text.set_text('T:'+str(round(T,3)))fig = plt.figure(figsize=(7,7)) plt.plot(A) plt.plot([0,LIMIT], [0,0], c='r') line, = plt.plot([x0, x0], [0, A[x0]], c='r', marker='+') text = plt.text(LIMIT*.8,max(A)*0.9,'T:'+str(round(T,3)))animation = animation.FuncAnimation(fig, update_animation, interval=1) plt.show()轉(zhuǎn)載于:https://my.oschina.net/airxiechao/blog/1408360
總結(jié)
- 上一篇: Windows Server2012 搭
- 下一篇: 剑指offer23 从上往下打印二叉树