算法(二)模拟退火算法

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

猜你喜欢

转载自blog.csdn.net/lolimostlovely/article/details/82390756
今日推荐