飛行中に鳥の群れを見ていると想像してみてください。リーダーも、誰も指示を与えていませんが、彼らは完全に調和して急降下して滑ります。カオスのように見えるかもしれませんが、隠された順序があります。捕食者やアリが食物への最短の道を見つけることを避ける魚の学校で同じパターンを見ることができます。これらのクリーチャーは、中央制御なしで驚くほど複雑なタスクに取り組むために、単純なルールとローカルコミュニケーションに依存しています。
それがswarmの知能の魔法です。この動作は、群れの知能を模倣することで困難な問題を解決するアルゴリズムを使用して再現できます。
粒子群最適化(PSO)
PSOでは、粒子が検索スペースを探索します。彼らは、2つの主な要因に基づいて位置を調整します。個人の最もよく知られている位置と、群れ全体の最も有名な位置です。このデュアルフィードバックメカニズムにより、それらはグローバルな最適に収束することができます。
粒子群の最適化がどのように機能するか
プロセスは、溶液スペース全体にランダムに初期化された粒子の群れから始まります。各粒子は、最適化問題に対する可能な解決策を表します。粒子が移動すると、彼らは自分のベストポジション(これまでに遭遇した最高の解決策)を覚えており、グローバルな最高の位置(あらゆる粒子が見つけた最高のソリューション)に引き付けられます。
この動きは、搾取と探索の2つの要因によって駆動されます。搾取には、現在の最良のソリューションを中心に検索を改良することが含まれますが、探索は粒子がソリューションスペースの他の部分を検索して、ローカルオプティマに閉じ込められないようにすることを促進します。これら2つのダイナミクスのバランスをとることにより、PSOは最適なソリューションに効率的に収束します。財務ポートフォリオ管理では、リスクを低く保ちながら最も収益を得るために資産を割り当てる最良の方法を見つけることは難しい場合があります。 PSOを使用して、どの資産が投資収益率が高いかを見つけましょう。
以下のコードは、架空の金融ポートフォリオを最適化するためにPSOがどのように機能するかを示しています。それはランダムな資産の割り当てから始まり、その後、最適なものに基づいていくつかの反復を微調整し、最も低いリスクを伴う最高のリターンの最適なミックスを徐々に見つけます。
import numpy as np import matplotlib.pyplot as plt # Define the PSO parameters class Particle: def __init__(self, n_assets): # Initialize a particle with random weights and velocities self.position = np.random.rand(n_assets) self.position /= np.sum(self.position) # Normalize weights so they sum to 1 self.velocity = np.random.rand(n_assets) self.best_position = np.copy(self.position) self.best_score = float('inf') # Start with a very high score def objective_function(weights, returns, covariance): """ Calculate the portfolio's performance. - weights: Asset weights in the portfolio. - returns: Expected returns of the assets. - covariance: Covariance matrix representing risk. """ portfolio_return = np.dot(weights, returns) # Calculate the portfolio return portfolio_risk = np.sqrt(np.dot(weights.T, np.dot(covariance, weights))) # Calculate portfolio risk (standard deviation) return -portfolio_return / portfolio_risk # We want to maximize return and minimize risk def update_particles(particles, global_best_position, returns, covariance, w, c1, c2): """ Update the position and velocity of each particle. - particles: List of particle objects. - global_best_position: Best position found by all particles. - returns: Expected returns of the assets. - covariance: Covariance matrix representing risk. - w: Inertia weight to control particle's previous velocity effect. - c1: Cognitive coefficient to pull particles towards their own best position. - c2: Social coefficient to pull particles towards the global best position. """ for particle in particles: # Random coefficients for velocity update r1, r2 = np.random.rand(len(particle.position)), np.random.rand(len(particle.position)) # Update velocity particle.velocity = (w * particle.velocity + c1 * r1 * (particle.best_position - particle.position) + c2 * r2 * (global_best_position - particle.position)) # Update position particle.position += particle.velocity particle.position = np.clip(particle.position, 0, 1) # Ensure weights are between 0 and 1 particle.position /= np.sum(particle.position) # Normalize weights to sum to 1 # Evaluate the new position score = objective_function(particle.position, returns, covariance) if score < particle.best_score: # Update the particle's best known position and score particle.best_position = np.copy(particle.position) particle.best_score = score def pso_portfolio_optimization(n_particles, n_iterations, returns, covariance): """ Perform Particle Swarm Optimization to find the optimal asset weights. - n_particles: Number of particles in the swarm. - n_iterations: Number of iterations for the optimization. - returns: Expected returns of the assets. - covariance: Covariance matrix representing risk. """ # Initialize particles particles = [Particle(len(returns)) for _ in range(n_particles)] # Initialize global best position global_best_position = np.random.rand(len(returns)) global_best_position /= np.sum(global_best_position) global_best_score = float('inf') # PSO parameters w = 0.5 # Inertia weight: how much particles are influenced by their own direction c1 = 1.5 # Cognitive coefficient: how well particles learn from their own best solutions c2 = 0.5 # Social coefficient: how well particles learn from global best solutions history = [] # To store the best score at each iteration for _ in range(n_iterations): update_particles(particles, global_best_position, returns, covariance, w, c1, c2) for particle in particles: score = objective_function(particle.position, returns, covariance) if score < global_best_score: # Update the global best position and score global_best_position = np.copy(particle.position) global_best_score = score # Store the best score (negative return/risk ratio) for plotting history.append(-global_best_score) return global_best_position, history # Example data for 3 assets returns = np.array([0.02, 0.28, 0.15]) # Expected returns for each asset covariance = np.array([[0.1, 0.02, 0.03], # Covariance matrix for asset risks [0.02, 0.08, 0.04], [0.03, 0.04, 0.07]]) # Run the PSO algorithm n_particles = 10 # Number of particles n_iterations = 10 # Number of iterations best_weights, optimization_history = pso_portfolio_optimization(n_particles, n_iterations, returns, covariance) # Plotting the optimization process plt.figure(figsize=(12, 6)) plt.plot(optimization_history, marker='o') plt.title('Portfolio Optimization Using PSO') plt.xlabel('Iteration') plt.ylabel('Objective Function Value (Negative of Return/Risk Ratio)') plt.grid(False) # Turn off gridlines plt.show() # Display the optimal asset weights print(f"Optimal Asset Weights: {best_weights}")
粒子群最適化のアプリケーション
機械学習:PSOを適用して機械学習アルゴリズムでハイパーパラメーターを調整し、最適なモデル構成を見つけるのに役立ちます。
エンジニアリング設計:PSOは、航空宇宙コンポーネントや電気回路などのシステムの設計パラメーターを最適化するのに役立ちます。
財務モデリング:金融では、PSOはポートフォリオの最適化に役立ち、リスクを最小限に抑えながらリターンを最小限に抑えます。ABCアルゴリズムでは、ミツバチの群れは、採用されたミツバチ、見物人、スカウトの3つの特別な役割に分割されています。これらの役割のそれぞれは、ミツバチが自然の中で食物源を検索して活用する方法の異なる側面を模倣しています。
rastrigin関数は最適化に人気のある問題であり、多数の局所的最小値で知られているため、多くのアルゴリズムにとって困難な課題になっています。目標は単純です:グローバルな最小値を見つけます。
この例では、この問題に取り組むために、人工蜂コロニーアルゴリズムを使用します。 ABCアルゴリズムの各ミツバチは、検索スペースを調査し、機能を最小限に抑えるためのより良いソリューションを探しています。このコードは、新しいエリアを探索、悪用、および偵察するミツバチをシミュレートし、探索と搾取のバランスを確保します。このグラフは、各反復でABCアルゴリズムによって見つかった最良のソリューションのフィットネスを示しています。この実行では、64回目の反復周辺で最適なフィットネスに達しました。
import numpy as np import matplotlib.pyplot as plt # Define the PSO parameters class Particle: def __init__(self, n_assets): # Initialize a particle with random weights and velocities self.position = np.random.rand(n_assets) self.position /= np.sum(self.position) # Normalize weights so they sum to 1 self.velocity = np.random.rand(n_assets) self.best_position = np.copy(self.position) self.best_score = float('inf') # Start with a very high score def objective_function(weights, returns, covariance): """ Calculate the portfolio's performance. - weights: Asset weights in the portfolio. - returns: Expected returns of the assets. - covariance: Covariance matrix representing risk. """ portfolio_return = np.dot(weights, returns) # Calculate the portfolio return portfolio_risk = np.sqrt(np.dot(weights.T, np.dot(covariance, weights))) # Calculate portfolio risk (standard deviation) return -portfolio_return / portfolio_risk # We want to maximize return and minimize risk def update_particles(particles, global_best_position, returns, covariance, w, c1, c2): """ Update the position and velocity of each particle. - particles: List of particle objects. - global_best_position: Best position found by all particles. - returns: Expected returns of the assets. - covariance: Covariance matrix representing risk. - w: Inertia weight to control particle's previous velocity effect. - c1: Cognitive coefficient to pull particles towards their own best position. - c2: Social coefficient to pull particles towards the global best position. """ for particle in particles: # Random coefficients for velocity update r1, r2 = np.random.rand(len(particle.position)), np.random.rand(len(particle.position)) # Update velocity particle.velocity = (w * particle.velocity + c1 * r1 * (particle.best_position - particle.position) + c2 * r2 * (global_best_position - particle.position)) # Update position particle.position += particle.velocity particle.position = np.clip(particle.position, 0, 1) # Ensure weights are between 0 and 1 particle.position /= np.sum(particle.position) # Normalize weights to sum to 1 # Evaluate the new position score = objective_function(particle.position, returns, covariance) if score < particle.best_score: # Update the particle's best known position and score particle.best_position = np.copy(particle.position) particle.best_score = score def pso_portfolio_optimization(n_particles, n_iterations, returns, covariance): """ Perform Particle Swarm Optimization to find the optimal asset weights. - n_particles: Number of particles in the swarm. - n_iterations: Number of iterations for the optimization. - returns: Expected returns of the assets. - covariance: Covariance matrix representing risk. """ # Initialize particles particles = [Particle(len(returns)) for _ in range(n_particles)] # Initialize global best position global_best_position = np.random.rand(len(returns)) global_best_position /= np.sum(global_best_position) global_best_score = float('inf') # PSO parameters w = 0.5 # Inertia weight: how much particles are influenced by their own direction c1 = 1.5 # Cognitive coefficient: how well particles learn from their own best solutions c2 = 0.5 # Social coefficient: how well particles learn from global best solutions history = [] # To store the best score at each iteration for _ in range(n_iterations): update_particles(particles, global_best_position, returns, covariance, w, c1, c2) for particle in particles: score = objective_function(particle.position, returns, covariance) if score < global_best_score: # Update the global best position and score global_best_position = np.copy(particle.position) global_best_score = score # Store the best score (negative return/risk ratio) for plotting history.append(-global_best_score) return global_best_position, history # Example data for 3 assets returns = np.array([0.02, 0.28, 0.15]) # Expected returns for each asset covariance = np.array([[0.1, 0.02, 0.03], # Covariance matrix for asset risks [0.02, 0.08, 0.04], [0.03, 0.04, 0.07]]) # Run the PSO algorithm n_particles = 10 # Number of particles n_iterations = 10 # Number of iterations best_weights, optimization_history = pso_portfolio_optimization(n_particles, n_iterations, returns, covariance) # Plotting the optimization process plt.figure(figsize=(12, 6)) plt.plot(optimization_history, marker='o') plt.title('Portfolio Optimization Using PSO') plt.xlabel('Iteration') plt.ylabel('Objective Function Value (Negative of Return/Risk Ratio)') plt.grid(False) # Turn off gridlines plt.show() # Display the optimal asset weights print(f"Optimal Asset Weights: {best_weights}")
ここでは、輪郭プロットにプロットされたrastrigin関数が、その多くの局所的な最小値を見ることができます。赤いドットは、実行したABCアルゴリズムによって見つかったグローバルミニマです。
ABCアルゴリズムは、最適化の問題を解決するための堅牢なツールです。大規模で複雑な検索スペースを効率的に探索する能力により、適応性とスケーラビリティが重要な業界にとって頼りになる選択肢になります。
これらのアプリケーションには次のものが含まれます
複数のSwarm Intelligenceアルゴリズムがあり、それぞれ異なる属性を持つ。どちらを使用するかを決定するとき、あなたのニーズに最適なものを決定するために、彼らの長所と短所を比較検討することが重要です。
ACOは、ルーティングやスケジューリングなどの組み合わせ問題に効果的ですが、重要な計算リソースが必要になる場合があります。 PSOはよりシンプルで、ハイパーパラメーターのチューニングなどの継続的な最適化に優れていますが、ローカルオプティマに苦労する可能性があります。 ABCは、慎重な調整が必要ですが、探査と搾取のバランスに成功しています。
弱点 |
優先ライブラリ |
最高のアプリケーション |
|
アリコロニー最適化(ACO) |
||||
複雑な離散スペースをうまく組み合わせた問題と処理に効果的に 計算的に集中しており、微調整 | が必要です
pyaco |
ルーティングの問題、スケジューリング、およびリソース割り当て |
|
粒子群最適化(PSO) |
||||
継続的な最適化とシンプルで簡単に実装できるのに適しています はローカルオプティマに収束することができ、離散問題に対してはあまり効果的ではありません |
pyswarms |
ハイパーパラメーターチューニング、エンジニアリング設計、財務モデリング |
|
人工蜂コロニー(ABC) |
||||
大規模で動的な問題とバランスの取れた探索と搾取に適応できる 計算的に集中しており、慎重なパラメーターチューニング | が必要です
beecolpy |
電気通信、大規模な最適化、および高次元空間 |
|
fireflyアルゴリズム(FA) |
マルチモーダルの最適化に優れており、強力なグローバル検索能力を持っています |
パラメーターの設定と収束が遅いことに敏感 |
fireflyalgorithm |
画像処理、エンジニアリング設計、およびマルチモーダル最適化 |
Cuckoo Search(cs) |
最適化の問題を解決するのに効率的で、強力な探索機能を備えています
|
は、早期に収束する場合があり、パフォーマンスはチューニング に依存します |
cso
|
スケジューリング、機能選択、およびエンジニアリングアプリケーション
|
以上がSwarm Intelligence Algorithms:3つのPython実装の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。