ホームページ > テクノロジー周辺機器 > AI > Swarm Intelligence Algorithms:3つのPython実装

Swarm Intelligence Algorithms:3つのPython実装

尊渡假赌尊渡假赌尊渡假赌
リリース: 2025-03-03 09:35:09
オリジナル
212 人が閲覧しました

飛行中に鳥の群れを見ていると想像してみてください。リーダーも、誰も指示を与えていませんが、彼らは完全に調和して急降下して滑ります。カオスのように見えるかもしれませんが、隠された順序があります。捕食者やアリが食物への最短の道を見つけることを避ける魚の学校で同じパターンを見ることができます。これらのクリーチャーは、中央制御なしで驚くほど複雑なタスクに取り組むために、単純なルールとローカルコミュニケーションに依存しています。

それがswarmの知能の魔法です。 

この動作は、群れの知能を模倣することで困難な問題を解決するアルゴリズムを使用して再現できます。

粒子群最適化(PSO)

粒子群最適化(PSO)は、鳥の群れや魚の群れの行動からインスピレーションを得ています。これらの自然なシステムでは、個人は自分の以前の経験と隣人の立場に基づいて動き、グループの最も成功したメンバーに従うように徐々に調整します。 PSOは、この概念を最適化の問題に適用します。ここで、エージェントと呼ばれる粒子が検索空間を移動して最適なソリューションを見つけます。

ACOと比較して、PSOは個別の空間ではなく連続して動作します。 ACOでは、パスファインディングと個別の選択に焦点が当てられていますが、PSOはパラメーターチューニングなどの連続変数を含む問題に適しています。 

PSOでは、粒子が検索スペースを探索します。彼らは、2つの主な要因に基づいて位置を調整します。個人の最もよく知られている位置と、群れ全体の最も有名な位置です。このデュアルフィードバックメカニズムにより、それらはグローバルな最適に収束することができます。

粒子群の最適化がどのように機能するか

プロセスは、溶液スペース全体にランダムに初期化された粒子の群れから始まります。各粒子は、最適化問題に対する可能な解決策を表します。粒子が移動すると、彼らは自分のベストポジション(これまでに遭遇した最高の解決策)を覚えており、グローバルな最高の位置(あらゆる粒子が見つけた最高のソリューション)に引き付けられます。

この動きは、搾取と探索の2つの要因によって駆動されます。搾取には、現在の最良のソリューションを中心に検索を改良することが含まれますが、探索は粒子がソリューションスペースの他の部分を検索して、ローカルオプティマに閉じ込められないようにすることを促進します。これら2つのダイナミクスのバランスをとることにより、PSOは最適なソリューションに効率的に収束します。

粒子群最適化Python実装

財務ポートフォリオ管理では、リスクを低く保ちながら最も収益を得るために資産を割り当てる最良の方法を見つけることは難しい場合があります。 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}")
ログイン後にコピー
ログイン後にコピー

Swarm Intelligence Algorithms:3つのPython実装

このグラフは、PSOアルゴリズムが各反復とのポートフォリオのアセットミックスをどれだけ改善したかを示しています。

粒子群最適化のアプリケーション

PSOは、特に連続ドメインで、さまざまな最適化問題を解決する際にその単純さと有効性に使用されます。その柔軟性により、正確なソリューションが必要な多くの現実世界のシナリオに役立ちます。

これらのアプリケーションには次のものが含まれます

機械学習:PSOを適用して機械学習アルゴリズムでハイパーパラメーターを調整し、最適なモデル構成を見つけるのに役立ちます。

エンジニアリング設計:PSOは、航空宇宙コンポーネントや電気回路などのシステムの設計パラメーターを最適化するのに役立ちます。

財務モデリング:金融では、PSOはポートフォリオの最適化に役立ち、リスクを最小限に抑えながらリターンを最小限に抑えます。
  • PSOのソリューションスペースを効率的に探索する能力により、ロボット工学からエネルギー管理、ロジスティクスまで、フィールド全体で適用できます。
  • 人工蜂コロニー(ABC)
  • 人工蜂コロニー(ABC)アルゴリズムは、ミツバチの採餌挙動をモデル化しています。
  • 本質的に、ミツバチは蜜源を効率的に検索し、この情報を他の巣のメンバーと共有します。 ABCはこの共同検索プロセスをキャプチャし、最適化の問題、特に複雑で高次元の空間を含む問題に適用します。
  • ABCを他のSwarm Intelligenceアルゴリズムと際立たせるのは、搾取のバランスをとる能力、現在のソリューションの改良と探索に焦点を当て、新しい潜在的に優れたソリューションを検索することです。これにより、ABCはグローバルな最適化が重要な大規模な問題に特に役立ちます。
