1
---
2
name: Network Analysis
3
description: Analyze network structures, identify communities, measure centrality, and visualize relationships for social networks and organizational structures
4
---
5
6
# Network Analysis
7
8
## Overview
9
10
This skill enables analysis of network structures to identify communities, measure centrality, detect influential nodes, and visualize complex relationships in social networks, organizational structures, and interconnected systems.
11
12
## When to Use
13
14
- Analyzing social networks to identify influential users and community structures
15
- Mapping organizational hierarchies and identifying key connectors or bottlenecks
16
- Studying citation networks to find impactful research papers and collaboration patterns
17
- Building recommendation systems based on network relationships and similarities
18
- Analyzing supply chain networks to optimize logistics and identify vulnerabilities
19
- Detecting fraud patterns through network analysis of financial transactions
20
21
## Network Concepts
22
23
- **Nodes**: Individual entities
24
- **Edges**: Connections/relationships
25
- **Degree**: Number of connections
26
- **Centrality**: Node importance measures
27
- **Community**: Densely connected groups
28
- **Clustering Coefficient**: Local density
29
30
## Key Metrics
31
32
- **Degree Centrality**: Number of connections
33
- **Betweenness Centrality**: Control over paths
34
- **Closeness Centrality**: Average distance to others
35
- **Eigenvector Centrality**: Connections to important nodes
36
- **Modularity**: Community structure strength
37
38
## Implementation with Python
39
40
```python
41
import pandas as pd
42
import numpy as np
43
import matplotlib.pyplot as plt
44
import networkx as nx
45
from collections import defaultdict, Counter
46
import seaborn as sns
47
48
# Create sample network (social network)
49
G = nx.Graph()
50
51
# Add nodes with attributes
52
nodes = [
53
('Alice', {'role': 'Manager', 'dept': 'Sales'}),
54
('Bob', {'role': 'Engineer', 'dept': 'Tech'}),
55
('Carol', {'role': 'Designer', 'dept': 'Design'}),
56
('David', {'role': 'Engineer', 'dept': 'Tech'}),
57
('Eve', {'role': 'Analyst', 'dept': 'Sales'}),
58
('Frank', {'role': 'Manager', 'dept': 'HR'}),
59
('Grace', {'role': 'Designer', 'dept': 'Design'}),
60
('Henry', {'role': 'Engineer', 'dept': 'Tech'}),
61
('Iris', {'role': 'Analyst', 'dept': 'Sales'}),
62
('Jack', {'role': 'Manager', 'dept': 'Finance'}),
63
]
64
65
for node, attrs in nodes:
66
G.add_node(node, **attrs)
67
68
# Add edges (relationships)
69
edges = [
70
('Alice', 'Bob'), ('Alice', 'Carol'), ('Alice', 'Eve'),
71
('Bob', 'David'), ('Bob', 'Henry'), ('Carol', 'Grace'),
72
('David', 'Henry'), ('Eve', 'Iris'), ('Frank', 'Jack'),
73
('Grace', 'Carol'), ('Alice', 'Frank'), ('Bob', 'Carol'),
74
('Eve', 'Alice'), ('Iris', 'Eve'), ('Jack', 'Frank'),
75
('Henry', 'David'), ('Carol', 'David'),
76
]
77
78
G.add_edges_from(edges)
79
80
print("Network Summary:")
81
print(f"Nodes: {G.number_of_nodes()}")
82
print(f"Edges: {G.number_of_edges()}")
83
print(f"Density: {nx.density(G):.2%}")
84
85
# 1. Degree Centrality
86
degree_centrality = nx.degree_centrality(G)
87
print("\n1. Degree Centrality (Top 5):")
88
for node, score in sorted(degree_centrality.items(), key=lambda x: x[1], reverse=True)[:5]:
89
print(f" {node}: {score:.3f}")
90
91
# 2. Betweenness Centrality (control over network)
92
betweenness_centrality = nx.betweenness_centrality(G)
93
print("\n2. Betweenness Centrality (Top 5):")
94
for node, score in sorted(betweenness_centrality.items(), key=lambda x: x[1], reverse=True)[:5]:
95
print(f" {node}: {score:.3f}")
96
97
# 3. Closeness Centrality (average distance to others)
98
closeness_centrality = nx.closeness_centrality(G)
99
print("\n3. Closeness Centrality (Top 5):")
100
for node, score in sorted(closeness_centrality.items(), key=lambda x: x[1], reverse=True)[:5]:
101
print(f" {node}: {score:.3f}")
102
103
# 4. Eigenvector Centrality
104
try:
105
eigenvector_centrality = nx.eigenvector_centrality(G, max_iter=100)
106
print("\n4. Eigenvector Centrality (Top 5):")
107
for node, score in sorted(eigenvector_centrality.items(), key=lambda x: x[1], reverse=True)[:5]:
108
print(f" {node}: {score:.3f}")
109
except:
110
print("\n4. Eigenvector Centrality: Not converged")
111
112
# 5. Community Detection (using modularity)
113
from networkx.algorithms import community
114
115
communities = list(community.greedy_modularity_communities(G))
116
print(f"\n5. Community Detection:")
117
print(f"Number of communities: {len(communities)}")
118
for i, comm in enumerate(communities):
119
print(f" Community {i+1}: {list(comm)}")
120
121
# 6. Network Statistics
122
degrees = [G.degree(n) for n in G.nodes()]
123
print(f"\n6. Network Statistics:")
124
print(f"Average Degree: {np.mean(degrees):.2f}")
125
print(f"Max Degree: {max(degrees)}")
126
print(f"Min Degree: {min(degrees)}")
127
print(f"Clustering Coefficient: {nx.average_clustering(G):.3f}")
128
print(f"Number of Triangles: {sum(nx.triangles(G).values()) // 3}")
129
130
# Visualization
131
fig, axes = plt.subplots(2, 2, figsize=(15, 12))
132
133
# Network layout
134
pos = nx.spring_layout(G, k=0.5, iterations=50, seed=42)
135
136
# 1. Network Graph (colored by degree)
137
ax = axes[0, 0]
138
node_colors = [degree_centrality[node] for node in G.nodes()]
139
nx.draw_networkx_nodes(G, pos, node_color=node_colors, node_size=1000, cmap='YlOrRd', ax=ax)
140
nx.draw_networkx_edges(G, pos, alpha=0.5, ax=ax)
141
nx.draw_networkx_labels(G, pos, font_size=8, ax=ax)
142
ax.set_title('Network Graph (Colored by Degree Centrality)')
143
ax.axis('off')
144
145
# 2. Network Graph (colored by communities)
146
ax = axes[0, 1]
147
color_map = []
148
colors = plt.cm.Set3(np.linspace(0, 1, len(communities)))
149
node_to_color = {}
150
for i, comm in enumerate(communities):
151
for node in comm:
152
node_to_color[node] = colors[i]
153
color_map = [node_to_color[node] for node in G.nodes()]
154
155
nx.draw_networkx_nodes(G, pos, node_color=color_map, node_size=1000, ax=ax)
156
nx.draw_networkx_edges(G, pos, alpha=0.5, ax=ax)
157
nx.draw_networkx_labels(G, pos, font_size=8, ax=ax)
158
ax.set_title('Network Graph (Colored by Community)')
159
ax.axis('off')
160
161
# 3. Centrality Comparison
162
ax = axes[1, 0]
163
centrality_df = pd.DataFrame({
164
'Degree': degree_centrality,
165
'Betweenness': betweenness_centrality,
166
'Closeness': closeness_centrality,
167
}).head(8)
168
169
centrality_df.plot(kind='barh', ax=ax, width=0.8)
170
ax.set_xlabel('Centrality Score')
171
ax.set_title('Top 8 Nodes - Centrality Comparison')
172
ax.legend(loc='lower right')
173
ax.grid(True, alpha=0.3, axis='x')
174
175
# 4. Degree Distribution
176
ax = axes[1, 1]
177
degree_sequence = sorted([d for n, d in G.degree()], reverse=True)
178
degree_count = Counter(degree_sequence)
179
degrees_unique = sorted(degree_count.keys())
180
counts = [degree_count[d] for d in degrees_unique]
181
182
ax.bar(degrees_unique, counts, color='steelblue', edgecolor='black', alpha=0.7)
183
ax.set_xlabel('Degree')
184
ax.set_ylabel('Count')
185
ax.set_title('Degree Distribution')
186
ax.grid(True, alpha=0.3, axis='y')
187
188
plt.tight_layout()
189
plt.show()
190
191
# 7. Path Analysis
192
print(f"\n7. Path Analysis:")
193
try:
194
shortest_path = nx.shortest_path_length(G, 'Alice', 'Jack')
195
print(f"Shortest path from Alice to Jack: {shortest_path}")
196
except nx.NetworkXNoPath:
197
print("No path exists between nodes")
198
199
# 8. Connectivity Analysis
200
print(f"\n8. Connectivity Analysis:")
201
print(f"Is connected: {nx.is_connected(G)}")
202
num_components = nx.number_connected_components(G)
203
print(f"Number of connected components: {num_components}")
204
205
# 9. Similarity Measures
206
def jaccard_similarity(node1, node2):
207
neighbors1 = set(G.neighbors(node1)) | {node1}
208
neighbors2 = set(G.neighbors(node2)) | {node2}
209
intersection = len(neighbors1 & neighbors2)
210
union = len(neighbors1 | neighbors2)
211
return intersection / union if union > 0 else 0
212
213
print(f"\n9. Node Similarity (Jaccard):")
214
print(f"Alice & Bob: {jaccard_similarity('Alice', 'Bob'):.3f}")
215
print(f"Alice & Jack: {jaccard_similarity('Alice', 'Jack'):.3f}")
216
217
# 10. Influence Score (Combination of metrics)
218
influence_score = {}
219
for node in G.nodes():
220
score = (degree_centrality[node] * 0.4 +
221
betweenness_centrality[node] * 0.3 +
222
closeness_centrality[node] * 0.3)
223
influence_score[node] = score
224
225
print(f"\n10. Influence Score (Top 5):")
226
for node, score in sorted(influence_score.items(), key=lambda x: x[1], reverse=True)[:5]:
227
print(f" {node}: {score:.3f}")
228
229
# Summary
230
print("\n" + "="*50)
231
print("NETWORK ANALYSIS SUMMARY")
232
print("="*50)
233
print(f"Most influential: {max(influence_score, key=influence_score.get)}")
234
print(f"Most connected: {max(degree_centrality, key=degree_centrality.get)}")
235
print(f"Network bottleneck: {max(betweenness_centrality, key=betweenness_centrality.get)}")
236
print(f"Closest to all: {max(closeness_centrality, key=closeness_centrality.get)}")
237
print("="*50)
238
```
239
240
## Centrality Measures
241
242
- **Degree**: Direct connections only
243
- **Betweenness**: Bridges between groups
244
- **Closeness**: Access to network
245
- **Eigenvector**: Connected to important nodes
246
- **PageRank**: Random walk probability
247
248
## Community Detection
249
250
- **Modularity Optimization**: Find dense groups
251
- **Louvain Algorithm**: Hierarchical communities
252
- **K-clique**: Overlapping communities
253
- **Spectral**: Eigenvalue-based
254
255
## Applications
256
257
- Social network analysis
258
- Organizational structures
259
- Citation networks
260
- Recommendation networks
261
- Supply chain analysis
262
263
## Deliverables
264
265
- Network visualization
266
- Centrality analysis
267
- Community detection results
268
- Connectivity metrics
269
- Influence rankings
270
- Key node identification
271
- Network statistics summary
272