優化算法(二)模擬退火算法

import numpy as np


# 隨機確定變化的方向
def direction2():
    if np.random.random() > 0.5:
        return 1
    return -1


# 隨機確定是否接受較差的解
def direction3(delta, T):
    chance = np.exp(-1*delta/T)
    if np.random.random() < chance:
        return True
    return False


# 模擬退火求解最小值
def saa(fitness, x, T=10000, c=0.96, t=1000):

    # fitness 表示待優化函數
    # x 表示一組可行解
    # T 表示溫度
    # c 表示退火因子
    # t 表示在每個溫度下的尋優次數

    # 初始化最優解
    pg = x

    # 解空間的維度
    d = len(x)

    # 主循環
    while T > 1:
        for i in range(t):
            for j in range(d):

                # 構造新解
                nx = pg[:]
                nx[j] += direction2() * np.random.random()

                # 更新最優解
                if fitness(nx) < fitness(pg):
                    pg = nx

                elif direction3(fitness(nx)-fitness(pg), T):
                    pg = nx

                T *= c

    # 返回最優解和最優值
    return pg, fitness(pg)


# 目標函數
def func(x):
    x1, x2 = x
    return x1 ** 2 + 2 * x1 + 1 + x2 ** 2 + 2 * x2 + 1


# 初始解
init = [2*np.random.random(), 2*np.random.random()]

xm, fv = saa(func, init)

print(xm, fv)
# [-1.001342543851264, -1.0025416982616582] 8.262654045854134e-06
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章