第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > python的智能算法_scikit-opt——Python中的群体智能优化算法库

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

时间:2023-11-12 15:04:38

相关推荐

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

安装

pip install scikit-opt

对于当前的开发者版本:

git clone git@:guofei9987/scikit-opt.git

cd scikit-opt

pipinstall .

Genetic Algorithm

第一步:定义你的问题

importnumpy as npdefschaffer(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 importGA

#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)

第三步:画出结果

importpandas as pdimportmatplotlib.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.

importnumpy as npfrom scipy importspatialimportmatplotlib.pyplot as plt

num_points= 50points_coordinate= np.random.rand(num_points, 2) #generate coordinate of points

distance_matrix = spatial.distance.cdist(points_coordinate, points_coordinate, metric='euclidean')defcal_total_distance(routine):'''The objective function. input routine, return total distance.

cal_total_distance(np.arange(num_points))'''num_points,=routine.shapereturn sum([distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]] for i in range(num_points)])

第二步:运行GA算法

from sko.GA importGA_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()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。