guofei9987/scikit-opt 这套算法库,很符合简单好用这个要求了。这个库对遗传算法、粒子群算法、模拟退火、蚁群算法较好的封装。
先定义好你的目标函数后,仅需要一两行代码就可以实现相应算法。
1. 遗传算法(Genetic Algorithm)
定义目标函数
def demo_func(x):
x1, x2, x3 = x
return x1 ** 2 + (x2 – 0.05) ** 2 + x3 ** 2
调入遗传算法求解器
from ga import GA
ga = GA(func=demo_func, lb=[-1, -10, -5], ub=[2, 10, 2], max_iter=500)
best_x, best_y = ga.fit()
用 matplotlib 画出结果
import pandas as pd
import matplotlib.pyplot as plt
FitV_history = pd.DataFrame(ga.FitV_history)
fig, ax = plt.subplots(2, 1)
ax[0].plot(FitV_history.index, FitV_history.values, ‘.’, color=’red’)
plt_max = FitV_history.max(axis=1)
ax[1].plot(plt_max.index, plt_max, label=’max’)
ax[1].plot(plt_max.index, plt_max.cummax())
plt.show()
1.1 用遗传算法解决TSP问题(旅行商问题)
GA_TSP 针对TSP问题重载了 交叉(crossover)、变异(mutation) 两个算子
这里作为demo,随机生成距离矩阵. 实战中,从数据源中读取。
import numpy as np
num_points = 8
points = range(num_points)
points_coordinate = np.random.rand(num_points, 2)
distance_matrix = np.zeros(shape=(num_points, num_points))
for i in range(num_points):
for j in range(num_points):
distance_matrix[i][j] = np.linalg.norm(points_coordinate[i] – points_coordinate[j], ord=2)
print(‘distance_matrix is: \n’, distance_matrix)
def cal_total_distance(points):
num_points, = points.shape
total_distance = 0
for i in range(num_points – 1):
total_distance += distance_matrix[points[i], points[i + 1]]
total_distance += distance_matrix[points[i + 1], points[0]]
return total_distance
然后调用遗传算法进行求解
from GA import GA_TSP
ga_tsp = GA_TSP(func=cal_total_distance, points=points, pop=50, max_iter=200, Pm=0.001)
best_points, best_distance = ga_tsp.fit()
画出结果
fig, ax = plt.subplots(1, 1)
best_points_ = np.concatenate([best_points, [best_points[0]]])
best_points_coordinate = points_coordinate[best_points_, :]
ax.plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1],’o-r’)
plt.show()