グラフ理論基礎とNetworkX入門
グラフとは?
グラフは以下で構成されます:
- ノード(頂点):実体(都市、人物、Webページ)
- エッジ:関係(道路、友情、リンク)
実生活の例
| シナリオ | ノード | エッジ | |---------|-------|-------| | 地図ナビ | 交差点 | 道路 | | SNS | 人物 | 友情関係 | | ネットワーク | サーバー | ケーブル |
グラフの種類
- 有向グラフ:エッジに方向あり
- 無向グラフ:エッジに方向なし
- 重み付きグラフ:エッジに重みあり
NetworkXのインストール
pip install networkx matplotlib numpy
🔥 Vibe プロンプト
「SNSグラフを分析:50ノードを作成、次数中心性と媒介中心性を計算、上位5ノードを色の濃淡で可視化。」
NetworkX実装
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
# グラフ作成
G = nx.Graph()
# ノード追加
G.add_node("台北")
G.add_node("台中")
G.add_node("高雄")
G.add_node("台南")
G.add_node("桃園")
# エッジ追加(重み付き)
G.add_edge("台北", "台中", weight=180)
G.add_edge("台中", "高雄", weight=200)
G.add_edge("台北", "桃園", weight=40)
G.add_edge("台中", "台南", weight=150)
G.add_edge("高雄", "台南", weight=70)
# 可視化
pos = nx.spring_layout(G, seed=42)
nx.draw(G, pos, with_labels=True, node_color='lightblue', node_size=1500, font_size=12)
labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
plt.title("台湾都市ネットワーク")
plt.show()
print(f"ノード数: {G.number_of_nodes()}")
print(f"エッジ数: {G.number_of_edges()}")
print(f"次数: {dict(G.degree())}")
SNSグラフ分析
# SNSネットワークを生成(50人)
np.random.seed(42)
G_social = nx.erdos_renyi_graph(n=50, p=0.08, seed=42)
# 中心性指標
degree_cent = nx.degree_centrality(G_social)
between_cent = nx.betweenness_centrality(G_social)
closeness_cent = nx.closeness_centrality(G_social)
# トップ5
top5_degree = sorted(degree_cent.items(), key=lambda x: x[1], reverse=True)[:5]
top5_between = sorted(between_cent.items(), key=lambda x: x[1], reverse=True)[:5]
print(f"\n=== SNS分析結果 ===")
print(f"\n次数中心性トップ5:")
for node, score in top5_degree:
print(f" ノード{node}: {score:.4f}")
print(f"\n媒介中心性トップ5:")
for node, score in top5_between:
print(f" ノード{node}: {score:.4f}")
# 可視化
colors = [degree_cent[n] * 100 for n in G_social.nodes()]
pos = nx.spring_layout(G_social, seed=42)
nx.draw(G_social, pos, node_color=colors, cmap=plt.cm.Blues,
node_size=500, with_labels=False)
plt.title("SNSネットワーク — 次数中心性(濃いほど重要)")
plt.show()
まとめ
| 概念 | 説明 | |------|------| | ノード | グラフの実体(都市、人物、ページ) | | エッジ | ノード間の関係 | | 次数 | ノードに接続するエッジ数 | | 中心性 | ノードの重要度指標 | | NetworkX | Pythonグラフ分析ライブラリ | | 応用 | SNS分析、路線図、推薦システムめ\n\n| 概念 | 説明 |\n|------|------|\n| ノード | グラフの実体(都市、人物、ページ) |\n| エッジ | ノード間の関係 |\n| 次数 | ノードに接続するエッジ数 |\n| 中心性 | ノードの重要度指標 |\n| NetworkX | Pythonグラフ分析ライブラリ |\n| 応用 | SNS分析、路線図、推薦システム |"}]}