人工蜂コロニーがどのように機能するか

ABCアルゴリズムでは、ミツバチの群れは、採用されたミツバチ、見物人、スカウトの3つの特別な役割に分割されています。これらの役割のそれぞれは、ミツバチが自然の中で食物源を検索して活用する方法の異なる側面を模倣しています。
  • 採用されたミツバチ:これらのミツバチは、既知の食物源を探索する責任があり、最適化問題の現在の溶液を表しています。これらのソースの品質(フィットネス)を評価し、情報を残りのハイブと共有します。
  • Onlooker Bees:雇用されているミツバチから情報を収集した後、見物人はさらに探索する食物源を選択します。彼らは、雇用されているミツバチが共有するソリューションの品質に基づいて選択し、より良いオプションにもっと焦点を合わせて、最適なソリューションの検索を改善します。
  • スカウトミツバチ:採用されたミツバチの食物源(ソリューション)が使い果たされたり停滞したりすると(特定の数の反復後に改善が見つからない場合)、ミツバチはスカウトになります。スカウトは、解決策スペースの新しい領域を探索し、潜在的に未開拓の食物源を探して、検索プロセスに多様性を注入します。
  • この動的により、ABCは、有望な領域を集中的に探索し、検索スペースの新しい領域を広く探索することの間の検索のバランスをとることができます。これにより、アルゴリズムはローカルオプティマに閉じ込められないようにし、グローバルな最適を見つける可能性を高めます。
  • 人工ビーコロニーPython実装

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}")
ログイン後にコピー
ログイン後にコピー

Swarm Intelligence Algorithms:3つのPython実装ここでは、輪郭プロットにプロットされたrastrigin関数が、その多くの局所的な最小値を見ることができます。赤いドットは、実行したABCアルゴリズムによって見つかったグローバルミニマです。

人工蜂コロニーの応用

ABCアルゴリズムは、最適化の問題を解決するための堅牢なツールです。大規模で複雑な検索スペースを効率的に探索する能力により、適応性とスケーラビリティが重要な業界にとって頼りになる選択肢になります。

これらのアプリケーションには次のものが含まれます

  • 電気通信:ABCを使用して、ネットワークリソースとアンテナの配置を最適化し、コストを最小限に抑えながらカバレッジと信号強度を最大化できます。
  • エンジニアリング:ABCは、構造設計最適化のパラメーターを微調整できます
  • データサイエンス:ABCは、機械学習のデータセット内の最も重要な変数を特定するために機能の選択に適用できます。
  • ABCは、動的で高次元の環境で最適なソリューションを見つける必要がある問題に適した柔軟なアルゴリズムです。その分散型の性質により、他のアルゴリズムが探索と搾取のバランスを効率的にバランスさせるのに苦労する可能性がある状況に適しています。
  • Swarm Intelligence Algorithmsの比較

複数のSwarm Intelligenceアルゴリズムがあり、それぞれ異なる属性を持つ。どちらを使用するかを決定するとき、あなたのニーズに最適なものを決定するために、彼らの長所と短所を比較検討することが重要です。

ACOは、ルーティングやスケジューリングなどの組み合わせ問題に効果的ですが、重要な計算リソースが必要になる場合があります。 PSOはよりシンプルで、ハイパーパラメーターのチューニングなどの継続的な最適化に優れていますが、ローカルオプティマに苦労する可能性があります。 ABCは、慎重な調整が必要ですが、探査と搾取のバランスに成功しています。

FireflyアルゴリズムやCuckoo検索最適化などの他のSwarm Intelligence Algorithmsも、特定のタイプの最適化問題に独自の利点を提供します。

アルゴリズム強みが必要です が必要です

課題と制限

