Python の群知能
(遺伝的アルゴリズム、粒子群最適化、シミュレーテッドアニーリング、アリコロニーアルゴリズム、免疫アルゴリズム、Pythonによる人工魚群アルゴリズム)
ドキュメント: https://scikit-opt.github.io/scikit-opt/#/en/
文档: https://scikit-opt.github.io/scikit-opt/#/zh/
ソースコード: https://github.com/guofei9987/scikit-opt
scikit-opt の改善にご協力くださいhttps://www.wjx.cn/jq/50964691.aspx
pip インストール scikit-opt
現在の開発者バージョンの場合:
git clone [email protected]:guofei9987/scikit-opt.git
cd scikit-opt
pip install .
UDF (ユーザー定義関数)が利用可能になりました!
たとえば、新しいタイプのselection
関数を考案したとします。
さて、 selection
関数は次のようになります。
-> デモコード:examples/demo_ga_udf.py#s1
# ステップ 1: 独自の演算子を定義します:defselection_tournament(algorithm, tourn_size):FitV = Algorithm.FitVsel_index = []for i in range(algorithm.size_pop):aspirants_index = np.random.choice(range(algorithm.size_pop), size =tourn_size)sel_index.append(max(aspirants_index, key=lambda) i: FitV[i]))algorithm.Chrom = アルゴリズム.Chrom[sel_index, :] # 次世代復帰アルゴリズム.Chrom
ga をインポートしてビルドする
-> デモコード:examples/demo_ga_udf.py#s2
import numpy as npfrom sko.GA import GA, GA_TSPdemo_func = lambda x: 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、 prob_mut=0.001,lb=[-1, -10, -5], ub=[2, 10, 2], precision=[1e-7, 1e-7, 1])
UDF を GA に登録します
-> デモコード:examples/demo_ga_udf.py#s3
ga.register(オペレーター名='選択'、オペレーター=選択トーナメント、ツアーサイズ=3)
scikit-opt はいくつかの演算子も提供します
-> デモコード:examples/demo_ga_udf.py#s4
sko.operators からランキング、選択、クロスオーバー、突然変異ga.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)
これまで、 UDF surport の
crossover
、mutation
、selection
、GA scikit-opt のranking
多数の演算子が用意されていました。こちらを参照してください。
上級ユーザー向け:
-> デモコード:examples/demo_ga_udf.py#s6
class MyGA(GA):defselection(self, Tourn_size=3):FitV = self.FitVsel_index = []for i in range(self.size_pop):aspirants_index = np.random.choice(range(self.size_pop), size =tourn_size)sel_index.append(max(aspirants_index, key=lambda i: FitV[i]))self.Chrom = self.Chrom[sel_index, :] # 次世代復帰 self.Chromranking =ranking.rankingdemo_func = lambda x: 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)
(バージョン 0.3.6 の新機能)
アルゴリズムを 10 回反復実行し、その後、前の 10 回の反復に基づいてさらに 20 回の反復を実行します。
sko.GA からインポート GAfunc = lambda x: x[0] ** 2ga = GA(func=func, n_dim=1)ga.run(10)ga.run(20)
ベクトル化
マルチスレッド
マルチプロセッシング
キャッシュされた
https://github.com/guofei9987/scikit-opt/blob/master/examples/example_function_modes.py を参照してください。
私たちは GPU 計算を開発しています。これはバージョン 1.0.0 で安定します。
例はすでに利用可能です: https://github.com/guofei9987/scikit-opt/blob/master/examples/demo_ga_gpu.py
ステップ1 :問題を定義する
-> デモコード: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'''def obj_func(p):x1, x2, x3 = プリターン x1 ** 2 + x2 ** 2 + x3 ** 2constraint_eq = [ラムダ x: 1 - x[1] - x[2] ]constraint_ueq = [ラムダ x: 1 - x[0] * x[1],ラムダ x: x[0] * x[1] - 5]
Step2 : 差分進化を行う
-> デモコード:examples/demo_de.py#s2
sko.DE からインポート DEde = 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)
ステップ1 :問題を定義する
-> デモコード:examples/demo_ga.py#s1
import numpy as npdef schaffer(p):''' この関数には十分な局所最小値があり、値 0 の (0,0) に強い衝撃を伴うグローバル最小値 https://en.wikipedia.org/wiki/Test_functions_for_optimization ''' x1、x2 = ppart1 = np.square(x1) - np.square(x2)part2 = np.square(x1) + np.square(x2)return 0.5 + (np.square(np.sin(part1)) - 0.5) / np.square(1 + 0.001 * part2)
ステップ 2 : 遺伝的アルゴリズムを実行する
-> デモコード:examples/demo_ga.py#s2
sko.GA からインポート GAga = GA(func=schaffer, n_dim=2, size_pop=50, max_iter=800, prob_mut=0.001, 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)
-> デモコード:examples/demo_ga.py#s3
import pandas as pdimport matplotlib.pyplot as pltY_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()
GA_TSP
インポートするだけで、 crossover
、 mutation
をオーバーロードして TSP を解決します
ステップ 1 : 問題を定義します。ポイントの座標と距離行列を準備します。
ここではデモとしてデータをランダムに生成します。
-> デモコード:examples/demo_ga_tsp.py#s1
import numpy as npfrom scipy import spatialimport matplotlib.pyplot as pltnum_points = 50points_coody = np.random.rand(num_points, 2) # 点の座標を生成します distance_matrix = spatial. distance.cdist(points_coowned, Points_cooperative, metric='euclidean')def cal_total_ distance(routine):''目的関数。入力ルーチン、合計距離を返します。 cal_total_ distance(np.arange(num_points)) '''num_points, = Luke.shapereturn sum([ distance_matrix[routine[i % num_points],ルーチン[(i + 1) % num_points]] for i in range(num_points)])
ステップ 2 : GA を実行する
-> デモコード:examples/demo_ga_tsp.py#s2
sko.GA からインポート GA_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()
ステップ 3 : 結果をプロットします。
-> デモコード:examples/demo_ga_tsp.py#s3
fig, ax = plt.subplots(1, 2)best_points_ = np.concatenate([best_points, [best_points[0]]]])best_points_coコーディネート = ポイント座標[best_points_, :]ax[0].plot(best_points_cooperative[:, 0] 、ベストポイント座標[:, 1]、 'または')ax[1].plot(ga_tsp.generation_best_Y)plt.show()
ステップ 1 : 問題を定義します。
-> デモコード:examples/demo_pso.py#s1
def Demon_func(x):x1, x2, x3 = xreturn x1 ** 2 + (x2 - 0.05) ** 2 + x3 ** 2
ステップ 2 : PSO を実行する
-> デモコード:examples/demo_pso.py#s2
sko.PSO からインポート PSOpso = 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 は ', pso.gbest_x、'best_y は'、pso.gbest_y)
ステップ 3 : 結果をプロットする
-> デモコード:examples/demo_pso.py#s3
matplotlib.pyplot を pltplt.plot(pso.gbest_y_hist)plt.show() としてインポートします
(x[0] - 1) ** 2 + (x[1] - 0) ** 2 - 0.5 ** 2<=0
のような非線形制約が必要な場合
コードは次のようなものです:
constraint_ueq = (ラムダ x: (x[0] - 1) ** 2 + (x[1] - 0) ** 2 - 0.5 ** 2、 )pso = PSO(func=demo_func、n_dim=2、pop=40、max_iter=max_iter、lb=[-2, -2]、ub=[2, 2] 、constraint_ueq=constraint_ueq)
複数の非線形制約を追加できることに注意してください。これをconstraint_ueq
に追加するだけです
さらに、アニメーションもあります。
↑ examples/demo_pso_ani.py を参照
ステップ 1 : 問題を定義する
-> デモコード:examples/demo_sa.py#s1
デモ_func = ラムダ x: x[0] ** 2 + (x[1] - 0.05) ** 2 + x[2] ** 2
ステップ 2 : SA を実行する
-> デモコード:examples/demo_sa.py#s2
sko.SA からインポート SAsa = 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)
ステップ 3 : 結果をプロットする
-> デモコード:examples/demo_sa.py#s3
matplotlib.pyplot を pltimport としてインポートし、パンダを pdplt.plot(pd.DataFrame(sa.best_y_history).cummin(axis=0))plt.show() としてインポートします。
さらに、scikit-opt は、Fast、Boltzmann、Cauchy の 3 種類のシミュレーション アニーリングを提供します。もっと見る
ステップ 1 : はい、問題を定義します。このステップをコピーするのは退屈です。
ステップ 2 : TSP の DO SA
-> デモコード:examples/demo_sa_tsp.py#s2
from sko.SA import SA_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 (ベストポイント))
ステップ 3 : 結果をプロットする
-> デモコード:examples/demo_sa_tsp.py#s3
matplotlib.ticker からインポート FormatStrFormatterfig, ax = plt.subplots(1, 2)best_points_ = np.concatenate([best_points, [best_points[0]]])best_points_cooperative = Points_cooperative[best_points_, :]ax[0].plot(sa_tsp.best_y_history)ax[0].set_xlabel("反復")ax[0].set_ylabel("距離")ax[1].plot(best_points_cooperative[:, 0], best_points_coowned [:, 1]、マーカー='o'、マーカーフェイスカラー='b'、カラー='c'、 linestyle='-')ax[1].xaxis.set_major_formatter(FormatStrFormatter('%.3f'))ax[1].yaxis.set_major_formatter(FormatStrFormatter('%.3f'))ax[1].set_xlabel("経度")ax[1].set_ylabel("緯度")plt.show()
詳細: アニメーションをプロットします:
↑ examples/demo_sa_tsp.pyを参照
-> デモコード:examples/demo_aca_tsp.py#s2
from sko.ACA import ACA_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()
-> デモコード:examples/demo_ia.py#s2
from sko.IA import IA_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ルーチン:'、best_points、 'ベスト距離:'、ベスト距離)
-> デモコード:examples/demo_afsa.py#s1
def func(x):x1, x2 = xreturn 1 / x1 ** 2 + x1 ** 2 + 1 / x2 ** 2 + x2 ** 2from sko.AFSA import AFSAafsa = 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)
Yu, J.、He, Y.、Yan, Q.、Kang, X. (2021)。 SpecView: 特異スペクトル変換を備えたマルウェア スペクトル視覚化フレームワーク。情報フォレンジックとセキュリティに関する IEEE トランザクション、16、5093-5107。
Zhen, H.、Zhai, H.、Ma, W.、Zhao, L.、Weng, Y.、Xu, Y.、... & He, X. (2021)。強化学習ベースの最適電力潮流解生成器の設計とテスト。エネルギーレポート。
Heinrich, K.、Zschech, P.、Janiesch, C.、および Bonin, M. (2021)。プロセス データのプロパティが重要: 深層学習による次のイベント予測のためのゲート畳み込みニューラル ネットワーク (GCNN) とキー値予測アテンション ネットワーク (KVP) を導入します。意思決定支援システム、143、113494。
香港のタン氏、SK のゴー氏(2021 年)。 Yi Jing の哲学に触発された、新しい非人口ベースのメタヒューリスティック オプティマイザー。 arXiv プレプリント arXiv:2104.08564。
Wu, G.、Li, L.、Li, X.、Chen, Y.、Chen, Z.、Qiao, B.、... & Xia, L. (2021)。 EBSN 推奨のためのグラフ埋め込みベースのリアルタイム ソーシャル イベント マッチング。ワールドワイドウェブ、1-22。
Pan, X.、Zhang, Z.、Zhang, H.、Wen, Z.、Ye, W.、Yang, Y.、... & Zhao, X. (2021)。注意メカニズムに基づく高速かつ堅牢な混合ガス識別および濃度検出アルゴリズムには、二重損失関数を備えたリカレント ニューラル ネットワークが装備されています。センサーとアクチュエーター B: 化学、342、129982。
カステラ バルセル、M. (2021)。 WindCrete 浮体式洋上風力タービンのステーション維持システムの最適化。
Zhai, B.、Wang, Y.、Wang, W.、Wu, B. (2021)。霧の状況下での高速道路区間における最適な可変速度制限制御戦略。 arXiv プレプリント arXiv:2107.14406。
ヤップ、XH (2021)。局所線形データのマルチラベル分類: 化学毒性予測への応用。
ゲブハルト、L. (2021)。アリのコロニー最適化を使用した低電圧グリッドの拡張計画 Ausbauplanung von Niederspannungsnetzen mithilfe eines Ameisenalgorithmus。
Ma, X.、Zhou, H.、Li, Z. (2021)。水素と電力システム間の相互依存性を最適化した設計。産業アプリケーションに関するIEEEトランザクション。
デ・クルソ、TDC (2021)。ヨハンセン・ルドワ・ソルネット・デ・ボルハス・ファイナンス・モデルの訓練。
Wu, T.、Liu, J.、Liu, J.、Huang, Z.、Wu, H.、Zhang, C.、... & Zhang, G. (2021)。 UAV 支援ワイヤレス センサー ネットワークにおける AoI 最適軌道計画のための新しい AI ベースのフレームワーク。無線通信に関する IEEE トランザクション。
Liu, H.、Wen, Z.、Cai, W. (2021 年 8 月)。 FastPSO: GPU 上の効率的な Swarm Intelligence アルゴリズムに向けて。第 50 回並列処理国際会議にて (pp. 1-10)。
マブブ、R. (2020)。 TSP を解決するためのアルゴリズムと最適化手法。
Li, J.、Chen, T.、Lim, K.、Chen, L.、Khan, SA、Xie, J.、および Wang, X. (2019)。ディープラーニングは金ナノクラスター合成を加速しました。アドバンスト インテリジェント システム、1(3)、1900029。