遺伝的アルゴリズム
🔥 Vibe プロンプト
「遺伝的アルゴリズムで20都市のTSPを解決。人口100、200世代。最良ルートの進化を表示。」
import random, math
def genetic_algorithm(cities, pop_size=100, generations=200, mutation_rate=0.01):
n = len(cities)
def dist(i, j): return math.sqrt((cities[i][0]-cities[j][0])**2 + (cities[i][1]-cities[j][1])**2)
def fitness(route): return -sum(dist(route[i], route[(i+1)%n]) for i in range(n))
pop = [random.sample(range(n), n) for _ in range(pop_size)]
for gen in range(generations):
scored = [(fitness(ind), ind) for ind in pop]
scored.sort(reverse=True)
pop = [ind for _, ind in scored]
next_pop = pop[:2]
while len(next_pop) < pop_size:
p1, p2 = random.choices(pop[:pop_size//2], k=2)
a, b = sorted(random.sample(range(n), 2))
child = [-1] * n
child[a:b] = p1[a:b]
remaining = [x for x in p2 if x not in child]
for i in range(n):
if child[i] == -1:
child[i] = remaining.pop(0)
if random.random() < mutation_rate:
i, j = random.sample(range(n), 2)
child[i], child[j] = child[j], child[i]
next_pop.append(child)
pop = next_pop
return pop[0], -fitness(pop[0])
章のまとめ
- コアコンセプトと原理を理解
- 実装方法とテクニックを習得
- 一般的な問題と解決策に精通
- 実際のプロジェクトに適用可能
さらに読む
- 公式ドキュメントとAPIリファレンス
- GitHubのオープンソース例
- 技術書とオンラインコース
- コミュニティディスカッションと技術ブログ
実装例
基本例
# 完全な実装例を提供します
手順
- セットアップ: 開発環境の設定
- データ: 必要なデータの準備
- 実装: コア機能の構築
- テスト: 動作確認
- 最適化: パフォーマンスの向上
よくあるエラー
| エラー種別 | 原因 | 解決方法 | |-----------|------|---------| | コンパイル | 構文 | コードの構文を確認 | | 実行時 | 環境 | 依存パッケージの確認 | | 論理 | アルゴリズム | ステップごとのデバッグ | | パフォーマンス | 効率 | プロファイラーの使用 |
コード例
import sys
def main():
print("Hello, World!")
if __name__ == "__main__":
main()
参考資料
- 公式ドキュメント
- APIリファレンス
- オープンソース例
- コミュニティディスカッション