scikit-opt 這個庫以很好用的方式實現了遺傳算法的應用,是目前能找到的較好的遺傳算法工具箱
去這裏 scikit-opt 下載源代碼。或者用pip安裝:
pip install scikit-opt
在多維優化時,想讓哪個變量限制爲整數,就設定 precision
爲 1即可。
例如,我想讓我的自定義函數 demo_func
的第一個變量限制爲整數,那麼就設定 precision
的第一個數爲1,例子如下:
from sko.GA import GA
demo_func = lambda x: x[0] ** 2 + (x[1] - 0.05) ** 2 + x[2] ** 2
ga = GA(func=demo_func, n_dim=3, max_iter=500, lb=[0, 0, 0], ub=[1, 1, 1], precision=[1, 1e-7, 1e-7])
best_x, best_y = ga.run()
print('best_x:', best_x, '\n', 'best_y:', best_y)