python 中的启发式算法工具包

本文介绍了一个强大的Python代码库scikit-opt,它封装了包括差分进化算法、遗传算法、粒子群算法等在内的7种启发式算法。文章通过实例展示了如何使用这些算法解决复杂优化问题,如定义问题、运行算法及结果可视化。

之前一直以为python没有相应的python工具包,后来发现其实python也有诸如遗传算法/粒子群算法等启发式算法工具包,链接如下:
github链接
中文帮助文档
Ubuntu安装如下:

pip install scikit-opt

scikit-opt是一个封装了7种启发式算法的 Python 代码库(差分进化算法、遗传算法、粒子群算法、模拟退火算法、蚁群算法、鱼群算法、免疫优化算法)
下面粘贴几个例子:

1. 差分进化算法

步骤1 定义问题 (demo源代码
"""
原问题:min f(x1, x2, x3) = x1^2 + x2^2 + x3^2
				s.t.
				    x1*x2 >= 1
				    x1*x2 <= 5
				    x2 + x3 = 1
				    0 <= x1, x2, x3 <= 5
"""


def obj_func(p):
    x1, x2, x3 = p
    return x1 ** 2 + x2 ** 2 + x3 ** 2


constraint_eq = [
    lambda x: 1 - x[1] - x[2]
]

constraint_ueq = [
    lambda x: 1 - x[0] * x[1],
    lambda x: x[0] * x[1] - 5
]
步骤2 做差分算法
from sko.DE import DE

de = DE(func=obj_func, n_dim=3, size_pop=50, max_iter=800, lb=[0, 0, 0], ub=[5, 5, 5],
        constraint_eq=constraint_eq, constraint_ueq=constraint_ueq)

best_x, best_y = de.run()
print('best_x:', best_x, '\n', 'best_y:', best_y)

2.遗传算法

步骤1 定义问题(demo源代码
import numpy as np

def schaffer(p):
    '''
    This function has plenty of local minimum, with strong shocks
    global minimum at (0,0) with value 0
    '''
    x1, x2 = p
    x = np.square(x1) + np.square(x2)
    return 0.5 + (np.sin(x) - 0.5) / np.square(1 + 0.001 * x)

步骤2 运行遗传算法
from sko.GA import GA

ga = GA(func=schaffer, n_dim=2, size_pop=50, max_iter=800, lb=[-1, -1], ub=[1, 1], precision=1e-7)
best_x, best_y = ga.run()
print('best_x:', best_x, '\n', 'best_y:', best_y)
步骤3 用 matplotlib 画出结果

结果

3.粒子群算法

demo:带约束的粒子群算法(源代码

步骤1 定义问题
def demo_func(x):
    x1, x2, x3 = x
    return x1 ** 2 + (x2 - 0.05) ** 2 + x3 ** 2
步骤2 做粒子群算法
from sko.PSO import PSO

pso = PSO(func=demo_func, dim=3, pop=40, max_iter=150, lb=[0, -1, 0.5], ub=[1, 1, 1], w=0.8, c1=0.5, c2=0.5)
pso.run()
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
步骤3 画出结果
import matplotlib.pyplot as plt

plt.plot(pso.gbest_y_hist)
plt.show()

在这里插入图片描述
还有个动图贴不出来……

总之这个算法包还是非常好的,更多资源请访问原链接中文文档

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值