Python中的群体智能

scikit-opt的Python项目详细描述


scikit-opt

PyPIBuild StatuscodecovLicensePythonPlatformDownloadsJoin the chat at https://gitter.im/guofei9987/scikit-opt

Python中的群体智能
(遗传算法、粒子群优化算法、模拟退火算法、蚁群算法、免疫算法、Python人工鱼群算法)

安装

pip install scikit-opt

对于当前的开发人员版本:

^{pr2}$

特点

功能1:UDF

UDF(用户定义函数)现在可用!在

例如,您刚刚开发了一个新类型的selection函数。
现在,您的selection函数如下:
->;演示代码:examples/demo_ga_udf.py#s1

# step1: define your own operator:defselection_tournament(algorithm,tourn_size):FitV=algorithm.FitVsel_index=[]foriinrange(algorithm.size_pop):aspirants_index=np.random.choice(range(algorithm.size_pop),size=tourn_size)sel_index.append(max(aspirants_index,key=lambdai:FitV[i]))algorithm.Chrom=algorithm.Chrom[sel_index,:]# next generationreturnalgorithm.Chrom

导入并构建ga
->;演示代码:examples/demo_ga_udf.py#s2

importnumpyasnpfromsko.GAimportGA,GA_TSPdemo_func=lambdax:x[0]**2+(x[1]-0.05)**2+(x[2]-0.5)**2ga=GA(func=demo_func,n_dim=3,size_pop=100,max_iter=500,lb=[-1,-10,-5],ub=[2,10,2],precision=[1e-7,1e-7,1])

将您的自定义项注册到GA
->;演示代码:examples/demo_ga_udf.py#s3

ga.register(operator_name='selection',operator=selection_tournament,tourn_size=3)

scikit opt还提供一些运算符
->;演示代码:examples/demo_ga_udf.py#s4

fromsko.operatorsimportranking,selection,crossover,mutationga.register(operator_name='ranking',operator=ranking.ranking). \
    register(operator_name='crossover',operator=crossover.crossover_2point). \
    register(operator_name='mutation',operator=mutation.mutation)

现在像往常一样进行GA
->;演示代码:examples/demo_ga_udf.py#s5

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

Until Now, the udf surport crossover, mutation, selection, ranking of GA scikit-opt provide a dozen of operators, see here

对于高级用户:

->演示代码:examples/demo_ga_udf.py#s6

classMyGA(GA):defselection(self,tourn_size=3):FitV=self.FitVsel_index=[]foriinrange(self.size_pop):aspirants_index=np.random.choice(range(self.size_pop),size=tourn_size)sel_index.append(max(aspirants_index,key=lambdai:FitV[i]))self.Chrom=self.Chrom[sel_index,:]# next generationreturnself.Chromranking=ranking.rankingdemo_func=lambdax:x[0]**2+(x[1]-0.05)**2+(x[2]-0.5)**2my_ga=MyGA(func=demo_func,n_dim=3,size_pop=100,max_iter=500,lb=[-1,-10,-5],ub=[2,10,2],precision=[1e-7,1e-7,1])best_x,best_y=my_ga.run()print('best_x:',best_x,'\n','best_y:',best_y)

特点二:GPU计算

我们正在开发GPU计算,它将在1.0.0版上稳定
已经有一个示例:https://github.com/guofei9987/scikit-opt/blob/master/examples/demo_ga_gpu.py

特色三:继续跑步

(版本0.3.6中的新功能)
运行一个算法进行10次迭代,然后在之前的10次迭代的基础上再运行20次迭代:

fromsko.GAimportGAfunc=lambdax:x[0]**2ga=GA(func=func,n_dim=1)ga.run(10)ga.run(20)

快速入门

1。差异进化

Step1:定义您的问题
->;演示代码:examples/demo_de.py#s1

'''min f(x1, x2, x3) = x1^2 + x2^2 + x3^2s.t.    x1*x2 >= 1    x1*x2 <= 5    x2 + x3 = 1    0 <= x1, x2, x3 <= 5'''defobj_func(p):x1,x2,x3=preturnx1**2+x2**2+x3**2constraint_eq=[lambdax:1-x[1]-x[2]]constraint_ueq=[lambdax:1-x[0]*x[1],lambdax:x[0]*x[1]-5]

Step2:进行差异进化
->;演示代码:examples/demo_de.py#s2

fromsko.DEimportDEde=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。遗传算法

Step1:定义您的问题
->;演示代码:examples/demo_ga.py#s1

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

Step2:执行遗传算法
->;演示代码:examples/demo_ga.py#s2

fromsko.GAimportGAga=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)

Step3:绘制结果
->;演示代码:examples/demo_ga.py#s3

importpandasaspdimportmatplotlib.pyplotaspltY_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()

Figure_1-1

2.2求解TSP(旅行商问题)

只需导入GA_TSP,它重载crossovermutation来解决TSP

Step1:定义您的问题。准备点坐标和距离矩阵。
在这里,我随机生成数据作为演示:
->;演示代码:examples/demo_ga_tsp.py#s1

