name: 网络分析 description: 分析网络结构,识别社区,测量中心性,并为社交网络和组织结构可视化关系
网络分析
概览
这项技能能够分析网络结构,识别社区,测量中心性,检测有影响力的节点,并为社交网络、组织结构和互联系统可视化复杂关系。
使用场景
- 分析社交网络以识别有影响力的用户和社区结构
- 映射组织层级并识别关键连接点或瓶颈
- 研究引用网络以找到有影响力的研究论文和合作模式
- 基于网络关系和相似性构建推荐系统
- 分析供应链网络以优化物流并识别漏洞
- 通过金融交易网络分析检测欺诈模式
网络概念
- 节点:个体实体
- 边:连接/关系
- 度:连接数
- 中心性:节点重要性度量
- 社区:密集连接的群体
- 聚类系数:局部密度
关键指标
- 度中心性:连接数
- 中介中心性:路径控制
- 接近中心性:到其他节点的平均距离
- 特征向量中心性:与重要节点的连接
- 模块化:社区结构强度
使用Python实现
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
from collections import defaultdict, Counter
import seaborn as sns
# 创建样本网络(社交网络)
G = nx.Graph()
# 添加带有属性的节点
nodes = [
('Alice', {'role': 'Manager', 'dept': 'Sales'}),
('Bob', {'role': 'Engineer', 'dept': 'Tech'}),
('Carol', {'role': 'Designer', 'dept': 'Design'}),
('David', {'role': 'Engineer', 'dept': 'Tech'}),
('Eve', {'role': 'Analyst', 'dept': 'Sales'}),
('Frank', {'role': 'Manager', 'dept': 'HR'}),
('Grace', {'role': 'Designer', 'dept': 'Design'}),
('Henry', {'role': 'Engineer', 'dept': 'Tech'}),
('Iris', {'role': 'Analyst', 'dept': 'Sales'}),
('Jack', {'role': 'Manager', 'dept': 'Finance'}),
]
for node, attrs in nodes:
G.add_node(node, **attrs)
# 添加边(关系)
edges = [
('Alice', 'Bob'), ('Alice', 'Carol'), ('Alice', 'Eve'),
('Bob', 'David'), ('Bob', 'Henry'), ('Carol', 'Grace'),
('David', 'Henry'), ('Eve', 'Iris'), ('Frank', 'Jack'),
('Grace', 'Carol'), ('Alice', 'Frank'), ('Bob', 'Carol'),
('Eve', 'Alice'), ('Iris', 'Eve'), ('Jack', 'Frank'),
('Henry', 'David'), ('Carol', 'David'),
]
G.add_edges_from(edges)
print("网络摘要:")
print(f"节点:{G.number_of_nodes()}")
print(f"边:{G.number_of_edges()}")
print(f"密度:{nx.density(G):.2%}")
# 1. 度中心性
degree_centrality = nx.degree_centrality(G)
print("
1. 度中心性(前5名):")
for node, score in sorted(degree_centrality.items(), key=lambda x: x[1], reverse=True)[:5]:
print(f" {node}: {score:.3f}")
# 2. 中介中心性(控制网络)
betweenness_centrality = nx.betweenness_centrality(G)
print("
2. 中介中心性(前5名):")
for node, score in sorted(betweenness_centrality.items(), key=lambda x: x[1], reverse=True)[:5]:
print(f" {node}: {score:.3f}")
# 3. 接近中心性(到其他节点的平均距离)
closeness_centrality = nx.closeness_centrality(G)
print("
3. 接近中心性(前5名):")
for node, score in sorted(closeness_centrality.items(), key=lambda x: x[1], reverse=True)[:5]:
print(f" {node}: {score:.3f}")
# 4. 特征向量中心性
try:
eigenvector_centrality = nx.eigenvector_centrality(G, max_iter=100)
print("
4. 特征向量中心性(前5名):")
for node, score in sorted(eigenvector_centrality.items(), key=lambda x: x[1], reverse=True)[:5]:
print(f" {node}: {score:.3f}")
except:
print("
4. 特征向量中心性:未收敛")
# 5. 社区检测(使用模块化)
from networkx.algorithms import community
communities = list(community.greedy_modularity_communities(G))
print(f"
5. 社区检测:")
print(f"社区数量:{len(communities)}")
for i, comm in enumerate(communities):
print(f" 社区 {i+1}: {list(comm)}")
# 6. 网络统计
degrees = [G.degree(n) for n in G.nodes()]
print(f"
6. 网络统计:")
print(f"平均度:{np.mean(degrees):.2f}")
print(f"最大度:{max(degrees)}")
print(f"最小度:{min(degrees)}")
print(f"聚类系数:{nx.average_clustering(G):.3f}")
print(f"三角形数量:{sum(nx.triangles(G).values()) // 3}")
# 可视化
fig, axes = plt.subplots(2, 2, figsize=(15, 12))
# 网络布局
pos = nx.spring_layout(G, k=0.5, iterations=50, seed=42)
# 1. 网络图(按度中心性着色)
ax = axes[0, 0]
node_colors = [degree_centrality[node] for node in G.nodes()]
nx.draw_networkx_nodes(G, pos, node_color=node_colors, node_size=1000, cmap='YlOrRd', ax=ax)
nx.draw_networkx_edges(G, pos, alpha=0.5, ax=ax)
nx.draw_networkx_labels(G, pos, font_size=8, ax=ax)
ax.set_title('网络图(按度中心性着色)')
ax.axis('off')
# 2. 网络图(按社区着色)
ax = axes[0, 1]
color_map = []
colors = plt.cm.Set3(np.linspace(0, 1, len(communities)))
node_to_color = {}
for i, comm in enumerate(communities):
for node in comm:
node_to_color[node] = colors[i]
color_map = [node_to_color[node] for node in G.nodes()]
nx.draw_networkx_nodes(G, pos, node_color=color_map, node_size=1000, ax=ax)
nx.draw_networkx_edges(G, pos, alpha=0.5, ax=ax)
nx.draw_networkx_labels(G, pos, font_size=8, ax=ax)
ax.set_title('网络图(按社区着色)')
ax.axis('off')
# 3. 中心性比较
ax = axes[1, 0]
centrality_df = pd.DataFrame({
'度': degree_centrality,
'中介性': betweenness_centrality,
'接近性': closeness_centrality,
}).head(8)
centrality_df.plot(kind='barh', ax=ax, width=0.8)
ax.set_xlabel('中心性得分')
ax.set_title('前8节点 - 中心性比较')
ax.legend(loc='lower right')
ax.grid(True, alpha=0.3, axis='x')
# 4. 度分布
ax = axes[1, 1]
degree_sequence = sorted([d for n, d in G.degree()], reverse=True)
degree_count = Counter(degree_sequence)
degrees_unique = sorted(degree_count.keys())
counts = [degree_count[d] for d in degrees_unique]
ax.bar(degrees_unique, counts, color='steelblue', edgecolor='black', alpha=0.7)
ax.set_xlabel('度')
ax.set_ylabel('计数')
ax.set_title('度分布')
ax.grid(True, alpha=0.3, axis='y')
plt.tight_layout()
plt.show()
# 7. 路径分析
print(f"
7. 路径分析:")
try:
shortest_path = nx.shortest_path_length(G, 'Alice', 'Jack')
print(f"从Alice到Jack的最短路径:{shortest_path}")
except nx.NetworkXNoPath:
print("节点之间无路径存在")
# 8. 连通性分析
print(f"
8. 连通性分析:")
print(f"是否连通:{nx.is_connected(G)}")
num_components = nx.number_connected_components(G)
print(f"连通分量数量:{num_components}")
# 9. 相似性度量
def jaccard_similarity(node1, node2):
neighbors1 = set(G.neighbors(node1)) | {node1}
neighbors2 = set(G.neighbors(node2)) | {node2}
intersection = len(neighbors1 & neighbors2)
union = len(neighbors1 | neighbors2)
return intersection / union if union > 0 else 0
print(f"
9. 节点相似性(Jaccard):")
print(f"Alice & Bob: {jaccard_similarity('Alice', 'Bob'):.3f}")
print(f"Alice & Jack: {jaccard_similarity('Alice', 'Jack'):.3f}")
# 10. 影响力评分(组合度量)
influence_score = {}
for node in G.nodes():
score = (degree_centrality[node] * 0.4 +
betweenness_centrality[node] * 0.3 +
closeness_centrality[node] * 0.3)
influence_score[node] = score
print(f"
10. 影响力评分(前5名):")
for node, score in sorted(influence_score.items(), key=lambda x: x[1], reverse=True)[:5]:
print(f" {node}: {score:.3f}")
# 总结
print("
" + "="*50)
print("网络分析总结")
print("="*50)
print(f"最有影响力的:{max(influence_score, key=influence_score.get)}")
print(f"连接最多的:{max(degree_centrality, key=degree_centrality.get)}")
print(f"网络瓶颈:{max(betweenness_centrality, key=betweenness_centrality.get)}")
print(f"最接近所有节点的:{max(closeness_centrality, key=closeness_centrality.get)}")
print("="*50)
中心性度量
- 度:仅直接连接
- 中介性:群体间的桥梁
- 接近性:网络的接入
- 特征向量:与重要节点的连接
- PageRank:随机游走概率
社区检测
- 模块化优化:寻找密集群体
- Louvain算法:层次社区
- K-团:重叠社区
- 谱系:基于特征值
应用领域
- 社交网络分析
- 组织结构
- 引用网络
- 推荐网络
- 供应链分析
交付物
- 网络可视化
- 中心性分析
- 社区检测结果
- 连通性指标
- 影响力排名
- 关键节点识别
- 网络统计摘要