Skip to content

Latest commit

 

History

History
344 lines (246 loc) · 12.4 KB

networkx.org

File metadata and controls

344 lines (246 loc) · 12.4 KB

NetworkX로 사회연결망 분석하기

Python으로 사회연결망 분석을 해봅시다.

Python으로 사회연결망 분석을 할 수 있도록 지원하는 패키지는 몇 가지가 있습니다. python-igraph, networkx, graph-tool 정도가 있는데요. 그 중에서 NetworkX가 가장 대중적으로 많이 사용됩니다.

(NetworkX가 2017년 9월에 1.x에서 2.0으로 메이저 업데이트를 했습니다. 그러면서 중요한 변화들이 생겼고요. 그래서 웹상의 다른 자료들을 참고하시면 잘 동작하지 않을 수 있습니다. 2.0 기준으로 설명된 자료인지 확인하세요.)

네트워크 생성하기

처음으로, 네트워크 분석을 위해 가장 처음 필요한, 네트워크를 생성하거나 불러오고, 분석을 수행하고 저장하는 방법을 알아봅니다.

우선 네트워크를 만드는 방법을 알아봅니다.

네트워크를 만들 수 있는 방법은 여러가지가 있습니다. 가장 간단한 방법은 분석자가 임의의 데이터를 만들어서 입력해주는 방법입니다.

1 -> 2
1 -> 3
2 -> 3
3 -> 4

위와 같은 edgelist를 네트워크 데이터로 만들려면 어떻게 할까요?

우선 아래와 같은 배열을 만듭니다.

%matplotlib inline
edges = [(1, 2), (1, 3), (2, 3), (3, 4)]

위와 같은 배열을 아래와 같이 네트워크로 만들 수 있습니다.

import networkx as nx
g = nx.Graph()
g.add_edges_from(edges)
print(nx.info(g))
Name: 
Type: Graph
Number of nodes: 4
Number of edges: 4
Average degree:   2.0000

네트워크가 어떻게 생겼는지 맵으로 확인해보려면 아래와 같이 그릴 수 있습니다.

nx.draw_networkx(g)

outputs/networkx-01-create-network-1.png

위와 같은 방법을 통해 네트워크를 만들고 그릴 수 있습니다. 하지만 대부분의 경우에는 네트워크를 직접 수동으로 입력하지 않고 CSV 등의 데이터 파일로부터 가져오게 됩니다. CSV 파일을 불러들이는 방법은 오늘 마지막 부분에서 다루겠습니다.

당분간의 실습은 NetworkX에서 내장하고 있는 예제 데이터를 사용하겠습니다.

g_karate = nx.karate_club_graph()
print(nx.info(g_karate))
Name: Zachary's Karate Club
Type: Graph
Number of nodes: 34
Number of edges: 78
Average degree:   4.5882
g_karate.edges
EdgeView([(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 10), (0, 11), (0, 12), (0, 13), (0, 17), (0, 19), (0, 21), (0, 31), (1, 17), (1, 2), (1, 3), (1, 21), (1, 19), (1, 7), (1, 13), (1, 30), (2, 3), (2, 32), (2, 7), (2, 8), (2, 9), (2, 27), (2, 28), (2, 13), (3, 7), (3, 12), (3, 13), (4, 10), (4, 6), (5, 16), (5, 10), (5, 6), (6, 16), (8, 32), (8, 30), (8, 33), (9, 33), (13, 33), (14, 32), (14, 33), (15, 32), (15, 33), (18, 32), (18, 33), (19, 33), (20, 32), (20, 33), (22, 32), (22, 33), (23, 32), (23, 25), (23, 27), (23, 29), (23, 33), (24, 25), (24, 27), (24, 31), (25, 31), (26, 33), (26, 29), (27, 33), (28, 33), (28, 31), (29, 32), (29, 33), (30, 33), (30, 32), (31, 32), (31, 33), (32, 33)])
nx.draw_networkx(g_karate)

outputs/networkx-01-create-network-2.png

노드가 34개, 링크가 78개인 네트워크입니다.

네트워크 기본 속성 알아보기

