python3中的遗传算法库
pyind的Python项目详细描述
Pyind
python3中的遗传算法库
pyind只支持ndarray(numpy)
安装
pip install pyind
关于求值函数
求值函数的格式如下
defevaluation_function(individual):# individual is an array of genereturnfitness_of_this_individual
关于conf
conf
的格式如下
conf_format={"eval":{"func":evaluation_function# Required fields and it has not default value.},"sel":{# See "Table Sel" below},"xovr":{# See "Table Xovr" below},"mut":{# See "Table Mut" below},}
可设置为conf["sel"]
的值如表所示
括号中是默认值
表选择
"sel" (elitism) | "num" (10) |
---|---|
elitism | 0–size of poplation |
roulette | 0–size of poplation |
可以设置为conf["xovr"]
的值如表所示
括号中是默认值
表xovr
"xovr" (p2) | "pb" (0.875) |
---|---|
p2 | 0–1 |
uniform | 0–1 |
ox | 0–1 |
可以设置为conf["mut"]
的值如表所示
括号中是默认值
表mut
"mut" (flip_bit) | "pb" (0.0075) | "delta" (1) |
---|---|---|
flip_bit | 0–1 | |
boundary | 0–1 | 0–∞ |
swap_idx | 0–1 |
未来版本
- 修复错误
- 增加选择、交叉和变异功能
- 跑得更快
许可证
麻省理工学院
示例代码
onemax问题
# Onemax ProblemimportnumpyasnpfrompyindimportpyindaspifrompyindimportdefaultsasdfIND_LEN=100POP_LEN=100defevl(ind):returnind.sum()if__name__=="__main__":pop=np.random.randint(2,size=(POP_LEN,IND_LEN))conf=df.CONFconf["eval"]["func"]=evlbest=pi.Pyind(pop,conf).run()print("best ind: ")print(best)
旅行商问题(tsp)
# Traveling salesman problemimportnumpyasnpimportmatplotlib.pyplotaspltfrompyindimportpyindaspifrompyindimportcrossoverasxovrfrompyindimportmutationasmutfrompyindimportdefaultsasdfCITIES_LEN=30POP_LEN=300END_GEN=500cities=np.random.rand(CITIES_LEN*2).reshape((-1,2))defevl(ind):total=0foriinrange(1,len(ind)):total+=np.linalg.norm(cities[ind[i]]-cities[ind[i-1]])return-totaldefsolve(pop):conf=df.CONFconf["eval"]["func"]=evlconf["xovr"]["func"]=xovr.oxconf["mut"]["func"]=mut.swap_idxconf["mut"]["pb"]=0.10returnpi.Pyind(pop,conf).run(END_GEN)if__name__=="__main__":t=cities.T# Create poppop=np.tile(np.arange(CITIES_LEN),(POP_LEN,1))foreinpop:np.random.shuffle(e)# Plot gen 0idx=pop[0]plt.plot(t[0,idx],t[1,idx],label="gen 0",marker="o")best=solve(pop)print("best ind: ")print(best)# Plot gen END_GENidx=bestplt.plot(t[0,idx],t[1,idx],label="gen "+str(END_GEN),marker="o")plt.legend()plt.show()