scikit-opt——Python中的群体智能优化算法库

安装

pip install scikit-opt

对于当前的开发者版本:

git clone :guofei9987/scikit-opt.git
cd scikit-opt
pip install .

Genetic Algorithm

第一步:定义你的问题

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)

第二步:运行遗传算法

from sko.GA import GA
#2个变量,每代取50个,800次迭代,上下界及精度
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)

第三步:画出结果

import pandas as pd
import matplotlib.pyplot as plt

Y_history = pd.DataFrame(ga.all_history_Y)
fig, ax = plt.subplots(2, 1)
ax[0].plot(Y_history.index, Y_history.values, ‘.‘, color=‘red‘)
Y_history.min(axis=1).cummin().plot(kind=‘line‘)
plt.show()

精度改成1就能视为整数规划。

Genetic Algorithm for TSP(Travelling Salesman Problem)

只需要导入GA_TSP,它重载了crossover, mutation来解决TSP.

第一步:定义你的问题。准备你的点的坐标和距离矩阵。

这里使用随机数据作为Demo.

import numpy as np
from scipy import spatial
import matplotlib.pyplot as plt

num_points = 50

points_coordinate = np.random.rand(num_points, 2)  # generate coordinate of points
distance_matrix = spatial.distance.cdist(points_coordinate, points_coordinate, metric=‘euclidean‘)


def cal_total_distance(routine):
    ‘‘‘The objective function. input routine, return total distance.
    cal_total_distance(np.arange(num_points))
    ‘‘‘
    num_points, = routine.shape
    return sum([distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]] for i in range(num_points)])

第二步:运行GA算法

from sko.GA import GA_TSP

ga_tsp = GA_TSP(func=cal_total_distance, n_dim=num_points, size_pop=50, max_iter=500, prob_mut=1)
best_points, best_distance = ga_tsp.run()

第三步:画出结果

fig, ax = plt.subplots(1, 2)
best_points_ = np.concatenate([best_points, [best_points[0]]])
best_points_coordinate = points_coordinate[best_points_, :]
ax[0].plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], ‘o-r‘)
ax[1].plot(ga_tsp.generation_best_Y)
plt.show()

参考链接:scikit-opt官方文档-遗传算法部分

相关推荐