네트워크의 밀도와 지름, 평균 도달 거리를 살펴봅시다.

print('Density:', nx.density(g_karate))
print('Diameter:', nx.diameter(g_karate))
print('Average path length:', nx.average_shortest_path_length(g_karate))
Density: 0.13903743315508021
Diameter: 5
Average path length: 2.408199643493761

각 노드들의 degree 분포를 살펴봅니다.

import pandas as pd
degree_freq = nx.degree_histogram(g_karate)
df_degree_freq = pd.DataFrame(degree_freq, columns=['Frequency']).rename_axis('Degree')
df_degree_freq
DegreeFrequency
00
11
211
36
46
53
62
70
80
91
101
110
121
130
140
150
161
171
df_degree_freq.plot.bar();

outputs/networkx-01-basic-net-properties-1.png

노드별 degree 값을 노드 속성으로 추가하려면 아래와 같이 합니다.

deg = g_karate.degree
for node, attrs in g_karate.nodes.items():
    attrs['degree'] = deg[node]
print(nx.get_node_attributes(g_karate, 'degree'))
{0: 16, 1: 9, 2: 10, 3: 6, 4: 3, 5: 4, 6: 4, 7: 4, 8: 5, 9: 2, 10: 3, 11: 1, 12: 2, 13: 5, 14: 2, 15: 2, 16: 2, 17: 2, 18: 2, 19: 3, 20: 2, 21: 2, 22: 2, 23: 5, 24: 3, 25: 3, 26: 2, 27: 4, 28: 3, 29: 4, 30: 4, 31: 6, 32: 12, 33: 17}

네트워크 스타일링하기

네트워크 맵을 스타일링하는 방법을 살펴봅니다.

우선 맵 전체에 적용되는 모양을 바꿔봅시다. 맵 크기를 좀 키우고, 링크의 색을 좀 연하게, 그리고 노드 테두리 색을 검은색으로 변경해보겠습니다.

import matplotlib.pyplot as plt
plt.figure(figsize=(12, 10))
pos = nx.spring_layout(g_karate)
nx.draw_networkx_edges(g_karate, pos, alpha=0.3);
nodes = nx.draw_networkx_nodes(g_karate, pos, node_size=200, linewidths=0.5);
nodes.set_edgecolor('k')

outputs/networkx-01-network-styling-1.png

이번에는 노드의 속성에 따라 색상을 다르게 그려봅시다. degree가 5 이상인 노드의 색을 다르게 줘봅시다.

big_nodes = [n for n, attrs in g_karate.nodes.items() if attrs['degree'] > 5]
big_nodes
[0, 1, 2, 3, 31, 32, 33]
import matplotlib.pyplot as plt
plt.figure(figsize=(12, 10))
pos = nx.spring_layout(g_karate)
nx.draw_networkx_edges(g_karate, pos, alpha=0.3);
nodes = nx.draw_networkx_nodes(g_karate, pos, node_size=200, linewidths=0.5);
nodes.set_edgecolor('k')
nodes = nx.draw_networkx_nodes(g_karate, pos, big_nodes, node_size=300, node_color='b', linewidths=0.5);
nodes.set_edgecolor('k')

outputs/networkx-01-network-styling-2.png

맵을 그린 후에, degree가 5 이상인 노드들을 다시 덧그렸습니다.

네트워크 변형하기

네트워크에서 특정 노드나 링크를 제거하거나 서브 네트워크를 추출하는 등, 네트워크를 다루는 방법을 알아봅니다.

서브 네트워크 추출하기

노드 속성을 기준으로 서브 네트워크를 추출해보겠습니다.

먼저, 위의 네트워크를 커뮤니티 분석을 통해 구분해봅시다.

communities = list(nx.algorithms.community.girvan_newman(g_karate))
print(communities[0])
({0, 1, 3, 4, 5, 6, 7, 10, 11, 12, 13, 16, 17, 19, 21}, {32, 33, 2, 8, 9, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31})

어떻게 구분되었는지 살펴볼까요?

import matplotlib.pyplot as plt
plt.figure(figsize=(12, 10))
pos = nx.spring_layout(g_karate)
nx.draw_networkx_edges(g_karate, pos, alpha=0.3);