importnumpyasnpfromscipyimportspatialimportmatplotlib.pyplotaspltnum_points=50points_coordinate=np.random.rand(num_points,2)# generate coordinate of pointsdistance_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.shapereturnsum([distance_matrix[routine[i%num_points],routine[(i+1)%num_points]]foriinrange(num_points)])

Step2:执行GA
->;演示代码:examples/demo_ga_tsp.py#s2

fromsko.GAimportGA_TSPga_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()

Step3:绘制结果:
->;演示代码:examples/demo_ga_tsp.py#s3

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

GA_TPS

3。粒子群优化

3.1约束

Step1:定义您的问题:
->;演示代码:examples/demo_pso.py#s1

defdemo_func(x):x1,x2,x3=xreturnx1**2+(x2-0.05)**2+x3**2

Step2:执行PSO
->;演示代码:examples/demo_pso.py#s2

fromsko.PSOimportPSOpso=PSO(func=demo_func,n_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)

Step3:绘制结果
->;演示代码:examples/demo_pso.py#s3

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

PSO_TPS

pso_ani
examples/demo_pso_ani.py

4。模拟退火

4.1多功能SA

Step1:定义您的问题
->;演示代码:examples/demo_sa.py#s1

^{pr21}$

Step2:执行SA
->;演示代码:examples/demo_sa.py#s2

fromsko.SAimportSAsa=SA(func=demo_func,x0=[1,1,1],T_max=1,T_min=1e-9,L=300,max_stay_counter=150)best_x,best_y=sa.run()print('best_x:',best_x,'best_y',best_y)

Step3:绘制结果
->;演示代码:examples/demo_sa.py#s3

importmatplotlib.pyplotaspltimportpandasaspdplt.plot(pd.DataFrame(sa.best_y_history).cummin(axis=0))plt.show()

sa

此外,scikit opt提供3种模拟退火:Fast、Boltzmann、Cauchy。见more sa

4.2 TSP

Step1:哦,是的,定义你的问题。复制这一步很无聊。在

Step2:对TSP执行SA
->;演示代码:examples/demo_sa_tsp.py#s2

fromsko.SAimportSA_TSPsa_tsp=SA_TSP(func=cal_total_distance,x0=range(num_points),T_max=100,T_min=1,L=10*num_points)best_points,best_distance=sa_tsp.run()print(best_points,best_distance,cal_total_distance(best_points))

Step3:绘制结果
->;演示代码:examples/demo_sa_tsp.py#s3

frommatplotlib.tickerimportFormatStrFormatterfig,ax=plt.subplots(1,2)best_points_=np.concatenate([best_points,[best_points[0]]])best_points_coordinate=points_coordinate[best_points_,:]ax[0].plot(sa_tsp.best_y_history)ax[0].set_xlabel("Iteration")ax[0].set_ylabel("Distance")ax[1].plot(best_points_coordinate[:,0],best_points_coordinate[:,1],marker='o',markerfacecolor='b',color='c',linestyle='-')ax[1].xaxis.set_major_formatter(FormatStrFormatter('%.3f'))ax[1].yaxis.set_major_formatter(FormatStrFormatter('%.3f'))ax[1].set_xlabel("Longitude")ax[1].set_ylabel("Latitude")plt.show()

sa

更多:绘制动画:

sa
examples/demo_sa_tsp.py

5。求解tsp问题的蚁群算法

在->;演示代码:examples/demo_aca_tsp.py#s2

fromsko.ACAimportACA_TSPaca=ACA_TSP(func=cal_total_distance,n_dim=num_points,size_pop=50,max_iter=200,distance_matrix=distance_matrix)best_x,best_y=aca.run()

ACA

6。免疫算法

{a39演示代码^;gt

fromsko.IAimportIA_TSPia_tsp=IA_TSP(func=cal_total_distance,n_dim=num_points,size_pop=500,max_iter=800,prob_mut=0.2,T=0.7,alpha=0.95)best_points,best_distance=ia_tsp.run()print('best routine:',best_points,'best_distance:',best_distance)

IA

7。人工鱼群算法

->演示代码:examples/demo_afsa.py#s1

deffunc(x):x1,x2=xreturn1/x1**2+x1**2+1/x2**2+x2**2fromsko.AFSAimportAFSAafsa=AFSA(func,n_dim=2,size_pop=50,max_iter=300,max_try_num=100,step=0.5,visual=0.3,q=0.98,delta=0.5)best_x,best_y=afsa.run()print(best_x,best_y)

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
在ElasticSearch中将SearchHit转换为Java对象   第三方库类的java重写XmlAdapter   java如何使用动画类获得平滑的动画效果?   Java PDFBox如果文本内容超过PDF的第一页,如何添加新页面?   Java二叉搜索树u根到最近叶的距离   java什么是diff Scanner和BufferedReader   java如何设计不生成并行数组的程序   java多次声明变量会降低执行速度吗?   java如何使用JXLAPI读取下拉列表的值   多线程为什么自定义阻塞队列在Java中不是线程安全的   java在一个变量中每输入1000个单位,就从另一个变量中减去1?   java Mapstruct通用映射器   Java中的类能否确定它是否已被修改?   java如何在MogoOperations聚合函数中定义输出类型?