python 中的启发式算法工具包

之前一直以为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()

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

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

发布了4 篇原创文章 · 获赞 0 · 访问量 740

猜你喜欢

转载自blog.csdn.net/u013310037/article/details/103675538