nodes = nx.draw_networkx_nodes(g_karate, pos, node_size=300, linewidths=0.5);
nodes.set_edgecolor('k')

nodes = nx.draw_networkx_nodes(g_karate, pos, communities[0][0], node_size=300, node_color='b', linewidths=0.5);
nodes.set_edgecolor('k')

nodes = nx.draw_networkx_nodes(g_karate, pos, communities[0][1], node_size=300, node_color='g', linewidths=0.5);
nodes.set_edgecolor('k')

outputs/networkx-01-network-transform-1.png

이 중에서 community 0번의 노드들만으로 구성된 서브 네트워크를 추출해봅시다.

g_community_0 = g_karate.subgraph(communities[0][0])
print(nx.info(g_community_0))
Name: Zachary's Karate Club
Type: SubGraph
Number of nodes: 15
Number of edges: 28
Average degree:   3.7333
import matplotlib.pyplot as plt
plt.figure(figsize=(12, 10))
pos = nx.spring_layout(g_community_0)
nx.draw_networkx_edges(g_community_0, pos, alpha=0.3);

nodes = nx.draw_networkx_nodes(g_community_0, pos, node_size=300, linewidths=0.5);
nodes.set_edgecolor('k')

outputs/networkx-01-network-transform-2.png

특정 조건의 노드 제거하기

전체 네트워크에서, 연결 중심성이 가장 강한 노드를 제거해봅시다.

bc = nx.algorithms.centrality.betweenness_centrality(g_karate)
print(bc)
bc_high_nodes = sorted(bc, key=lambda x: bc[x], reverse=True)[:1]
print(bc_high_nodes)
{0: 0.4376352813852815, 1: 0.053936688311688304, 2: 0.14365680615680618, 3: 0.011909271284271283, 4: 0.0006313131313131313, 5: 0.02998737373737374, 6: 0.029987373737373736, 7: 0.0, 8: 0.05592682780182781, 9: 0.0008477633477633478, 10: 0.0006313131313131313, 11: 0.0, 12: 0.0, 13: 0.04586339586339586, 14: 0.0, 15: 0.0, 16: 0.0, 17: 0.0, 18: 0.0, 19: 0.03247504810004811, 20: 0.0, 21: 0.0, 22: 0.0, 23: 0.017613636363636363, 24: 0.0022095959595959595, 25: 0.0038404882154882154, 26: 0.0, 27: 0.02233345358345358, 28: 0.0017947330447330447, 29: 0.0029220779220779218, 30: 0.014411976911976907, 31: 0.13827561327561325, 32: 0.145247113997114, 33: 0.304074975949976}
[0]

0번 노드가 가장 연결 중심성이 높습니다.

import matplotlib.pyplot as plt
plt.figure(figsize=(12, 10))
pos = nx.spring_layout(g_karate)
nx.draw_networkx_edges(g_karate, pos, alpha=0.3);

nodes = nx.draw_networkx_nodes(g_karate, pos, node_size=300, linewidths=0.5);
nodes.set_edgecolor('k')

nodes = nx.draw_networkx_nodes(g_karate, pos, bc_high_nodes, node_size=300, node_color='y', linewidths=0.5);
nodes.set_edgecolor('k')

outputs/networkx-01-network-transform-3.png

아래와 같이 0번 노드를 제거합니다.

g_karate.remove_nodes_from(bc_high_nodes)
print(nx.info(g_karate))
Name: Zachary's Karate Club
Type: Graph
Number of nodes: 33
Number of edges: 62
Average degree:   3.7576

그리고 다시 맵을 그려보면, 아래와 같이 네트워크가 분할되는 것을 볼 수 있습니다.

import matplotlib.pyplot as plt
plt.figure(figsize=(12, 10))
pos = nx.spring_layout(g_karate)
nx.draw_networkx_edges(g_karate, pos, alpha=0.3);

nodes = nx.draw_networkx_nodes(g_karate, pos, node_size=300, linewidths=0.5);
nodes.set_edgecolor('k')

outputs/networkx-01-network-transform-4.png