多くの機械学習技術と同様に、Swarm Intelligence Algorithmsは、パフォーマンスに影響を与える可能性のある課題に遭遇します。これらには次のものが含まれます

    未熟な収束:群れは、最適下の解であまりにも速く落ち着く可能性があります。
  1. パラメーターチューニング:最適な結果を達成するには、多くの場合、アルゴリズム設定を慎重に調整する必要があります。
  2. 計算リソースとスケーラビリティ:これらのアルゴリズムは、特により大きく、より複雑な問題で計算的に集中的である可能性があり、問題の複雑さが増加するにつれてパフォーマンスが低下する可能性があります。
  3. 確率的性質:これらのアルゴリズムの固有のランダム性は、結果の変動につながる可能性があります。
  4. 最新の研究と進歩
  5. 顕著な傾向は、群れの知能を他の機械学習技術と統合することです。研究者は、群れのアルゴリズムが機能の選択やハイパーパラメーターの最適化などのタスクをどのように強化できるかを調査しています。エンジニアリングの問題を解決するためのハイブリッド粒子群最適化アルゴリズムをチェックしてください。
最近の進歩は、早期収束など、群れの知能に関連する伝統的な課題のいくつかに対処することにも焦点を当てています。最適でないソリューションに収束するリスクを緩和するために、新しいアルゴリズムと手法が開発されています。詳細については、粒子群群最適化の早期収束を排除するためのメモリベースのアプローチをご覧ください

スケーラビリティは、研究のもう1つの重要な分野です。問題がますます複雑になり、データ量が増加するにつれて、研究者はSwarm Intelligenceアルゴリズムをよりスケーラブルで効率的にする方法に取り組んでいます。これには、大規模なデータセットと高次元スペースをより効果的に処理できるアルゴリズムの開発が含まれ、これらのアルゴリズムの実行に関連する時間とコストを削減するための計算リソースを最適化します。これの詳細については、群れ検索の理論と適用性に関する最近の開発をご覧ください。

群アルゴリズムは、ロボット工学、大規模な言語モデル(LLM)、医学的診断までの問題に適用されています。これらのアルゴリズムが、LLMSが忘れられた規制の権利を遵守するための情報を戦略的に忘れるのに役立つかどうかについて、継続的な研究があります。そして、もちろん、Swarm Algorithmsにはデータサイエンスに多数のアプリケーションがあります。

結論

Swarm Intelligenceは、さまざまな業界で最適化問題のための強力なソリューションを提供します。地方分権化、肯定的なフィードバック、および適応の原則により、従来のアルゴリズムが苦労する可能性のある複雑で動的なタスクに取り組むことができます。 

群れのアルゴリズムの現在の状態「Swarm Intelligence:A Survey of Model Spalsification and Applications」のこのレビューをご覧ください。

AIのビジネスアプリケーションをより深く掘り下げるには、ビジネスリーダー向けの人工知能(AI)戦略または人工知能をチェックしてください。自然を模倣した他のアルゴリズムについて学ぶには、遺伝的アルゴリズムをご覧ください:Python実装を備えた完全なガイド。

弱点

優先ライブラリ

最高のアプリケーション

アリコロニー最適化(ACO)

複雑な離散スペースをうまく組み合わせた問題と処理に効果的に

計算的に集中しており、微調整

pyaco

ルーティングの問題、スケジューリング、およびリソース割り当て

粒子群最適化(PSO)

継続的な最適化とシンプルで簡単に実装できるのに適しています

はローカルオプティマに収束することができ、離散問題に対してはあまり効果的ではありません

pyswarms

ハイパーパラメーターチューニング、エンジニアリング設計、財務モデリング

人工蜂コロニー(ABC)

大規模で動的な問題とバランスの取れた探索と搾取に適応できる

計算的に集中しており、慎重なパラメーターチューニング

beecolpy

電気通信、大規模な最適化、および高次元空間

fireflyアルゴリズム(FA)

マルチモーダルの最適化に優れており、強力なグローバル検索能力を持っています

パラメーターの設定と収束が遅いことに敏感

fireflyalgorithm

画像処理、エンジニアリング設計、およびマルチモーダル最適化

Cuckoo Search(cs)

最適化の問題を解決するのに効率的で、強力な探索機能を備えています

は、早期に収束する場合があり、パフォーマンスはチューニング

に依存します

cso

スケジューリング、機能選択、およびエンジニアリングアプリケーション

以上がSwarm Intelligence Algorithms:3つのPython実装の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート