SlideShare a Scribd company logo
1 of 42
Download to read offline
사회 연결망의 링크 예측
Kyunghoon Kim
kyunghoon@unist.ac.kr
Bongsoo Jang
bsjang@unist.ac.kr
November 13, 2015
Research Performed: ∼ November 13, 2015
Supporter: Changyong Lee
1 목적
사회 연결망의 링크를 예측하는 많은 방법들이 존재한다. 그 방법들에 대하여
정리하여 논하고, 실제 어떻게 시뮬레이션을 할 수 있는지 시도한다.
1.1 정의
사회 연결망 Social networks 소셜 네트워크(Social networks)는 한국어로 사회
망 또는 사회 연결망이라고 불린다. 사회 연결망이란 도로망, 철도망, 통신
망과 같이 인간이 모여 살기 때문에 생겨나는 사회적 하부구조를 포괄적으로
의미하기 때문에 그 의미가 폭 넓다고 할 수 있다.
사회 연결망은 행위자와 행위자들 사이의 관계로 구성되는 사회적 구조이며,
이러한 사회 연결망은 행위자를 점으로 하고 관계를 선으로 한 그래프로
표현될 수 있다.
사회 연결망 분석 Social network analysis 사회 연결망 분석은 연결망 안의 행
위자들의 관계를 수치화, 통계화, 그래프화하여 관계에 대한 해석을 가능하도
록 한다. 1980년대까지 사회 연결망 분석은 사회과학에서 확립된 분야였다.
1990년대에 연결망 분석은 더 많은 분야로 확산되었는데, 물리학과 생물학도
포함된다. 응용분야로는 경영상담, 공공보건, 범죄/전쟁 방지가 있다. 경영상
담에서 연결망 분석은 종종 지식경영의 맥락에 적용되는데, 목적은 조직들이
그 구성원들 사이에 분포한 정보와 능력들을 더 잘 뽑아낼 수 있게 도와주는
것이다. 공공보건에서 연결망접근은 전염병 확산을 막고 건강관리와 사회적
지지를 제공하는데 중요했다.
모든 응용분야 중 국가안보는 아마도 사회연결망분석을 가장 많이 끌어안은
영역일 것이다. 범죄, 그 중에서도 조직범죄에 맞선 사람들은 오랫동안 연결
망관점을 이용했다. 그들은 “관심 인물”들 사이의 링크로 이루어진 연결망을
벽을 덮을 만큼 큰 지도로 만들어 붙였다. 이 연결망접근은 사담 후세인을
잡는데 기여했다고 한다. 덧붙여, 테러그룹들은 조직보다는 연결망으로 널리
알려져 있으며 기능적인 연결망을 혼란시키는 연구에 불을 붙였다. 동시에
1
연결망에 맞서기 위해 연결망이 필요하다고 주장되기도 하는데, 이는 분산된
단위를 이용한 군사 실험으로 이어진다.(Borgatti et al., 2009)
링크 예측 소셜 네트워크에서의 링크 예측은 현재 주어진 네트워크에서 빠진 링크를
예측하거나, 미래의 네트워크에서 새롭게 나타나거나 사라질 링크를 예측하는
것을 의미한다. 이것은 소셜 네트워크의 진화를 분석하는 데 중요하다.
특정한 시간 t에서 다음과 같은 사회망을 정의하자.
G(V, E) (1)
여기서 V 는 노드들의 집합, E 는 링크들의 집합이다.
링크 예측은
1. 미래 시간 t′
(t′
> t)에서 노드들 사이에 나타날 링크나 지워질 링크
2. 현재 시간 t에 빠진 링크 또는 관찰되지 않은 링크
를 예측하는 것을 목표로 한다.
이 링크 예측 문제를 해결하기 위한 방법들을 하나의 프레임워크로 정리한
것은 Figure 1.1과 같다.(Wang et al., 2015)
Figure 1: 일반적인 링크 예측 프레임워크
2 링크 예측 기법
링크 예측을 위한 방법에는 크게 노드의 정보를 사용하는 방법, 위상적 구조를
사용하는 방법 그리고 사회과학 이론을 사용하는 방법 등 기본적인 링크 예측 방법과
약간 복잡하지만 학습 기반의 링크 예측 방법 등이 존재한다. 여기서 그 방법들을
한 번 살펴보자.
본 절에서 사용하는 파이썬 코드는 다음 라이브러리들을 가정하고 있다.
1 %pylab inline
2 import numpy as np
3 import pandas as pd
4 import networkx as nx
5 import networkx_addon # it's not a public library
2
networkx_addon은 https://github.com/hhchen1105/networkx_addon.git
에서 다운받을 수 있다.
git clone https://github.com/hhchen1105/networkx_addon.git
cd networkx_addon
python setup.py install
2.1 노드 기반 링크 예측
링크 예측에 있어 노드 쌍의 유사도를 계산하는 것은 가장 직관적인 해결책일
것이다. 노드 쌍의 유사도가 높을 수록 링크가 있을 가능성(likelihood)이 높다는
아이디어이다.
여기서 유사도를 계산하기 위해 노드가 가진 특성을 이용하는 것이 노드 기반
링크 예측이다. 예를 들어, 노드를 사람이라고 했을 때, 사람이 가진 종교, 취미,
위치 등을 특성(attributes)으로 하여 그 특성의 유사도를 계산하는 것이다. 이것은
링크를 가지지 않은 비슷한 특성을 가진 사람들은 서로 링크될 가능성이 높다는
것을 가정으로 한다.
실제로 사회 연결망 서비스(Social network service)의 하나인 페이스북에서는
유저의 프로필을 참고하여 유저들의 유사성을 계산해 친구일 가능성이 높은 유저를
추천해 줄 수 있다.
다른 예로, 위키페디아 페이지를 수정하는 사용자 행동를 특징으로 하여 그 행동의
유사성을 이용해 링크를 예측하는 연구가 있다. (Anderson et al., 2012)
결론적으로, 노드 기반 링크 예측은 노드의 특성(attributes)이나 행동(action)을
사용하여 노드 쌍의 유사성을 계산한다. 지금까지 유사성을 계산하기 위해 많은
방법들이 제안되어 왔으며(Jones and Furnas, 1987), 유사성을 계산하기 위한 방법
으로는 유클리디안 거리(Euclidean distance)와 코사인 유사도(Cosine similarity)
가 많이 사용된다. 유저의 특성을 벡터 형태로 표현하는 것을 벡터 공간 모델
(Vector space model, VSM)이라고 하며, 임의의 두 벡터 사이의 거리를 계산하는
것이 유클리디안 거리이고, 각도를 계산하는 것이 코사인 유사도이다.
계산을 위해 다음을 가정하자. 두 개의 벡터 x, y가 각각 n개의 원소를 갖는다고
하자.
x =< x1, x2, · · · , xn > (2)
y =< y1, y2, · · · , yn > (3)
Definition 2.1 (유클리디안 거리)
d(x, y) = d(y, x) =
√
(y1 − x1)2 + (y2 − x2)2 + · · · + (yn − xn)2
=
n∑
i=1
(yi − xi)2
(4)
3
Definition 2.2 (코사인 유사도) x와 y 사이의 각도 θ 의 코사인은 다음과 같이
계산된다.
cos(x, y) =
∑n
i=1 xi · yi
√∑n
i=1 x2
i ·
∑n
i=1 y2
i
=
x · y
√
x · x ·
√
y · y
=
x
∥x∥
·
y
∥y∥
(5)
벡터 공간 모델에 대한 수학적인 해석은 SIAM의 Berry et al. (1999), 매력적인
성질과 그 응용은 AAAI의 Turney et al. (2010)을 참고하면 된다.
Example 2.1 철수는 울산과기원을 다니고 독서를 취미로 하며 울산에 있다. 영
희는 울산과기원을 다니고 음악감상을 취미로 하며 울산에 있다. 철수와 영희의
벡터 공간 모델에서의 유사도를 구해보자.
철수 영희
교육 울산과기원 울산과기원
취미 독서 음악감상
위치 울산 울산
⇒
철수 영희
울산과기원 1 1
독서 1 0
음악감상 0 1
울산 1 1
Table 1: 벡터 공간 모델의 예
벡터 공간 모델에 의해 만들어진 두 벡터 ⃗V철수 =




1
1
0
1



, ⃗V영희 =




1
0
1
1



에 대해,
유클리디안 거리는 다음과 같이 계산할 수 있다..
1 def euclidean(x,y):
2 return np.sqrt(np.sum((x-y)**2))
3
4 a = np.array([1,1,0,1])
5 b = np.array([1,0,1,1])
6 dist = euclidean(a, b)
코사인 유사도의 경우 scikit-learn 라이브러리를 쓰면 쉽게 계산할 수 있다.
1 from sklearn.metrics.pairwise import cosine_similarity
2 sim = cosine_similarity(a, b)
3 print sim
이 때의 결과 값은
1 array([[ 0.66666667]])
과 같이 나오는데, 값만 가져오기 위해서는 sim[0][0] 또는 sim[0,0]과 같이 배열에
직접 접근하여 얻어낸다.
scikit-learn을 사용하지 않고 직접 계산하는 방법은 다음과 같이 한다.
4
1 import math
2 def cosine_similarity(v1,v2):
3 sumxx, sumxy, sumyy = 0, 0, 0
4 for i in range(len(v1)):
5 x = v1[i]; y = v2[i]
6 sumxx += x*x
7 sumyy += y*y
8 sumxy += x*y
9 return sumxy/math.sqrt(sumxx*sumyy)
10
11 sim = cosine_similarity(a, b)
2.2 위상 기반 링크 예측
노드나 링크에 특성(attributes)이 없더라도 위상적 정보(topological information)
를 기반으로 두 노드의 유사도를 계산할 수 있는 많은 방법들이 존재한다. Liben-
Nowell and Kleinberg (2007) 논문 이후로 그래프의 구조적 특징을 기반으로 한
여러 가지 측정법 (metric) 들이 논의되었고, 이후에는 위상 기반의 측정법들이
제안되었다. 이 측정법들은 크게 세 가지 분류로 나누어 볼 수 있는데, 그 각각을
살펴보도록 하자.
먼저 기본적인 표기법은 다음과 같다.
• 소문자 = 노드
• 대문자 = 인접행렬
• Γ(x) = 노드 x의 이웃들의 집합
• |Γ(x)| = 노드 x의 이웃들의 개수
2.2.1 이웃 기반 링크 예측
이웃을 기반으로 한 링크 예측은 Table 2에서 그 특징들을 살펴볼 수 있다.
Definition 2.3 공통 이웃 Common Neighbors (CN)
CN은 간단한 형태 때문에 링크 예측 문제에서 가장 많이 쓰여지는 측정법 중 하
나이다.(Newman, 2001) 이 방법은 두 개의 노드 x, y 가 공통적으로 가지고 있는
이웃의 개수를 센다.
CN(x, y) = |Γ(x) ∩ Γ(y)| (6)
1 >>> G = nx.complete_graph(5)
2 >>> sorted(nx.common_neighbors(G, 0, 1))
3 [2, 3, 4]
함수의 파이썬 코드는 다음과 같다.
1 def common_neighbors(G, u, v):
2 if u not in G:
3 raise nx.NetworkXError('u is not in the graph.')
5
Table 2: 이웃 기반 링크 예측 비교표
측정법 정규화 시간 복잡도 특징
CN No O(n2
) 간단하고 직관적
JC Yes O(2n2
) 이웃의 전체 개수와 공통 이웃의 비율
SI Yes O(n2
) 노드의 Degree가 낮을 수록 링크를 가질 가능성이 크다
SC Yes O(n2
) 코사인 유사도 사용
HP Yes O(n2
) 링크를 가질 가능성은 낮은 Degree 일수록 높다
HD Yes O(n2
) 링크를 가질 가능성은 높은 Degree 일수록 높다
LHN Yes O(n2
) 많은 공통 이웃을 가질수록 링크 가능성이 높다
PD Yes O(n2
) 대중적인 노드인지 예측의 정확도를 향상시킨다
AA No O(2n2
) 적은 이웃을 가지는 공통 이웃들은 가중치가 높다
PA No O(2n) 높은 도수를 갖는 노드와의 링크 가능성이 높다
RA No O(2n2
) AA와 비슷하나, 높은 공통 이웃을 가진 것을 억압한다
4 if v not in G:
5 raise nx.NetworkXError('v is not in the graph.')
6
7 return (w for w in G[u] if w in G[v] and w not in (u, v))
Definition 2.4 자카드 계수 Jaccard Coefficient (JC)
JC는 CN의 정규화된 값이다.
JC(x, y) =
|Γ(x) ∩ Γ(y)|
|Γ(x) ∪ Γ(y)|
(7)
jaccard_coefficient(G, ebunch=None)
여기서 ebunch는 선택된 노드쌍만 계산되도록 하는 변수이다. (default = None)
1 for u in G.nodes_iter():
2 candidates = [(u, v) for v in nx.non_neighbors(G, u)]
3 preds = nx.jaccard_coefficient(G, candidates)
4 for source, target, value in preds:
5 index_data[source][target]['j'] = value
위 함수의 파이썬 코드는 다음과 같으며, 다른 측정법 역시 유사하게 함수를 작성할
수 있다.
1 def _apply_prediction(G, func, ebunch=None):
2 """Applies the given function to each edge in the
3 specified iterable of edges.
4
5 ``G`` is an instance of :class:`networkx.Graph `.
6
7 ``func`` is a function on two inputs , each of which is a
8 node in the graph. The function can return anything , but
6
9 it should return a value representing a prediction of the
10 likelihood of a "link" joining the two nodes.
11
12 ``ebunch `` is an iterable of pairs of nodes. If not
13 specified , all non-edges in the graph ``G`` will be used.
14 """
15 if ebunch is None:
16 ebunch = nx.non_edges(G)
17 return ((u, v, func(u, v)) for u, v in ebunch)
18
19 def jaccard_coefficient(G, ebunch=None):
20 def predict(u, v):
21 union_size = len(set(G[u]) | set(G[v]))
22 if union_size == 0:
23 return 0
24 return len(list(nx.common_neighbors(G, u, v))) / union_size
25 return _apply_prediction(G, predict , ebunch)
Definition 2.5 소렌슨 인덱스 Sørensen Index (SI)
공통 이웃의 개수를 고려함과 동시에, 낮은 도수의 노드는 링크가 생길 가능성이
높음을 나타냈다.
SI(x, y) =
|Γ(x) ∩ Γ(y)|
|Γ(x)| + |Γ(y)|
(8)
Definition 2.6 살톤 코사인 유사도 Salton Cosine Similarity (SC)
SC는 노드 x와 y 사이의 유사도를 계산하기 위해서 일반적인 코사인 방법을 적용
했다.
SC(x, y) =
|Γ(x) ∩ Γ(y)|
√
|Γ(x)| · |Γ(y)|
(9)
Definition 2.7 Hub Promoted (HP)
HP는 노드 x와 y 의 위상적인 겹침을 정의했다(Ravasz et al., 2002). HP의 값은
도수가 낮은 노드에 의해 결정된다.
HP(x, y) =
|Γ(x) ∩ Γ(y)|
min(|Γ(x)|, |Γ(y)|)
(10)
Definition 2.8 Hub Depressed (HD)
Zhou et al. (2009)는 HP와 유사하지만 HD의 값이 도수가 높은 노드에 의해 결정
되도록 정의했다.
HD(x, y) =
|Γ(x) ∩ Γ(y)|
max(|Γ(x)|, |Γ(y)|)
(11)
Definition 2.9 Leicht-Holme-Newman (LHN)
LHN은 JC보다 높은 도수를 갖는 노드에 패널티를 주는(punish) 방법이다. (Leicht
et al., 2006)
LHN(x, y) =
|Γ(x) ∩ Γ(y)|
|Γ(x)| · |Γ(y)|
(12)
7
LHN은 networkx_addon을 사용해서 쉽게 계산할 수 있다. networkx_addon의
설치는 2절을 참고하자.
1 G=nx.Graph()
2 G.add_edges_from([(0,7), (0,1), (0,2), (0,3), (1,4), (2,4)])
3 networkx_addon.similarity.lhn(G)
함수의 파이썬 코드는 다음과 같다.
1 def lhn(G, c=0.9, remove_neighbors=False, inv_method=0):
2 if type(G) == nx.MultiGraph or type(G) == nx.MultiDiGraph:
3 raise Exception("lhn() not defined for graphs with multiedges.")
4
5 if G.is_directed():
6 raise Exception("lhn() not defined for directed graphs.")
7
8 A = nx.adjacency_matrix(G, nodelist=G.nodes(), weight=None)
9 w, v = numpy.linalg.eigh(A)
10 lambda1 = max([abs(x) for x in w])
11 I = numpy.eye(A.shape[0])
12 S = None
13 if inv_method == 1:
14 S = scipy.linalg.pinv(I - c/lambda1 * A)
15 elif inv_method == 2:
16 S = numpy.linalg.inv(I - c/lambda1 * A)
17 else:
18 S = numpy.linalg.pinv(I - c/lambda1 * A)
19 deg = numpy.array(sum(A)).reshape(-1,)
20 for i in range(S.shape[0]):
21 for j in range(S.shape[1]):
22 S[i,j] /= (deg[i]*deg[j])
23 return S, G.nodes()
Definition 2.10 Parameter-Dependent (PD)
대중적(popular)인지 아닌지를 예측하는 정확도를 높이기 위해서 Zhu et al. (2012)
이 제안한 방법이다. 여기서 λ는 free parameter이다. λ = 0일 때는 CN, λ = 0.5
일 때는 SC, λ = 1일 때는 LHN이다.
PD(x, y) =
|Γ(x) ∩ Γ(y)|
(|Γ(x)| · |Γ(y)|)λ
(13)
Definition 2.11 아다믹-아다르 계수 Adamic-Adar Coefficient (AA)
처음에는 Adamic과 Adar가 두 웹 페이지의 유사성을 계산하기 위해서 제안한
공식이다. 적은 이웃을 갖는 공통 이웃의 비중을 높여주었다.
AA(x, y) =
∑
z∈Γ(x)∩Γ(y)
1
log |Γ(z)|
(14)
adamic_adar_index(G, ebunch=None)
8
1 for u in G.nodes_iter():
2 candidates = [(u, v) for v in nx.non_neighbors(G, u)]
3 preds = nx.adamic_adar_index(G, candidates)
4 for source, target, value in preds:
5 index_data[source][target]['a'] = value
함수의 파이썬 코드는 다음과 같다.
1 def adamic_adar_index(G, ebunch=None):
2 def predict(u, v):
3 return sum(1 / log(G.degree(w)) for w in nx.common_neighbors(G, u, v))
4 return _apply_prediction(G, predict , ebunch)
Definition 2.12 선호적 연결 Preferential Attachment (PA)
낮은 도수를 갖는 노드보다 높은 도수를 갖는 노드에 연결될 가능성이 높음을 표현
한다.
PA(x, y) = |Γ(x)| · |Γ(y)| (15)
preferential_attachment(G, ebunch=None)
1 for u in G.nodes_iter():
2 candidates = [(u, v) for v in nx.non_neighbors(G, u)]
3 preds = nx.preferential_attachment(G, candidates)
4 for source, target, value in preds:
5 index_data[source][target]['p'] = value
함수의 파이썬 코드는 다음과 같다.
1 def preferential_attachment(G, ebunch=None):
2 def predict(u, v):
3 return G.degree(u) * G.degree(v)
4 return _apply_prediction(G, predict , ebunch)
예를 들어, 다음과 같은 그래프를 가정하자. (Figure 2)
1 G = nx.Graph()
2 G.add_edges_from([('A','B'), ('A','C'), ('A','D'), ('A','E')
3 , ('A','F'), ('F','E')])
4 pos = nx.circular_layout(G)
5 nx.draw(G, with_labels=True, pos=pos)
링크가 없는 노드 쌍마다 PA를 계산한 후, 그 값이 3 이상이면 빨간색 선(링크
예측 선)으로 보이도록 하자. (threshold> 3)
1 plt.figure(figsize=(15, 5))
2 threshold = 3
3 pos = nx.circular_layout(G)
4 nx.draw_networkx_nodes(G, pos, node_size=500, node_color='yellow')
5 nx.draw_networkx_edges(G, pos, alpha=0.2)
6 nx.draw_networkx_labels(G, pos, font_size=20);
9
Figure 2: 주어진 그래프
7
8 selected_lines = []
9 for u in G.nodes_iter():
10 preds = nx.preferential_attachment(G, [(u, v) for v in nx.non_neighbors(G, u)])
11 largest = heapq.nlargest(5, preds, key = lambda x: x[2])
12 for l in largest:
13 selected_lines.append(l)
14
15 subG = nx.Graph()
16 for line in selected_lines:
17 print line[0], line[1], line[2]
18 if line[2]>threshold:
19 subG.add_edge(line[0], line[1])
20
21 pos_subG = dict()
22 for s in subG.nodes():
23 pos_subG[s] = pos[s]
24
25 nx.draw_networkx_edges(subG, pos_subG , edge_color='red');
26 plt.axis('off');
위 코드의 실행 결과는 다음과 같이 나타난다.
1 C E 4
2 C F 4
3 C D 2
4 B E 4
5 B F 4
6 B D 2
7 E C 4
8 E B 4
9 E D 2
10 D C 2
11 D B 2
12 D E 2
13 D F 2
14 F C 4
10
15 F B 4
16 F D 2
Figure 3: PA 링크예측(빨간색 선)
PA의 특징이 좀 더 잘 나타날 수 있도록 그래프의 노드 크기를 조절하자.
1 degree = nx.degree_centrality(G)
2 pos = nx.circular_layout(G)
3 nx.draw_networkx_nodes(G, pos, node_color='yellow', 
4 nodelist=degree.keys(),
5 node_size=np.array(degree.values())*10000)
6 nx.draw_networkx_edges(G, pos, alpha=0.2)
7 nx.draw_networkx_labels(G, pos, font_size=20);
Figure 4: PA 링크예측(빨간색 선)과 노드 크기 조절
Definition 2.13 리소스 할당 Resource Allocation (RA)
Zhou et al. (2009)이 제안한 방법은 자원 할당의 물리적인 프로세스에서 영감을
받았다. 높은 공통 이웃을 가지는 비중을 줄인다는 점에서, RA는 AA와 비슷한
형태이다. 하지만 RA는 AA보다 더 강하게 높은 공통 이웃을 가지는 노드를 억압
한다. 따라서 평균 도수(average degree)가 작은 네트워크에서는 RA, AA 둘 다
비슷한 링크 예측 결과를 보이지만, 높은 평균 도수를 갖는 네트워크에서는 RA가
더 나은 결과를 보여준다.
RA(x, y) =
∑
z∈Γ(x)∩Γ(y)
1
|Γ(z)|
(16)
11
resource_allocation_index(G, ebunch=None)
1 for u in G.nodes_iter():
2 candidates = [(u, v) for v in nx.non_neighbors(G, u)]
3 preds = nx.resource_allocation_index(G, candidates)
4 for source, target, value in preds:
5 index_data[source][target]['r'] = value
함수의 파이썬 코드는 다음과 같다.
1 def resource_allocation_index(G, ebunch=None):
2 def predict(u, v):
3 return sum(1 / G.degree(w) for w in nx.common_neighbors(G, u, v))
4 return _apply_prediction(G, predict , ebunch)
2.2.2 경로 기반 링크 예측
Definition 2.14 국소 경로 Local Path (LP)
LP는 말 그대로 국소적인 부분에 대해서 계산하는 방법이다. Lü et al. (2009)
에 따르면 CN, Katz에 비해 우수하다고 평가한다. 이웃들의 정보만을 사용하는
방법과는 달리, 경로 길이가 2 또는 3인 노드까지를 포함하여 정보를 사용한다는
것이 특징이다. 명백하게도, 경로 길이가 2인 것은 3인 것보다 더 관련이 있을
것이므로, 경로길이 3인 경우는 매개변수 α를 주어 그 비중을 낮춘다. 여기서 α는
0에 가까운 값이다.
LP = A2
+ αA3
(17)
행렬의 곱은 다음과 같이 표현할 수 있다.
1 A = np.matrix('1 2; 3 4')
2 A = np.matrix([[1, 2], [3, 4]])
3 A_2 = A*A
4 A_3 = A_2*A
Networkx의 그래프 구조를 행렬로 바꾸어, 그 행렬을 제곱하기 위해서는 다음과
같이 사용한다.
1 G = nx.path_graph(5)
2 A = nx.to_numpy_matrix(G)
3 A_2 = A**2
4 A_3 = A**3
Definition 2.15 Katz
Katz metric은 상당히 오래 전에 나온 개념으로 Katz (1953)가 제안한 방식이다.
Katz는 모든 경로의 닮음을 기반으로 하며, 두 노드 사이의 모든 경로를 센다.
경로의 길이가 짧을수록 더 많은 비중을 주기 위해 감쇠비(damping factor)로 β 를
사용한다. 만약 β 가 매우 작다면, Katz의 결과는 CN과 매우 유사할 것이다.
Katz(x, y) =
∞∑
l=1
βl
· |pathl
x,y| = βA + β2
A2
+ β3
A3
+ · · · .
= (I − βA)−1
− I
(18)
12
networkx에서 쓰이는 파라미터와 공식은 다음과 같다.
katz_centrality(G, alpha=0.1, beta=1.0, max_iter=1000,
tol=1e-06, nstart=None, normalized=True, weight='weight')
xi = α
∑
j
Aijxj + β (19)
1 >>> G = nx.path_graph(5)
2 >>> centrality = nx.katz_centrality(G)
3 >>> for n,c in sorted(centrality.items()):
4 ... print("%d %0.2f"%(n,c))
Definition 2.16 Relation Strength Similarity (RSS)
Chen et al. (2012)가 제안한 RSS는 가중치 사회 연결망을 위한 비대칭 측정법이다.
이것의 계산은 연결 강도 R(x, y)를 기반으로 하는데, 이웃 노드들 사이의 상대적인
유사정도로 정규화된 가중치 점수로 계산된다.
다음과 같이 가정하자. 노드 x에서 y 로 가는 r 보다 짧은 L개의 단순 경로 p1,
p2, · · · , pL 가 있다고 하자. 그리고 경로 pl 은 K 개의 노드 z1, z2, · · · , zk−1, zk 로
구성된다고 하자. 그러면 RSS는 다음과 같이 정의된다.
RSS(x, y) =
L∑
l=1
R∗
pl
(x, y) (20)
R∗
pl
(x, y) =
{
ΠK
k=1R(zk, zk+1), K ≤ r
0, otherwise
(21)
L을 2로 두었을 때 networkx_addon을 이용해 다음과 같이 계산할 수 있다.
1 G=nx.Graph()
2 G.add_edges_from([(0,1), (0,2), (1,3), (2,3)], weight=1)
3 networkx_addon.similarity.rss2(G)
함수의 파이썬 코드는 다음과 같다.
1 def rss2(G, remove_neighbors=False, dump_process=False, 
2 disregard_weight=False):
3 if type(G) == nx.MultiGraph or type(G) == nx.MultiDiGraph:
4 raise Exception("rss2() not defined for graphs with 
5 multiedges.")
6
7 if G.is_directed():
8 raise Exception("rss2() not defined for directed graphs.")
9
10 weighted_deg = G.degree(weight='weight')
11 rss2 = { }
12 cur_iter = 0
13
13 total_iter = G.number_of_nodes()
14 for a in G.nodes():
15 if dump_process:
16 cur_iter += 1
17 print cur_iter , '/', total_iter
18 for b in G.neighbors(a):
19 for c in G.neighbors(b):
20 if a == c:
21 continue
22 if remove_neighbors and c in G.neighbors(a):
23 continue
24 if disregard_weight:
25 t1 = float(1)
26 t2 = float(1)
27 s1 = len(set(G.neighbors(a)))
28 s2 = len(set(G.neighbors(b)))
29 else:
30 t1 = float(G[a][b]['weight'])
31 t2 = float(G[b][c]['weight'])
32 s1 = weighted_deg[a]
33 s2 = weighted_deg[b]
34 if a not in rss2:
35 rss2[a] = { }
36 if c not in rss2[a]:
37 rss2[a][c] = t1/s1 * t2/s2
38 else:
39 rss2[a][c] += t1/s1 * t2/ s2
40 return rss2
Definition 2.17 FriendLink (FL)
Papadimitriou et al. (2012)가 제안한 FL은 노드 x와 y 사이의 정해진 길이 l 안에
서 지나가는 모든 경로에 의한 유사도이다.
FL(x, y) =
l∑
i=1
1
i − 1
·
|pathsi
x,y|
Πi
j=2(n − j)
(22)
2.2.3 무작위 걷기 기반 링크 예측
사회망에서 노드들 사이의 사회적 상호작용은 무작위 걷기(random walk)로 모델
링될 수 있다. 이 예측 방법들은 노드에서 이웃 노드로 가는 전이 확률(transition
probabilities)를 이용한다.
Definition 2.18 Hitting Time (HT)
노드 x에서 y 로 랜덤 워크로 이동할 때 필요한 기대값(expected number of steps)
이다. (Fouss et al., 2007)
A의 대각 행렬(diagonal matrix) DA 가 값 (DA)i,i =
∑
j Ai,j 를 가지고, Pi,j 가
14
노드 i에서 j 로 가는 이동(stepping) 확률이라면, P = D−1
A A라 하자.
HT(x, y) = 1 +
∑
ω∈Γ(x)
Px,ωHT(ω, y) (23)
Definition 2.19 Commute Time (CT) HT는 대칭이 아니기 때문에, CT는 x
에서 y 로, y 에서 x 로 가는 두 가지 기대값을 모두 쓰고자 한다. L = DA − A
의 의사역행렬(pseudo inverse matrix)을 L†
라 하고, m은 사회 연결망의 링크의
개수를 세는 함수라 하자.
CT(x, y) = HT(x, y) + HT(y, x) = m(L†
x,x + L†
y,y − 2L†
x,y) (24)
Definition 2.20 Cosine Similarity Time (CST)
CST는 의사역행렬 L†
를 이용하여 계산한다.
CST(x, y) =
L†
x,y
√
L†
x,xL†
y,y
(25)
Definition 2.21 SimRank
두 개의 노드가 유사한 노드에 연결되어있는 경우, 두 노드들은 유사하다고 가정
하자. (Jeh and Widom, 2002) 파라미터 γ 는 원래 노드에서 부터 먼 정도에 따라
연결된 노드의 가중치를 얼마나 빠르게 감소시킬지를 결정한다.
simRank(x, y) =
{
1, x = y
γ ·
∑
a∈Γ(x)
∑
b∈Γ(y) simRank(a,b)
|Γ(x)|·|Γ(y)| , otherwise
(26)
이 방법은 무작위 서퍼쌍 모델(random surfer-pairs model)로 설명할 수 있는데,
독립적으로 출발한 두 개의 랜덤 서퍼가 같은 노드에서 만날 기대값을 구하는
것이다.
계산 복잡도는 O(n4
)로 큰 규모의 네트워크에는 적합하지 않다(high computation
cost).
SimRank는 많이 알려진 방법으로, 많은 코드들이 공개되어 있다. 여기서는
networkx_addon을 사용하자.
1 G = nx.Graph()
2 G.add_edges_from([('a','b'), ('b','c'), ('a','c'), ('c','d')])
3 s = networkx_addon.similarity.simrank(G)
함수의 파이썬 코드는 다음과 같다.
1 def simrank(G, c=0.9, max_iter=100, remove_neighbors=False, 
2 remove_self=False, dump_process=False):
3 if type(G) == nx.MultiGraph or type(G) == nx.MultiDiGraph:
4 raise Exception("simrank() not defined for graphs 
5 with multiedges.")
6
7 if G.is_directed():
8 raise Exception("simrank() not defined for directed 
15
9 graphs.")
10
11 sim_old = defaultdict(list)
12 sim = defaultdict(list)
13 for n in G.nodes():
14 sim[n] = defaultdict(int)
15 sim[n][n] = 1
16 sim_old[n] = defaultdict(int)
17 sim_old[n][n] = 0
18
19 # calculate simrank
20 for iter_ctr in range(max_iter):
21 if _is_converge(sim, sim_old):
22 break
23 sim_old = copy.deepcopy(sim)
24 for i, u in enumerate(G.nodes()):
25 if dump_process:
26 sys.stdout.write("r%d : % d / %d" % 
27 (iter_ctr , i, G.number_of_nodes()))
28 for v in G.nodes():
29 if u == v:
30 continue
31 s_uv = 0.0
32 for n_u in G.neighbors(u):
33 for n_v in G.neighbors(v):
34 s_uv += sim_old[n_u][n_v]
35 sim[u][v] = (c * s_uv / (len(G.neighbors(u))*
36 len(G.neighbors(v)))) 
37 if len(G.neighbors(u)) * 
38 len(G.neighbors(v)) > 0 else 0
39 if dump_process:
40 print ''
41
42 if remove_self:
43 for m in G.nodes():
44 G[m][m] = 0
45
46 if remove_neighbors:
47 for m in G.nodes():
48 for n in G.neighbors(m):
49 sim[m][n] = 0
50
51 return sim
52
53 def _is_converge(s1, s2, eps=1e-4):
54 for i in s1.keys():
55 for j in s1[i].keys():
56 if abs(s1[i][j] - s2[i][j]) >= eps:
57 return False
58 return True
16
Definition 2.22 Rooted PageRank (RPR)
RPR은 하이퍼링크로 구성된 네트워크 검색을 위한 페이지 랭크(PageRank)1
알고
리즘의 수정된 버전이다. 네트워크에서 노드의 순위(rank)는 노드들이 랜덤워크를
통해 도달하게 되는 확률에 비례한다. 여기서 매개변수 ϵ은 출발한 뒤로 얼마나
잘 이웃 노드에 방문하는지를 나타낸다. 대각행렬 D 의 원소를 Di,i =
∑
j Ai,j 라
하면, 다음과 같이 정의할 수 있다.
RPR = (1 − ϵ)(I − ϵD−1
A)−1
(27)
일반적인 페이지랭크 알고리즘은 손쉽게 돌려볼 수 있다.
1 >>> G = nx.DiGraph(nx.path_graph(4))
2 >>> pr = nx.pagerank(G, alpha=0.85)
이 함수의 파이썬 코드2
는 다음과 같다. 이를 변형하여 RPR로 바꿀 수 있다. 또는
라이브러리 Numpy 등을 활용해 행렬 연산을 하도록 하자.
1 def pagerank(G, alpha=0.85, personalization=None,
2 max_iter=100, tol=1.0e-6, nstart=None, weight='weight',
3 dangling=None):
4 if len(G) == 0:
5 return {}
6
7 if not G.is_directed():
8 D = G.to_directed()
9 else:
10 D = G
11
12 # Create a copy in (right) stochastic form
13 W = nx.stochastic_graph(D, weight=weight)
14 N = W.number_of_nodes()
15
16 # Choose fixed starting vector if not given
17 if nstart is None:
18 x = dict.fromkeys(W, 1.0 / N)
19 else:
20 # Normalized nstart vector
21 s = float(sum(nstart.values()))
22 x = dict((k, v / s) for k, v in nstart.items())
23
24 if personalization is None:
25 # Assign uniform personalization vector if not given
26 p = dict.fromkeys(W, 1.0 / N)
27 else:
28 missing = set(G) - set(personalization)
29 if missing:
30 raise NetworkXError('Personalization dictionary '
1x = (I − αAD−1)−11 = D(D − αA)−11
2https://networkx.github.io/documentation/latest/_modules/networkx/algorithms/
link_analysis/pagerank_alg.html
17
31 'must have a value for every node. '
32 'Missing nodes %s' % missing)
33 s = float(sum(personalization.values()))
34 p = dict((k, v / s) for k, v in personalization.items())
35
36 if dangling is None:
37 # Use personalization vector if dangling vector not specified
38 dangling_weights = p
39 else:
40 missing = set(G) - set(dangling)
41 if missing:
42 raise NetworkXError('Dangling node dictionary '
43 'must have a value for every node. '
44 'Missing nodes %s' % missing)
45 s = float(sum(dangling.values()))
46 dangling_weights = dict((k, v/s) for k, v in dangling.items())
47 dangling_nodes = [n for n in W if W.out_degree(n, weight=weight) == 0.0]
48
49 # power iteration: make up to max_iter iterations
50 for _ in range(max_iter):
51 xlast = x
52 x = dict.fromkeys(xlast.keys(), 0)
53 danglesum = alpha * sum(xlast[n] for n in dangling_nodes)
54 for n in x:
55 # this matrix multiply looks odd because it is
56 # doing a left multiply x^T=xlast^T*W
57 for nbr in W[n]:
58 x[nbr] += alpha * xlast[n] * W[n][nbr][weight]
59 x[n] += danglesum * dangling_weights[n] + (1.0 - alpha) * p[n]
60 # check convergence , l1 norm
61 err = sum([abs(x[n] - xlast[n]) for n in x])
62 if err < N*tol:
63 return x
64 raise NetworkXError('pagerank: power iteration failed to converge '
65 'in %d iterations.' % max_iter)
Definition 2.23 PropFlow
PropFlow는 RPR과 비슷하지만, 더 국소적으로 계산되는 특징을 가지고 있다.
PF(x, y) = PF(a, x)
wxy
∑
k∈Γ(x) wxk
(28)
2.3 사회과학 이론 기반 링크 예측
최근 많은 연구들은 링크 예측 문제를 해결하기 위해 커뮤니티(community), 삼각
닫힘 (triadic closure), 강한 연결과 약한 연결 (strong and weak ties), 유유상종
(homophily), 구조적 균형(structural balance)과 같은 고전적인 사회과학 이론들
을 이용하고 있다. 노드나 위상 기반의 링크 예측과 달리 추가적인 사회적 상호작용
18
정보를 잡아내기 때문에 성능을 향상시킬 수 있다. 특히, 규모가 큰 네트워크에서
효과적이다.
2.3.1 커뮤니티 발견 Community detection
Valverde-Rebaza and de Andrade Lopes (2013)는 규모가 큰 네트워크에서 구조
적 정보만으로 링크 예측에서 좋은 성능을 내기에는 충분하지 않기 때문에, 노드가
그들의 커뮤니티 안에서 갖는 행동이나 관심사 같은 추가적인 정보를 활용하였다.
이들은 트위터 네트워크에서의 미래 시간에 생길 링크 예측을 실험하였다. 트위터는
상호적인 관계를 요구하지 않으면서, 수많은 유저들이 활발하게 정보를 공유하는
서비스이다. 이 트위터 네트워크는 방향성을 가지면서 비대칭이고 규모가 매우
큰 특징을 갖는다. WIC 와 W form measures를 사용하는데(Valverde-Rebaza
and de Andrade Lopes, 2012), 이 접근 방법을 사용하기 위해서는 커뮤니티 발견
(community detection)이 선행되어야 한다. 여기서는 시간 복잡도를 줄이기 위해
선형시간에 가까운 Raghavan et al. (2007)의 label propagation algorithm(LPA)
를 사용했다. 커뮤니티 발견을 위해 Newman (2006)과 같은 다른 알고리즘을 썼을
때 그 성능향상을 기대할 수도 있다.
커뮤니티 발견을 위해 Blondel et al. (2008)의 방법(Louvain Community Detec-
tion)을 사용해 보자. 코드는 https://bitbucket.org/taynaud/python-louvain
에서 다운받을 수 있다. 다운받은 후 폴더 안에서 다음 명령을 실행하여 라이브러
리를 설치하자.
$ python setup.py install
설치된 라이브러리 community를 불러오고, community.best_partition 함수를
이용해 쉽게 계산할 수 있다.
1 import community
2 G = nx.karate_club_graph()
3 plt.figure(figsize=(10, 5))
4 #first compute the best partition
5 partition = community.best_partition(G)
6
7 #drawing
8 size = float(len(set(partition.values())))
9 pos = nx.spring_layout(G)
10 count = 0.
11 for com in set(partition.values()) :
12 count = count + 1.
13 list_nodes = [nodes for nodes in partition.keys()
14 if partition[nodes] == com]
15 nx.draw_networkx_nodes(G, pos, list_nodes , node_size = 50,
16 node_color = str(count / size))
17
18 nx.draw_networkx_edges(G,pos, alpha=0.5)
19 plt.axis('off');
19
Figure 5: 가라테 클럽의 Louvain Community Detection
2.3.2 중심성 Centrality
Liu et al. (2013)은 약한 연결(weak ties)과 공통 이웃의 세 가지 노드 중심성(도수
중심성 degree centrality, 근접 중심성 closeness centrality, 매개 중심성 betweeness
centrality)을 사용하여 링크 예측 방법을 제안하였다.
LCS(x, y) =
∑
z
(w(z) · f(z))β
(29)
f(z) =
{
1, z ∈ Γ(x) ∩ Γ(y),
0, otherwise
(30)
w(z)는 노드의 중심성을 의미하고, f(z)는 전환 함수(switch function)을 말한다.
β 는 공통된 이웃이 두 노드 사이 링크 가능성에 기여하는 정도를 조절한다. 만약 β
가 1보다 크다면, 큰 중심성이 작은 중심성보다 더 중요한 비중을 차지한다. 만약
β 가 0보다 작다면, 큰 중심성은 작은 중심성보다 더 억제된다. β 가 (0, 1) 사이에
있다면, 모든 노드가 동등하게 억제된다.
중심성이 중요한 역할을 한다는 것을 보여준 연구는 또 있다. Li et al. (2011)는
지금까지의 연구들은 유사한 노드를 찾는데 집중했지만, 노드의 중심성 또한 링크
예측에 중요한 역할을 한다는 사실을 보여준 연구이다. 이 사실을 보여주기 위해
극대 엔트로피 무작위 걷기(Maximal entropy random walk, MERW)를 이용한다.
MERW를 사용하는 이유는 MERW의 전이 확률이 노드의 고유벡터(eigenvector)
중심성에 비례하기 때문이다. 도수, 매개, 근접 중심성이 가지는 아이디어들과는
다르게, 고유벡터 중심성은 중요한 이웃을 많이 가질수록 그래프에서 중요한 노드
라는 것을 알려주는 측정법이다. 다시 말해, 고유벡터 중심성은 노드의 구조적 문맥
(structural context)을 잡아낸다고 할 수 있다. 게다가 노드의 중심성을 얻기 위해
서 MERW는 두 가지 좋은 성질을 가지고 있다. 첫 번째는 주어진 두 노드 사이의
같은 길이를 같는 경로는 같은 확률을 갖는다. 두 번째는 주어진 두 노드 사이의
가장 긴 경로는 낮은 확률을 갖는다. 따라서, 전통적인 무작위 걷기 (Traditional
random walk, TRW)보다 MERW가 목적에 더 적합하다고 할 수 있다.
여기에서 사용하는 중심성들을 계산해 보자.
1 import operator
20
2
3 G = nx.karate_club_graph()
4 print "::: Betweenness Centrality"
5 x = nx.betweenness_centrality(G)
6 sorted_list = sorted(x.iteritems(), key=operator.itemgetter(1),
7 reverse=True)
8 for s in sorted_list[:5]:
9 print s[0], s[1]
그래프의 매개 중심성을 계산하여 변수 x에 넣고, 매개 중심성이 높은 순서대로
정렬하여 가장 높은 순서로 5개만 출력하는 코드이다. 위 코드의 결과는 다음과
같이 출력된다.
1 ::: Betweenness Centrality
2 0 0.437635281385
3 33 0.30407497595
4 32 0.145247113997
5 2 0.143656806157
6 31 0.138275613276
도수 중심성, 근접 중심성은 nx.betweenness_centrality 대신 nx.degree_centrality,
nx.closeness_centrality를 사용한다. 더 많은 중심성들은 3.4.9절을 참고하자.
2.3.3 성장 역학 Growth Dynamics
좀 더 복잡한 형태로 같은 이벤트에 있는 구성원끼리의 관계 등을 고려하여 사회
연결망의 진화 과정을 예측하는 모형들이 있다.(Qiu et al., 2010), (Qiu et al., 2011)
2.3.4 기타 사회과학 이론
이외에도 유유상종(homophily)을 사용한 Yang et al. (2011), 이질적인 사회 연
결망(heterogeneous social network)에서의 사회적 패턴을 찾기 위해 사회적 균형
등을 사용한 Dong et al. (2012) 등의 연구가 있다.
2.4 학습 기반 링크 예측
학습 기반의 링크 예측은 최근에 연구되고 있는 분야이다. 이 분야의 연구들은 크
게 특징 기반 분류(feature-based classification), 확률적 그래프 모델(probabilistic
graph model) 그리고 행렬 인수분해(matrix factorization)로 나눌 수 있다.
2.4.1 특징 기반 분류
그래프 G(V, E)에서 x, y ∈ V 를 노드라 하고, 노드 쌍 (x, y)의 레이블(label)을
l(x,y)
라 하자. 링크 예측을 위해, 각각의 연결되지 않은 노드 쌍의 레이블을 두 가지
경우로 나누자. 양수(+1)이면 링크가 있고, 음수(−1)면 링크가 없는 경우다.
l(x,y)
=
{
+1, if (x, y) ∈ E
−1, if (x, y) /∈ E
(31)
21
Figure 6: 그래프 커널 기반 추천 시스템 프레임워크
이것은 전형적인 이진 분류 문제이고, 해결법으로 다양한 지도 분류 학습 모델
(supervised classification learning model)들을 사용할 수 있다. 많이 알려진 방법
으로는 의사 결정 나무(decision tree), 지지 벡터 머신(support vector machine),
나이브 베이즈(naive Bayes) 등이 있다.
효율적인 분류자(classifier)를 구축하기 위해서는 사회 연결망에서 적절한 특징
들을 어떻게 정의하고 추출하느냐가 중요하다. 쉽게 생각해서는, 우리가 이미 위
절에서 살펴보았던 노드, 위상, 사회 이론을 기반으로 한 측정법들을 특징으로 삼아
분류 학습 모델을 구축할 수 있다. 예를 들어, 노드와 링크의 특성(사용자의 나이,
관심사, 친구관계 등)을 사용하여 성능 향상을 꾀한다.
특징을 잡는 다른 예로써, Lichtenwalter and Chawla (2012)는 지역적 위상 정보
(local topology information)를 특징으로 잡아 점배열프로필(Vertex collocation
profile, VCP)을 구축했다. VCP는 V CPn,r
i,j 로 구성되며, n개의 노드와 r 개의
링크를 가지는 모든 가능한 서브그래프에서 그들의 공통 원소에 대해 두 점 vi,
vj 사이의 관계를 벡터로 표현한 것이다. VCP는 그 성능을 인정받아 링크 예측
라이브러리 LPmade의 1.2 버전3
에 포함되었다.
다른 방법으로는 그래프 커널 기반 학습 방법이 있다. 추천 시스템은 제품, 서비스,
콘텐츠 등을 유저에게 추천하기 위해 다양한 곳에 적용되어 왔다. 협력적 필터링
(Collaborative filtering, CF)은 현재도 많은 곳에서 쓰이는 성공적인 추천 패러다
임으로, 유저와 아이템 간의 거래 정보를 활용하는 시스템이다. 이 때 거래가 일어
나는 것은 유저와 아이템 사이에서만 일어나므로 이것은 이분(bipartite) 그래프
구조를 가지며, 추천 문제는 링크 예측 문제로 바라볼 수 있다. 이 문제를 해결하기
위해 Li and Chen (2013)는 커널 기반 학습 방법을 사용했다.
커널 학습 방법의 핵심 아이디어는 데이터들을 비선형 매핑을 통해 정보가 풍부한
(informative) 고차원 특징 공간으로 보내는 것이다. 이 방법은 커널 함수가 무엇이
냐가 중요하다.
k : χ × χ → R (32)
Li and Chen (2013)에서 커널 함수는 데이터를 입력 공간 χ 에서 특징 공간
H(reproducing kernel Hilbert space, RKHS) 으로 보낸 Φ(x) : χ → H 으로 정
의한다. 그리고 다음 조건을 만족한다. k(x, x′
) =< Φ(x), Φ(x′
) > 이에 대한
일반적인 프레임워크는 Figure 6와 같다.
3http://mloss.org/revision/view/864/
22
그 외의 다른 특징 기반 분류 방법들은 각각의 학습 방법들이 주어진 데이터에
맞게 구성되어 있어 그 각각을 기술하기에 복잡하므로, 다음 Table 34
요약본을
참고하자.
Table 3: 특징 기반 분류 방법들
방법 특징 학습 모델 네트워크 형태 장단점
VCP
Vertex collocation
profile
Classification models
in WEKA, HPLP su-
pervised link predic-
tion framework
Directed, weighted,
temporal, multi-
relational networks
Preserves as much topo-
logical information as pos-
sible; low performance in
featuring and training
Generic
kernel-
based
machine
learning
Topological features:
random walk paths;
node features: re-
flecting users’ deci-
sions
One-class SVM ker-
nel machine
User-item bipartite
network
Do not require explicit
feature generation; perfor-
mance is highly dependent
on kernel functions
Scellato
et al.
(2011)
Place features, social
features, global fea-
tures
Classifiers in WEKA:
J48, NaÅNıve Bayes,
model trees, random
forests
Location-based social
networks
Achieve high precision
Pavlov
and
Ichise
(2007),
Wohl-
farth
and
Ichise
(2008)
Topological features,
semantic and event-
based features
SVM, decision trees,
J48, decision stump,
boosting
Co-authorship net-
works
Performance is dependent
on classification models
Scripps
et al.
(2008)
Node attributes,
neighborhood topo-
logical features
Discriminative classi-
fiers
General networks
Flexible framework that
automatically determines
the most predictive fea-
tures
De Sá
and
Prudên-
cio
(2011)
Features of topology-
based metrics
J48, NaÅNıve Bayes,
IBk, libSVM, LibLin-
ear
Weighted networks
Using weights can improve
supervised link prediction
Kunegis
and
Lom-
matzsch
(2009)
Adjacency matrix,
number and length of
paths
Laplacian Kernels
Undirected,
weighted, un-
weighted, unipartite
and bipartite large
networks
General graph kernels and
dimensionality reduction;
runtime only depends on
the chosen reduced rank,
and is independent of the
original graph size
Pujari
and
Kanawati
(2012)
Topological features
Supervised rank ag-
gregation, decision
tree, naÅNıve Bayes,
kNN
General networks
Aggregate features as
many as possible; high
time complexity
4Wang et al. (2015)
23
Chiang
et al.
(2011)
Features from longer
cycles
Logistic regression Signed networks
Not only achieves good ac-
curacy for sign prediction
but is also effective in low-
ering the false positive rate
Leskovec
et al.
(2010)
Degrees of the nodes,
triad
Logistic regression Signed networks
Signs of links can be pre-
dicted with high accuracy
Cao
et al.
(2010)
No specific features
restricted
Nonparametric
Bayesian model,
transfer learning
Large user-item net-
works
Transfer learning could
help boost the performance
Brouard
et al.
(2011)
No specific features
restricted
Output kernel regres-
sion
General networks
Uses the unlabeled data to
improve performances for
a low percentage of known
links
Lu et al.
(2010)
Path-based features Logistic regression
Social networks with
multiple auxiliary
networks
Prediction accuracy is im-
proved; do not consider
other features
Wu et al.
(2013)
Statistics of co-
inventors, link
homophily, inter-
est homophily, and
correlation
Ranking factor graph
model; interactive
learning
Enterprise social net-
works
Significantly improves
the performance for rec-
ommending co-invention
relationships
Kashima
et al.
(2009)
Node features: Kro-
necker sum similar-
ity, Kronecker prod-
uct similarity
Link propagation
Multi-relational net-
works
Handles strength and types
of links; high computa-
tional time and space
Raymond
and
Kashima
(2010)
Node features: Kro-
necker sum and prod-
uct
Link propagation;
matrix factorization
and approximation
Large dynamic net-
works
Less computational cost
while maintaining accu-
racy
2.4.2 확률적 그래프 모델
사회 연결망에서 노드 쌍 사이의 링크는 랜덤 워크의 전이 확률이나 위상적 유사성
을 계산했던 것처럼 확률로써 값을 할당할 수 있다. 이것을 확률적 그래프라 한다.
연구들 중에는 많은 네트워크들이 계층적 구조(hierarchical structure)를 가진다고
그 결과를 제안한다. 여기서 계층적 구조란 노드들이 그룹에 그룹에 다시 그룹에
속하는 것과 같은 구조를 말한다.
Clauset et al. (2008)는 네트워크에서 계층적 구조를 추론하고 이것을 링크 예측을
푸는데 적용하는 방법을 제안했다. Figure 7과 같이 계층적 네트워크는 계층적 랜덤
그래프라고 불리는 계통수(dendrogram)로 표현될 수 있다. 네트워크의 노드는 N
개의 잎으로 표현되고, N − 1개에 해당하는 확률 pr 이 존재한다. 노드 쌍이 연결될
확률을 pr 로 나타내는데, r 은 두 노드의 가장 낮은 공통된 조상 (ancestor)이다.
예를 들어, Figure 7에서 노드 a와 c의 연결 확률(링크 예측)은 0.6이고, 노드 b
와 d가 연결될 확률은 0.3이다. 목표는 관찰된 네트워크에 잘 맞는 계통수을 찾는
것이다. 주어진 네트워크 G와 계통수 D 에 대해, Er 은 링크의 개수라 하자. Lr
과 Rr 은 각각 r 에서 왼쪽, 오른쪽 뿌리 방향으로의 서브 트리의 나뭇잎의 개수다.
24
그러면 링크 예측 가능성은 다음과 같이 정의하자.
L(D, {Pr}) = ΠrpEr
r (1 − pr)LrRr−Er
(33)
내부 노드의 확률은 L(D, {Pr})을 극대화함으로써 쉽게 결정된다. 연결되지 않은
노드 x, y 가 연결될지 예측하기 위해, 먼저 그들의 가능성에 비율적인 확률로 계통
수의 집합을 샘플링한다. 그리고 이것을 계속 반영해서 평균 확률 pxy 를 계산한다.
CN 같은 전통적인 측정법과 비교해 보면, 계층적 랜덤 그래프 모델은 종류별로
나누는 구조(assortative)인지 아닌지(disassortative)표현할 수 있고, 네트워크의
넓은 범위에 대해 좀 더 링크 예측의 정확도를 높일 수 있다. 하지만 계산 시간이
오래 걸리기 때문에, 수 천개의 노드 정도로 구성된 네트워크 정도에서만 사용한다.
Figure 7: 네트워크의 계통수(dendrogram)
이 외에도 확률적 블록 모델(stochastic block model, Guimerà and Sales-Pardo
(2009)), 베이즈 이론(Bayes’ Theorem)을 사용한 모델, 마코브 랜덤 필드(Markov
Random Fields, MRF)를 사용한 모델 등 많은 방법들이 존재하며, 요약된 내용은
Table 45
를 참고하자.
Table 4: 확률적 그래프 모델 방법들
방법 그래프 모델 네트워크 형태 특징
Clauset
et al.
(2008)
Hierarchical random graph,
maximum likelihood, Monte
Carlo sampling
Hierarchical networks
Accurately predict missing links;
performs poorly for networks have
no hierarchical structure
Guimerà
and
Sales-
Pardo
(2009)
Stochastic block model Noisy networks
Outperforms at identifying both
missing links and spurious links;
high computation time
Chen
and
Zhang
(2014)
Marginalized denoising model General large networks
Models the dense and smooth affin-
ity matrices; is scalable to large net-
works
5Wang et al. (2015)
25
Wang
et al.
(2007)
Maximum entropy Markov
random fields
Co-authorship net-
works
Co-occurrence probability feature is
effective for link prediction, and
combining with topology features
and semantic features can improve
the performance
Kashima
and Abe
(2006)
Parameterized probabilistic
model, incremental learning
Dynamic networks
Achieves better performance than
basic topology-based metrics
Yang
et al.
(2011)
Friendship-interest propa-
gation framework devises a
factor-based random walk
model
Interest networks,
friendship networks
Bridges collaborative filtering in rec-
ommendation systems and random
walk
Backstrom
and
Leskovec
(2011)
Supervised random walks General networks
Combines network structure with
the attributes of nodes and links;
requires no network feature gener-
ation
Marchette
and
Priebe
(2008)
Constrained random dot prod-
uct graph
Incomplete networks
Predicts the possible unobserved
links that actually present in the
network
Leroy
et al.
(2010)
Bootstrap probabilistic graph
Networks without the
initial status and with
other information
Handle the cold start link predic-
tion: predicting the structure of
a social network when the net-
work itself is totally missing while
some other information regarding
the nodes is available
Kuo
et al.
(2013)
Factor graph model
Networks with aggrega-
tive statistics of links
Link prediction with aggregative
statistics problem
2.4.3 행렬 인수분해
행렬을 인수분해하는 것은 때때로 행렬 내에 숨겨진 정보를 드러나게 하는 역할을
한다. 이를 이용해 링크 예측을 하는 것은 Menon and Elkan (2011)에서 제안되
었다.
행렬을 인수분해하는 다양한 방법 중에 특이값 분해(Singular value decomposi-
tion, SVD)와 LU 분해(Decomposition)를 해보자.
SVD는 라이브러리 Numpy를 이용해서 할 수 있다.
1 A = nx.to_numpy_matrix(G)
2 U, s, Vh = np.linalg.svd(A, full_matrices=True)
분해된 값이 행렬 A와 같은지 확인해 보자.
1 >>> np.allclose(A, np.dot(U, np.dot(np.diag(s), Vh)))
2 True
최적 근사(Best approximation)를 위해서 고유값을 잘라내 보자.
1 s[-1]=s[-2]=0
2 approx = np.dot(U, np.dot(np.diag(s), Vh))
26
이 외에도 다양한 행렬 연산 함수들을 사용해서 원하는 작업을 할 수 있다. 자
세한 것은 Numpy 메뉴얼을 참고하자. http://docs.scipy.org/doc/numpy/
reference/routines.linalg.html
LU 분해를 위해서는 라이브러리 scipy가 필요하다. 설치가 되어 있지 않은 경우
명령어 pip을 이용해 설치하자.
$ pip install scipy
scipy의 선형대수 패키지를 사용한다.
1 import scipy
2 A = nx.to_numpy_matrix(G)
3 scipy.linalg.lu(A)
3 시뮬레이션
3.1 네트워크 데이터
링크 예측을 위해 공개된 인기 있는 네트워크 데이터들은 다음과 같다. (Wang
et al., 2015)
데이터 설명
크기
링크
노드 링크
DBLP
Co-authorship
network
317080 1049866 snap.stanford.edu/data/com-DBLP.html
Paper citation
network
324339 812740 arnetminer.org/citation
Heterogeneous
bibliographic
28702 authors;
28569 docs
103201 www.cs.uiuc.edu/hbdeng/data/kdd2011.htm
Arxiv
High energy
physics paper
citation network
34546 421578
snap.stanford.edu/data/cit-HepPh.html
snap.stanford.edu/data/cit-HepTh.html
NIPS 1-17
Co-authorship
networks in NIPS
2865 4733 ai.stanford.edu/gal/data.html
Enron email
Email communi-
cation network
28000
36692
250000
183831
www.cs.cmu.edu/enron/
snap.stanford.edu/data/email-Enron.html
Patents cita-
tion
Citation net-
work among US
patents
3774768 16518948 snap.stanford.edu/data/cit-Patents.html
Facebook
Interactions be-
tween users on
Facebook
4039
60290
3694
88234
1545686
13692
snap.stanford.edu/data/egonets-Facebook.html
socialnetworks.mpi-sws.org/datasets.html
delab.csd.auth.gr/ symeon/facebook.txt
Twitter
Interactions be-
tween users on
Twitter
81306
124501
1768149
22169689
snap.stanford.edu/data/egonets-Twitter.html
lsir.epfl.ch/aberer/
Foursquare
Location-based
social network
269279 1101504 www.csie.ntu.edu.tw/ d97944007/aggregative/
27
MovieLens
Movie rating net-
work
72000 users;
10000 movies
10000000
ratings
grouplens.org/datasets/movielens/
Book-
Crossing
Book ratings net-
work
278858 users;
271379 books
1149780
ratings
www2.informatik.uni-freiburg.de/
cziegler/BX/
Wikipedia Vote network 7115 103689 snap.stanford.edu/data/wiki-Vote.html
Epinions
Trust social net-
work
131828 841372 snap.stanford.edu/data/soc-sign-epinions.html
Slashdot Signed network 82140 549202
snap.stanford.edu/data/soc-sign-
Slashdot090221.html
Plurk
Micro-blog social
network
543329 3660507 www.csie.ntu.edu.tw/ d97944007/diffusion/
3.2 Python
파이썬을 http://www.python.org를 통해 설치하면 필요한 라이브러리를 설치
하는 데 많은 시간을 소모하게 되므로, 여기서는 라이브러리가 미리 통합되어 있는
파이썬 배포판6
중 하나인 Anaconda를 사용하도록 한다. Anaconda는 레드햇에서
만들었으며 칼데라 오픈리눅스 설치 소프트웨어 이름이 리자드(도마뱀)인 것에서
도마뱀을 먹는 비단뱀을 뜻하는 아나콘다라는 이름이 지어졌다. 윈도우, 맥, 리눅스
버전을 제공한다. 여기서는 Python 2.7을 사용하도록 하자.
Anaconda Download : https://www.continuum.io/downloads
라이브러리에 대한 명령은 다음과 같이 이용하자.
Theorem 3.1 윈도우 유저의 경우, 윈도우 키를 누르고 cmd 입력, 엔터 후 나오는
화면에서 아래의 명령어 입력한다. 맥 또는 리눅스 유저의 경우, 터미널에서 명령
어를 사용하자.
• python -m pip install -U pip # pip의 버전 업그레이드
• pip install -U ipython # ipython의 버전 업그레이드
– pip install <라이브러리 이름> # 설치
– pip install -U <라이브러리 이름> # 업그레이드
– pip uninstall <라이브러리 이름> # 제거
윈도우 유저의 경우, ASCII 에러가 날 수 있다. 이 경우 아래의 내용을 수정해야
한다.
• 텍스트 에디터로 다음 파일 열기 ‘C:AnacondaLibsite.py’
• 아래 내용을 찾아
def setencoding():
encoding = “ascii”
6Enthought Canopy, Continuum Analytics Anaconda, Python(x,y), WinPython
28
• 아래처럼 변경
def setencoding():
encoding = “mbcs”
3.3 IPython
IPython은 인터랙티브 컴퓨팅을 위한 명령 쉘을 제공한다. IPython notebook
을 이용하면 웹 상에서 입력, 출력 셀을 통해 리치 미디어를 다룰 수 있어 매우
편리하다. 최신 버전을 사용하는 경우, Jupyter라는 이름으로 바뀌었을 수 있다.
IPython notebook의 사용은 Anaconda Launcher에서 실행하거나 터미널 또는
cmd에서 명령어를 입력하여 시작한다.
$ ipython notebook
실행 후, 크롬 등의 인터넷 브라우져를 통해 http://localhost:8888 또는 실행 화
면에서 나오는 주소를 통해 접속한다.
IPython에 대한 학습은 다음 사이트를 참고하자.
https://github.com/jrjohansson/scientific-python-lectures
3.4 Networkx
네트워크(그래프) 계산을 하기 위한 라이브러리로 Networkx를 이용할 수 있다.
만약 설치가 되어있지 않다면 다음과 같이 Command Mode에서 쉽게 설치할 수
있다.
$ pip install networkx
or $ easy_install networkx
or $ sudo apt-get install python-networkx
수동으로 설치할 경우 pypi7
를 참고하자.
Networkx를 이용하기 위한 기본적인 방법은 다음과 같다.
1 >>> import networkx as nx # Import Library
2 >>> G = nx.Graph() # Generate graph type
3 >>> G.add_edge(1,2) # Add link
4 >>> nx.draw(G) # Draw graph
3.4.1 Graph 만들기
그래프의 형태를 먼저 정의하고, 노드와 링크를 추가한다.
1 >>> import networkx as nx # Import Library
2 >>> G=nx.Graph() # Define Graph Type
3 >>> G.add_node('a', 'b', 'c')
4 >>> G.add_edge('a', 'b')
7https://pypi.python.org/pypi/networkx/
29
Networkx에서 지원하는 그래프의 형태는 총 네 가지로 Graph(), DiGraph(),
MultiGraph(), MultiDiGraph()8
이다.
3.4.2 노드를 정의하는 방법
1 >>> G = nx.Graph()
2 >>> G.add_node('apple') % 노드 'apple' 추가
3 >>> G . add_nodes_from(['banana' ,'kiwi' ,'mango']) % 리스트로추가 1
4 or
5 >>> fruits = ['banana' ,'kiwi' ,'mango']
6 >>> G . add_nodes_from(fruits) % 리스트로추가 2
7
8 >>> G . nodes() % 노드들보기
9 ['apple' , 'kiwi' , 'mango' , 'banana']
3.4.3 노드의 속성 부여하기
1 >>> G.nodes()
2 ['kiwi', 'mango', 'apple', 'banana']
3 >>> G.node['kiwi']
4 {}
5 >>> G.node['kiwi']['kind'] = 'fruit'
6 >>> G.node['kiwi']
7 {'kind': 'fruit'}
8 >>> G.nodes(data=True)
9 [('kiwi', {'kind': 'fruit'}), ('mango', {}), ('apple', {}),
10 ('banana', {})]
11
12 >>> G.add_node('kiwi', kind='fruit')
13 >>> G.add_nodes_from(['banana', 'apple'], kind='fruit')
14 >>> G.node['banana']
15 {'kind': 'fruit'}
3.4.4 엣지를 정의하는 방법
1 >>> G = nx.Graph()
2 >>> G.add_edge('apple', 'banana') % 'apple'과 'banana'의 관계추가
3 >>> G . add_edges_from([('apple' ,'mango'),('apple' ,'kiwi')]) % 리
스트로추가 1
4 or
5 >>> relations = [('apple' ,'mango'),('apple' ,'kiwi')]
6 >>> G . add_edges_from(relations) % 리스트로추가 2
7
8 >>> G . edges() % 엣지들보기
9 [('apple' , 'banana'), ('kiwi' , 'apple'), ('mango' , 'apple')]
3.4.5 엣지의 속성 부여하기
8https://networkx.github.io/documentation/latest/reference/classes.html
30
1 >>> G.edges()
2 [('kiwi', 'apple'), ('mango', 'apple'), ('apple', 'banana')]
3 >>> G.edges(data=True)
4 [('kiwi', 'apple', {}), ('mango', 'apple', {}), ('apple',
5 'banana', {})]
6
7 >>> G.add_edge('apple', 'mango', weight=2.5)
8 >>> G.add_edges_from(relations , color='blue')
9 >>> G['apple']['mango']['weight']=5
10 >>> G.edge['apple']['kiwi']['weight']=2
11 >>> G.edges(data=True)
12 [('kiwi', 'apple', {'color': 'blue'}),
13 ('mango', 'apple', {'color': 'blue', 'weight': 5}),
14 ('apple', 'banana', {})]
3.4.6 네트워크 그리기
네트워크를 그리기 위해서는 크게 세 가지가 정의되어 있어야 한다.
a. 점
b. 선
c. 점의 위치
a와 b는 위에서 살펴 보았으므로, c를 알아보도록 하자.
기본적인 명령어 nx.draw 를 사용했을 때는 점의 위치를 spring layout으로 계산
하여 그림을 그려준다.
1 >>> G = nx.Graph()
2 >>> relations = [('apple', 'banana'), ('kiwi', 'apple'),
3 ('mango', 'apple')]
4 >>> G.add_edges_from(relations) # Generate nodes, edges
5 >>> nx.draw(G) # Generate positions of nodes with spring layout
만약 원하는 그래프 레이아웃이 있는 경우, 다음의 명령어들을 사용한다.
1 >>> nx.draw(G) # 기본그리기
2 >>> nx.draw_circular(G) # 원위에노드놓기
3 >>> nx.draw_graphviz(G) # Graphviz 사용
4 >>> nx.draw_random(G) # 균등분포를이용한랜덤
5 >>> nx.draw_shell(G) # 동심원위에노드놓기
6 >>> nx.draw_spectral(G) # 그래프라플라시안의고유벡터기반
7 >>> nx.draw_spring}}(G) # Fruchterman -Reingold force-directed
예를 들어, 다음과 같이 pos 변수를 점들의 위치로 지정하고, 그 변수를 draw할 때
position으로 사용한다.
1 >>> pos = nx.spectral_layout(G)
2 >>> print pos
3 {'kiwi': array([ 1., 0.]), 'mango': array([ 0., 1.]),
4 'apple': array([ 0.66666667, 0.66666667]), 'banana':
5 array([ 1., 1.])}
6
7 >>> nx.draw(G, pos)
31
3.4.7 한글이 들어간 네트워크 그리기
네트워크 그림에서 한글이 표시되지 않을 때는, 한글이 패치된 버전을 사용하면
일시적으로 해결할 수 있다.
pip install -U git+https://github.com/koorukuroo/networkx_for_unicode
한국어 폰트를 사용하기 위해서 아래와 같이 폰트의 위치를 설정한다.
1 import matplotlib.font_manager as fm
2 # fp1 = fm.FontProperties(fname="./NanumGothic.otf")
3 fp1 = fm.FontProperties(fname="./NotoSansKR -Regular.otf")
4 nx.set_fontproperties(fp1)
5 G = nx.Graph()
6 G.add_edge(u'한국어',u'영어')
7 nx.draw(G, with_labels=True)
폰트가 마땅한 것이 없을 때에는 https://www.google.com/get/noto/pkgs/
NotoSansKorean-windows.zip 사용을 추천한다.
3.4.8 네트워크 정보 보기
1 print "Number of Nodes : ", nx.number_of_nodes(G)
2 print "Number of Edges : ", nx.number_of_edges(G)
3 degreelist = list(G.degree().values())
4 print "Avg. Node Degree : ", float(sum(degreelist))/
5 nx.number_of_nodes(G)
6 try:
7 print "Avg. Path Length : ",
8 nx.average_shortest_path_length(G)
9 except nx.NetworkXError as e:
10 print e
11 print "Avg. Clustering Coefficient : ",
12 nx.average_clustering(G)
13 Number of Nodes : 5242
14 Number of Edges : 67806
15 Avg. Node Degree : 25.8702785196
16 Avg. Path Length : Graph is not connected.
17 Avg. Clustering Coefficient : 0.259480104154
3.4.9 네트워크의 중심성 계산하기
Networkx에서는 다양한 중심성 계산 함수들을 제공한다.9
도수 중심성 Degree
1 nx.degree_centrality(G)
2 nx.in_degree_centrality(G)
3 nx.out_degree_centrality(G)
근접 중심성 Closeness
9https://networkx.github.io/documentation/latest/reference/algorithms.
centrality.html
32
1 nx.closeness_centrality(G[, u, distance , ...])
매개 중심성 Betweenness
1 nx.betweenness_centrality(G[, k, normalized , ...])
2 nx.edge_betweenness_centrality(G[, k, ...])
Current Flow Closeness
1 nx.current_flow_closeness_centrality(G[, ...])
Current-Flow Betweenness
1 nx.current_flow_betweenness_centrality(G[, ...])
2 nx.edge_current_flow_betweenness_centrality(G)
3 nx.approximate_current_flow_betweenness_centrality(G)
고유벡터 중심성 Eigenvector
1 nx.eigenvector_centrality(G[, max_iter , tol, ...])
2 nx.eigenvector_centrality_numpy(G[, weight])
3 nx.katz_centrality(G[, alpha, beta, max_iter , ...])
4 nx.katz_centrality_numpy(G[, alpha, beta, ...])
Communicability
1 nx.communicability(G)
2 nx.communicability_exp(G)
3 nx.communicability_centrality(G)
4 nx.communicability_centrality_exp(G)
5 nx.communicability_betweenness_centrality(G[, ...])
6 nx.estrada_index(G)
Load
1 nx.load_centrality(G[, v, cutoff, normalized , ...])
2 nx.edge_load(G[, nodes, cutoff])
Dispersion
1 nx.dispersion(G[, u, v, normalized , alpha, b, c])
3.5 Gephi
Gephi는 공개된 그래프 네트워크 시각화 프로그램이다. Gephi의 발음은 gϵfi10
로
한다. Gephi는 http://gephi.github.io에서 다운 받을 수 있다. 만약 Java8이
설치되어 있다면 Gephi가 올바르게 실행되지 않을 수 있다. 아쉽지만 Gephi 0.8.2
beta에서는 Java7을 사용해야 한다. http://www.oracle.com/technetwork/
java/javase/downloads/jdk7-downloads-1880260.html을 참고하여 Java SE
Development Kit 7u79을 설치하자.
네트워크를 GUI(Graphic User Interface) 환경에서 다루고 싶을 때, Networkx에서
생성한 네트워크를 gephi로 가져올 수 있다. Networkx의 가라테 도장11
(Zachary,
1977) 데이터를 사용하자.
10https://en.wikipedia.org/wiki/Pronunciation_respelling_for_English
11http://vlado.fmf.uni-lj.si/pub/networks/data/Ucinet/UciData.htm
33
Figure 8: Gephi 실행 화면
1 G = nx.karate_club_graph()
2 nx.draw(G, with_labels=True)
Figure 9: 가라테 클럽의 networkx 그림
이 데이터를 Gephi에서 사용할 수 있도록 변환하자.
1 nx.write_gexf(G, 'karate.gexf')
IPython notebook이 실행된 위치(ipynb 파일이 있는 곳)에 gexf 파일이 생성되
었다. 그 파일을 찾아 Gephi에서 불러오자. 이것을 적당히 조절하면 Figure 11
와 같이 그릴 수 있다. 자세한 사용법은 http://gephi.github.io/users/ 또는
Gephi Cookbook12
등을 참고하자.
12https://www.packtpub.com/big-data-and-business-intelligence/gephi-cookbook
34
Figure 10: 가라테 클럽의 Gephi 그림
Figure 11: 가라테 클럽의 Gephi 그림
3.6 Pynetviz
Networkx에서 그래프를 그리기 위해 nx.draw 함수를 사용하는 것은 라이브러리
Matplotlib의 pyplot을 이용한 기능이다. 간단한 네트워크라면 상관 없지만, 만약
규모가 큰 네트워크라면 그림을 그리는 데 상당히 많은 시간이 소요되며, 그림의
모양이 보기 좋지 않을 경우 다시 그려야 하는 불편함이 있다. 이 불편함을 해소하기
위해, 데이터 시각화 라이브러리 D3.js를 사용한 라이브러리 pynetviz를 사용해서
네트워크를 그려보도록 하자. https://pypi.python.org/pypi/pynetviz
$ pip install pynetviz
가장 기본적인 사용법은 다음과 같다.
35
1 import pynetviz.sigmajs as nvs
2 G = nx.karate_club_graph()
3 layout = nx.spring_layout(G)
4 nvs.make_gexf(G, layout)
5 nvs.make_html(drawEdges='true')
6 nvs.view_html(height=1000)
Figure 12: 가라테 클럽의 Pynetviz 그림
중심성 등을 반영한 노드의 사이즈 조절은 다음과 같이 할 수 있다.
1 layout = nx.spring_layout(G)
2 nvs.make_gexf(G, layout, size=nx.betweenness_centrality(G))
3 nvs.make_html(drawEdges='true')
4 nvs.view_html(height=500)
자세한 사용법은 https://github.com/koorukuroo/pynetviz 또는 http://
goo.gl/7U2IlV을 참고하자.
3.7 Scikit-Learn
Scikit-Learn은 파이썬의 기계학습 (Machine learning) 라이브러리이다. Clas-
sification, Regression, Clustering, Dimensionality reduction, Model selection,
36
Figure 13: 가라테 클럽의 Pynetviz 그림 with Centrality
Preprocessing 등 전통적인 방법들을 대다수 지원하고 있으며, 일부 함수들의 경우
병렬 계산도 지원한다.
사용 방법은 http://scikit-learn.org/stable/documentation.html을 참고
하자.
4 Conclusions
링크 예측을 하는 주요 방법들과 그 방법들을 파이썬으로 구현하는 방법에 대해
살펴봤다. 링크 예측의 전통적인 방법이나 유명한 방법이 아닌 경우 코드로 구현되어
있지 않아 직접 구현을 해야 하지만, 파이썬에서 Numpy, Networkx, Scikit-learn
등을 이용해 어렵지 않게 구현할 수 있음을 알 수 있다. 네트워크의 시각화는 Pyplot,
Gephi, Pynetviz 등을 통해 가능함을 살펴보았다.
C언어로 작성된 LPmade13
를 파이썬에서 사용하고 싶은 경우 작성되어 있는
Python Wrapper를 이용하여 사용할 수 있다. 다음을 참고하자. https://github.
com/jtreanor/LPmade-Python
References
Anderson, A., Huttenlocher, D., Kleinberg, J., and Leskovec, J. (2012). Effects
of user similarity in social media. In Proceedings of the fifth ACM international
conference on Web search and data mining, pages 703–712. ACM.
Backstrom, L. and Leskovec, J. (2011). Supervised random walks: predicting
and recommending links in social networks. In Proceedings of the fourth
ACM international conference on Web search and data mining, pages 635–
644. ACM.
Berry, M. W., Drmac, Z., and Jessup, E. R. (1999). Matrices, vector spaces,
and information retrieval. SIAM review, 41(2):335–362.
13http://mloss.org/software/view/307/
37
Blondel, V. D., Guillaume, J.-L., Lambiotte, R., and Lefebvre, E. (2008). Fast
unfolding of communities in large networks. Journal of Statistical Mechanics:
Theory and Experiment, 2008(10):P10008.
Borgatti, S. P., Mehra, A., Brass, D. J., and Labianca, G. (2009). Network
analysis in the social sciences. science, 323(5916):892–895.
Brouard, C., Szafranski, M., et al. (2011). Semi-supervised penalized output
kernel regression for link prediction. In Proceedings of the 28th International
Conference on Machine Learning (ICML-11), pages 593–600.
Cao, B., Liu, N. N., and Yang, Q. (2010). Transfer learning for collective
link prediction in multiple heterogenous domains. In Proceedings of the 27th
International Conference on Machine Learning (ICML-10), pages 159–166.
Chen, H.-H., Gou, L., Zhang, X. L., and Giles, C. L. (2012). Discovering missing
links in networks using vertex similarity measures. In Proceedings of the 27th
Annual ACM Symposium on Applied Computing, pages 138–143. ACM.
Chen, Z. and Zhang, W. (2014). A marginalized denoising method for link
prediction in relational data. In Proceedings of the 2014 SIAM International
Conference on Data Mining, Philadelphia, pages 298–306.
Chiang, K.-Y., Natarajan, N., Tewari, A., and Dhillon, I. S. (2011). Exploiting
longer cycles for link prediction in signed networks. In Proceedings of the 20th
ACM international conference on Information and knowledge management,
pages 1157–1162. ACM.
Clauset, A., Moore, C., and Newman, M. E. (2008). Hierarchical structure and
the prediction of missing links in networks. Nature, 453(7191):98–101.
De Sá, H. R. and Prudêncio, R. B. (2011). Supervised link prediction in weighted
networks. In Neural Networks (IJCNN), The 2011 International Joint Con-
ference on, pages 2281–2288. IEEE.
Dong, Y., Tang, J., Wu, S., Tian, J., Chawla, N. V., Rao, J., and Cao, H. (2012).
Link prediction and recommendation across heterogeneous social networks. In
Data Mining (ICDM), 2012 IEEE 12th International Conference on, pages
181–190. IEEE.
Fouss, F., Pirotte, A., Renders, J.-M., and Saerens, M. (2007). Random-walk
computation of similarities between nodes of a graph with application to
collaborative recommendation. Knowledge and data engineering, ieee trans-
actions on, 19(3):355–369.
Guimerà, R. and Sales-Pardo, M. (2009). Missing and spurious interactions and
the reconstruction of complex networks. Proceedings of the National Academy
of Sciences, 106(52):22073–22078.
38
Jeh, G. and Widom, J. (2002). Simrank: a measure of structural-context sim-
ilarity. In Proceedings of the eighth ACM SIGKDD international conference
on Knowledge discovery and data mining, pages 538–543. ACM.
Jones, W. P. and Furnas, G. W. (1987). Pictures of relevance: A geometric anal-
ysis of similarity measures. Journal of the American society for information
science, 38(6):420–442.
Kashima, H. and Abe, N. (2006). A parameterized probabilistic model of
network evolution for supervised link prediction. In Data Mining, 2006.
ICDM’06. Sixth International Conference on, pages 340–349. IEEE.
Kashima, H., Kato, T., Yamanishi, Y., Sugiyama, M., and Tsuda, K. (2009).
Link propagation: A fast semi-supervised learning algorithm for link predic-
tion. In SDM, volume 9, pages 1099–1110. SIAM.
Katz, L. (1953). A new status index derived from sociometric analysis. Psy-
chometrika, 18(1):39–43.
Kunegis, J. and Lommatzsch, A. (2009). Learning spectral graph transforma-
tions for link prediction. In Proceedings of the 26th Annual International
Conference on Machine Learning, pages 561–568. ACM.
Kuo, T.-T., Yan, R., Huang, Y.-Y., Kung, P.-H., and Lin, S.-D. (2013). Unsu-
pervised link prediction using aggregative statistics on heterogeneous social
networks. In Proceedings of the 19th ACM SIGKDD international conference
on Knowledge discovery and data mining, pages 775–783. ACM.
Leicht, E., Holme, P., and Newman, M. E. (2006). Vertex similarity in networks.
Physical Review E, 73(2):026120.
Leroy, V., Cambazoglu, B. B., and Bonchi, F. (2010). Cold start link predic-
tion. In Proceedings of the 16th ACM SIGKDD international conference on
Knowledge discovery and data mining, pages 393–402. ACM.
Leskovec, J., Huttenlocher, D., and Kleinberg, J. (2010). Predicting positive
and negative links in online social networks. In Proceedings of the 19th inter-
national conference on World wide web, pages 641–650. ACM.
Li, R.-H., Yu, J. X., and Liu, J. (2011). Link prediction: the power of maximal
entropy random walk. In Proceedings of the 20th ACM international confer-
ence on Information and knowledge management, pages 1147–1156. ACM.
Li, X. and Chen, H. (2013). Recommendation as link prediction in bipartite
graphs: A graph kernel-based machine learning approach. Decision Support
Systems, 54(2):880–890.
Liben-Nowell, D. and Kleinberg, J. (2007). The link-prediction problem for
social networks. Journal of the American society for information science and
technology, 58(7):1019–1031.
39
Lichtenwalter, R. N. and Chawla, N. V. (2012). Vertex collocation profiles:
subgraph counting for link analysis and prediction. In Proceedings of the 21st
international conference on World Wide Web, pages 1019–1028. ACM.
Liu, H., Hu, Z., Haddadi, H., and Tian, H. (2013). Hidden link prediction based
on node centrality and weak ties. EPL (Europhysics Letters), 101(1):18004.
Lü, L., Jin, C.-H., and Zhou, T. (2009). Similarity index based on local paths
for link prediction of complex networks. Physical Review E, 80(4):046122.
Lu, Z., Savas, B., Tang, W., and Dhillon, I. S. (2010). Supervised link pre-
diction using multiple sources. In Data Mining (ICDM), 2010 IEEE 10th
International Conference on, pages 923–928. IEEE.
Marchette, D. J. and Priebe, C. E. (2008). Predicting unobserved links in
incompletely observed networks. Computational Statistics & Data Analysis,
52(3):1373–1386.
Menon, A. K. and Elkan, C. (2011). Link prediction via matrix factorization.
In Machine Learning and Knowledge Discovery in Databases, pages 437–452.
Springer.
Newman, M. E. (2001). Clustering and preferential attachment in growing
networks. Physical Review E, 64(2):025102.
Newman, M. E. (2006). Modularity and community structure in networks.
Proceedings of the National Academy of Sciences, 103(23):8577–8582.
Papadimitriou, A., Symeonidis, P., and Manolopoulos, Y. (2012). Fast and
accurate link prediction in social networking systems. Journal of Systems
and Software, 85(9):2119–2132.
Pavlov, M. and Ichise, R. (2007). Finding experts by link prediction in co-
authorship networks. FEWS, 290:42–55.
Pujari, M. and Kanawati, R. (2012). Link prediction in complex networks by
supervised rank aggregation. In Tools with Artificial Intelligence (ICTAI),
2012 IEEE 24th International Conference on, volume 1, pages 782–789. IEEE.
Qiu, B., He, Q., and Yen, J. (2011). Evolution of node behavior in link predic-
tion. In AAAI.
Qiu, B., Ivanova, K., Yen, J., and Liu, P. (2010). Behavior evolution and event-
driven growth dynamics in social networks. In Social Computing (SocialCom),
2010 IEEE Second International Conference on, pages 217–224. IEEE.
Raghavan, U. N., Albert, R., and Kumara, S. (2007). Near linear time algorithm
to detect community structures in large-scale networks. Physical Review E,
76(3):036106.
40
Ravasz, E., Somera, A. L., Mongru, D. A., Oltvai, Z. N., and Barabási, A.-
L. (2002). Hierarchical organization of modularity in metabolic networks.
science, 297(5586):1551–1555.
Raymond, R. and Kashima, H. (2010). Fast and scalable algorithms for semi-
supervised link prediction on static and dynamic graphs. In Machine Learning
and Knowledge Discovery in Databases, pages 131–147. Springer.
Scellato, S., Noulas, A., and Mascolo, C. (2011). Exploiting place features in
link prediction on location-based social networks. In Proceedings of the 17th
ACM SIGKDD international conference on Knowledge discovery and data
mining, pages 1046–1054. ACM.
Scripps, J., Tan, P.-N., Chen, F., and Esfahanian, A.-H. (2008). A matrix
alignment approach for link prediction. In ICPR, pages 1–4. Citeseer.
Turney, P. D., Pantel, P., et al. (2010). From frequency to meaning: Vector space
models of semantics. Journal of artificial intelligence research, 37(1):141–188.
Valverde-Rebaza, J. and de Andrade Lopes, A. (2013). Exploiting behaviors of
communities of twitter users for link prediction. Social Network Analysis and
Mining, 3(4):1063–1074.
Valverde-Rebaza, J. C. and de Andrade Lopes, A. (2012). Link prediction in
complex networks based on cluster information. In Advances in Artificial
Intelligence-SBIA 2012, pages 92–101. Springer.
Wang, C., Satuluri, V., and Parthasarathy, S. (2007). Local probabilistic mod-
els for link prediction. In Data Mining, 2007. ICDM 2007. Seventh IEEE
International Conference on, pages 322–331. IEEE.
Wang, P., Xu, B., Wu, Y., and Zhou, X. (2015). Link prediction in social
networks: the state-of-the-art. Science China Information Sciences, 58(1):1–
38.
Wohlfarth, T. and Ichise, R. (2008). Semantic and event-based approach for
link prediction. In Practical Aspects of Knowledge Management, pages 50–61.
Springer.
Wu, S., Sun, J., and Tang, J. (2013). Patent partner recommendation in enter-
prise social networks. In Proceedings of the sixth ACM international confer-
ence on Web search and data mining, pages 43–52. ACM.
Yang, S.-H., Long, B., Smola, A., Sadagopan, N., Zheng, Z., and Zha, H. (2011).
Like like alike: joint friendship and interest propagation in social networks.
In Proceedings of the 20th international conference on World wide web, pages
537–546. ACM.
Zachary, W. W. (1977). An information flow model for conflict and fission in
small groups. Journal of anthropological research, pages 452–473.
41
Zhou, T., Lü, L., and Zhang, Y.-C. (2009). Predicting missing links via local
information. The European Physical Journal B, 71(4):623–630.
Zhu, Y.-X., Lü, L., Zhang, Q.-M., and Zhou, T. (2012). Uncovering missing
links with cold ends. Physica A: Statistical Mechanics and its Applications,
391(22):5769–5778.
42

More Related Content

What's hot

Tokyor35 人工データの発生
Tokyor35 人工データの発生Tokyor35 人工データの発生
Tokyor35 人工データの発生
Yohei Sato
 

What's hot (20)

2値ディープニューラルネットワークと組込み機器への応用: 開発中のツール紹介
2値ディープニューラルネットワークと組込み機器への応用: 開発中のツール紹介2値ディープニューラルネットワークと組込み機器への応用: 開発中のツール紹介
2値ディープニューラルネットワークと組込み機器への応用: 開発中のツール紹介
 
SSII2020SS: グラフデータでも深層学習 〜 Graph Neural Networks 入門 〜
SSII2020SS: グラフデータでも深層学習 〜 Graph Neural Networks 入門 〜SSII2020SS: グラフデータでも深層学習 〜 Graph Neural Networks 入門 〜
SSII2020SS: グラフデータでも深層学習 〜 Graph Neural Networks 入門 〜
 
2 データのベクトル表現と集合
2 データのベクトル表現と集合2 データのベクトル表現と集合
2 データのベクトル表現と集合
 
MLP-Mixer: An all-MLP Architecture for Vision
MLP-Mixer: An all-MLP Architecture for VisionMLP-Mixer: An all-MLP Architecture for Vision
MLP-Mixer: An all-MLP Architecture for Vision
 
【DL輪読会】Trajectory Prediction with Latent Belief Energy-Based Model
【DL輪読会】Trajectory Prediction with Latent Belief Energy-Based Model【DL輪読会】Trajectory Prediction with Latent Belief Energy-Based Model
【DL輪読会】Trajectory Prediction with Latent Belief Energy-Based Model
 
【論文紹介】How Powerful are Graph Neural Networks?
【論文紹介】How Powerful are Graph Neural Networks?【論文紹介】How Powerful are Graph Neural Networks?
【論文紹介】How Powerful are Graph Neural Networks?
 
深層学習と確率プログラミングを融合したEdwardについて
深層学習と確率プログラミングを融合したEdwardについて深層学習と確率プログラミングを融合したEdwardについて
深層学習と確率プログラミングを融合したEdwardについて
 
Graph convolution (スペクトルアプローチ)
Graph convolution (スペクトルアプローチ)Graph convolution (スペクトルアプローチ)
Graph convolution (スペクトルアプローチ)
 
Link prediction
Link predictionLink prediction
Link prediction
 
グラフデータ分析 入門編
グラフデータ分析 入門編グラフデータ分析 入門編
グラフデータ分析 入門編
 
PCAの最終形態GPLVMの解説
PCAの最終形態GPLVMの解説PCAの最終形態GPLVMの解説
PCAの最終形態GPLVMの解説
 
できる!遺伝的アルゴリズム
できる!遺伝的アルゴリズムできる!遺伝的アルゴリズム
できる!遺伝的アルゴリズム
 
[DL輪読会]A Bayesian Perspective on Generalization and Stochastic Gradient Descent
 [DL輪読会]A Bayesian Perspective on Generalization and Stochastic Gradient Descent [DL輪読会]A Bayesian Perspective on Generalization and Stochastic Gradient Descent
[DL輪読会]A Bayesian Perspective on Generalization and Stochastic Gradient Descent
 
Graph Attention Network
Graph Attention NetworkGraph Attention Network
Graph Attention Network
 
Graph Convolutional Network 概説
Graph Convolutional Network 概説Graph Convolutional Network 概説
Graph Convolutional Network 概説
 
[기초개념] Graph Convolutional Network (GCN)
[기초개념] Graph Convolutional Network (GCN)[기초개념] Graph Convolutional Network (GCN)
[기초개념] Graph Convolutional Network (GCN)
 
[DL輪読会]Adversarial Feature Matching for Text Generation
[DL輪読会]Adversarial Feature Matching for Text Generation[DL輪読会]Adversarial Feature Matching for Text Generation
[DL輪読会]Adversarial Feature Matching for Text Generation
 
Tokyor35 人工データの発生
Tokyor35 人工データの発生Tokyor35 人工データの発生
Tokyor35 人工データの発生
 
ベイズ統計学の概論的紹介
ベイズ統計学の概論的紹介ベイズ統計学の概論的紹介
ベイズ統計学の概論的紹介
 
[PRML] パターン認識と機械学習(第2章:確率分布)
[PRML] パターン認識と機械学習(第2章:確率分布)[PRML] パターン認識と機械学習(第2章:確率分布)
[PRML] パターン認識と機械学習(第2章:確率分布)
 

Viewers also liked

[20150829, PyCon2015] NetworkX를 이용한 네트워크 링크 예측
[20150829, PyCon2015] NetworkX를 이용한 네트워크 링크 예측[20150829, PyCon2015] NetworkX를 이용한 네트워크 링크 예측
[20150829, PyCon2015] NetworkX를 이용한 네트워크 링크 예측
Kyunghoon Kim
 
사이버컴과 네트워크분석 6주차 1
사이버컴과 네트워크분석 6주차 1사이버컴과 네트워크분석 6주차 1
사이버컴과 네트워크분석 6주차 1
Han Woo PARK
 

Viewers also liked (13)

Reasoning Over Knowledge Base
Reasoning Over Knowledge BaseReasoning Over Knowledge Base
Reasoning Over Knowledge Base
 
[20150829, PyCon2015] NetworkX를 이용한 네트워크 링크 예측
[20150829, PyCon2015] NetworkX를 이용한 네트워크 링크 예측[20150829, PyCon2015] NetworkX를 이용한 네트워크 링크 예측
[20150829, PyCon2015] NetworkX를 이용한 네트워크 링크 예측
 
Using Bayesian Optimization to Tune Machine Learning Models
Using Bayesian Optimization to Tune Machine Learning ModelsUsing Bayesian Optimization to Tune Machine Learning Models
Using Bayesian Optimization to Tune Machine Learning Models
 
Comparison Study of Decision Tree Ensembles for Regression
Comparison Study of Decision Tree Ensembles for RegressionComparison Study of Decision Tree Ensembles for Regression
Comparison Study of Decision Tree Ensembles for Regression
 
Topic Modeling
Topic ModelingTopic Modeling
Topic Modeling
 
사이버컴과 네트워크분석 6주차 1
사이버컴과 네트워크분석 6주차 1사이버컴과 네트워크분석 6주차 1
사이버컴과 네트워크분석 6주차 1
 
One-Shot Learning
One-Shot LearningOne-Shot Learning
One-Shot Learning
 
7장 네트워크로 세상을 읽다 : 사회 관계망 분석 입문하기
7장 네트워크로 세상을 읽다 : 사회 관계망 분석 입문하기7장 네트워크로 세상을 읽다 : 사회 관계망 분석 입문하기
7장 네트워크로 세상을 읽다 : 사회 관계망 분석 입문하기
 
Overview of TensorFlow For Natural Language Processing
Overview of TensorFlow For Natural Language ProcessingOverview of TensorFlow For Natural Language Processing
Overview of TensorFlow For Natural Language Processing
 
Convolutional Neural Network for Alzheimer’s disease diagnosis with Neuroim...
Convolutional Neural Network for Alzheimer’s disease diagnosis with Neuroim...Convolutional Neural Network for Alzheimer’s disease diagnosis with Neuroim...
Convolutional Neural Network for Alzheimer’s disease diagnosis with Neuroim...
 
Deep Learning For Speech Recognition
Deep Learning For Speech RecognitionDeep Learning For Speech Recognition
Deep Learning For Speech Recognition
 
Gephi Quick Start
Gephi Quick StartGephi Quick Start
Gephi Quick Start
 
How To Do A Discourse Analysis
How To Do A Discourse AnalysisHow To Do A Discourse Analysis
How To Do A Discourse Analysis
 

Similar to 사회 연결망의 링크 예측

이산치수학 Project5
이산치수학 Project5이산치수학 Project5
이산치수학 Project5
KoChungWook
 
Data Structure 2
Data Structure 2Data Structure 2
Data Structure 2
yonsei
 
사이버컴과 네트워크분석 5주차 1
사이버컴과 네트워크분석 5주차 1사이버컴과 네트워크분석 5주차 1
사이버컴과 네트워크분석 5주차 1
Han Woo PARK
 

Similar to 사회 연결망의 링크 예측 (20)

이산치수학 Project5
이산치수학 Project5이산치수학 Project5
이산치수학 Project5
 
Data Structure 2
Data Structure 2Data Structure 2
Data Structure 2
 
사이버컴과 네트워크분석 5주차 1
사이버컴과 네트워크분석 5주차 1사이버컴과 네트워크분석 5주차 1
사이버컴과 네트워크분석 5주차 1
 
Chapter 16 structured probabilistic models for deep learning - 1
Chapter 16 structured probabilistic models for deep learning - 1Chapter 16 structured probabilistic models for deep learning - 1
Chapter 16 structured probabilistic models for deep learning - 1
 
Learning how to explain neural networks: PatternNet and PatternAttribution
Learning how to explain neural networks: PatternNet and PatternAttributionLearning how to explain neural networks: PatternNet and PatternAttribution
Learning how to explain neural networks: PatternNet and PatternAttribution
 
이정근_project_로봇비전시스템.pdf
이정근_project_로봇비전시스템.pdf이정근_project_로봇비전시스템.pdf
이정근_project_로봇비전시스템.pdf
 
R_datamining
R_dataminingR_datamining
R_datamining
 
07. PCA
07. PCA07. PCA
07. PCA
 
Visualizing data using t-SNE
Visualizing data using t-SNEVisualizing data using t-SNE
Visualizing data using t-SNE
 
7. Linear Regression
7. Linear Regression7. Linear Regression
7. Linear Regression
 
[Swift] Data Structure - Graph
[Swift] Data Structure - Graph[Swift] Data Structure - Graph
[Swift] Data Structure - Graph
 
Tda jisu kim
Tda jisu kimTda jisu kim
Tda jisu kim
 
Support Vector Machine Tutorial 한국어
Support Vector Machine Tutorial 한국어Support Vector Machine Tutorial 한국어
Support Vector Machine Tutorial 한국어
 
이산수학02
이산수학02이산수학02
이산수학02
 
RUCK 2017 빅데이터 분석에서 모형의 역할
RUCK 2017 빅데이터 분석에서 모형의 역할RUCK 2017 빅데이터 분석에서 모형의 역할
RUCK 2017 빅데이터 분석에서 모형의 역할
 
Lecture 4: Neural Networks I
Lecture 4: Neural Networks ILecture 4: Neural Networks I
Lecture 4: Neural Networks I
 
점, 선, 면
점, 선, 면점, 선, 면
점, 선, 면
 
DM_02
DM_02DM_02
DM_02
 
8. Logistic Regression
8. Logistic Regression8. Logistic Regression
8. Logistic Regression
 
Growth hackers 0905 network analysis
Growth hackers 0905 network analysisGrowth hackers 0905 network analysis
Growth hackers 0905 network analysis
 

More from Kyunghoon Kim

넥스트 노멀 - 인간과 AI의 협업
넥스트 노멀 - 인간과 AI의 협업넥스트 노멀 - 인간과 AI의 협업
넥스트 노멀 - 인간과 AI의 협업
Kyunghoon Kim
 
토론하는 AI 김컴재와 AI 조향사 센트리아
토론하는 AI 김컴재와 AI 조향사 센트리아토론하는 AI 김컴재와 AI 조향사 센트리아
토론하는 AI 김컴재와 AI 조향사 센트리아
Kyunghoon Kim
 
빅데이터의 다음 단계는 예측 분석이다
빅데이터의 다음 단계는 예측 분석이다빅데이터의 다음 단계는 예측 분석이다
빅데이터의 다음 단계는 예측 분석이다
Kyunghoon Kim
 
기계가 선형대수학을 통해 한국어를 이해하는 방법
기계가 선형대수학을 통해 한국어를 이해하는 방법기계가 선형대수학을 통해 한국어를 이해하는 방법
기계가 선형대수학을 통해 한국어를 이해하는 방법
Kyunghoon Kim
 

More from Kyunghoon Kim (20)

넥스트 노멀 - 인간과 AI의 협업
넥스트 노멀 - 인간과 AI의 협업넥스트 노멀 - 인간과 AI의 협업
넥스트 노멀 - 인간과 AI의 협업
 
토론하는 AI 김컴재와 AI 조향사 센트리아
토론하는 AI 김컴재와 AI 조향사 센트리아토론하는 AI 김컴재와 AI 조향사 센트리아
토론하는 AI 김컴재와 AI 조향사 센트리아
 
빅데이터의 다음 단계는 예측 분석이다
빅데이터의 다음 단계는 예측 분석이다빅데이터의 다음 단계는 예측 분석이다
빅데이터의 다음 단계는 예측 분석이다
 
중학생을 위한 4차 산업혁명 시대의 인공지능 이야기
중학생을 위한 4차 산업혁명 시대의 인공지능 이야기중학생을 위한 4차 산업혁명 시대의 인공지능 이야기
중학생을 위한 4차 산업혁명 시대의 인공지능 이야기
 
업무 자동화
업무 자동화업무 자동화
업무 자동화
 
4차 산업혁명 시대의 진로와 진학
4차 산업혁명 시대의 진로와 진학4차 산업혁명 시대의 진로와 진학
4차 산업혁명 시대의 진로와 진학
 
20200620 신호와 소음 독서토론
20200620 신호와 소음 독서토론20200620 신호와 소음 독서토론
20200620 신호와 소음 독서토론
 
중학생을 위한 인공지능 이야기
중학생을 위한 인공지능 이야기중학생을 위한 인공지능 이야기
중학생을 위한 인공지능 이야기
 
슬쩍 해보는 선형대수학
슬쩍 해보는 선형대수학슬쩍 해보는 선형대수학
슬쩍 해보는 선형대수학
 
파이썬으로 해보는 이미지 처리
파이썬으로 해보는 이미지 처리파이썬으로 해보는 이미지 처리
파이썬으로 해보는 이미지 처리
 
기계가 선형대수학을 통해 한국어를 이해하는 방법
기계가 선형대수학을 통해 한국어를 이해하는 방법기계가 선형대수학을 통해 한국어를 이해하는 방법
기계가 선형대수학을 통해 한국어를 이해하는 방법
 
공공데이터 활용사례
공공데이터 활용사례공공데이터 활용사례
공공데이터 활용사례
 
기계학습, 딥러닝, 인공지능 사이의 차이점 이해하기
기계학습, 딥러닝, 인공지능 사이의 차이점 이해하기기계학습, 딥러닝, 인공지능 사이의 차이점 이해하기
기계학습, 딥러닝, 인공지능 사이의 차이점 이해하기
 
Korean Text mining
Korean Text miningKorean Text mining
Korean Text mining
 
2018 인공지능에 대하여
2018 인공지능에 대하여2018 인공지능에 대하여
2018 인공지능에 대하여
 
Naive bayes Classification using Python3
Naive bayes Classification using Python3Naive bayes Classification using Python3
Naive bayes Classification using Python3
 
Basic statistics using Python3
Basic statistics using Python3Basic statistics using Python3
Basic statistics using Python3
 
[20160813, PyCon2016APAC] 뉴스를 재미있게 만드는 방법; 뉴스잼
[20160813, PyCon2016APAC] 뉴스를 재미있게 만드는 방법; 뉴스잼[20160813, PyCon2016APAC] 뉴스를 재미있게 만드는 방법; 뉴스잼
[20160813, PyCon2016APAC] 뉴스를 재미있게 만드는 방법; 뉴스잼
 
NMF with python
NMF with pythonNMF with python
NMF with python
 
IPython
IPythonIPython
IPython
 

사회 연결망의 링크 예측

  • 1. 사회 연결망의 링크 예측 Kyunghoon Kim kyunghoon@unist.ac.kr Bongsoo Jang bsjang@unist.ac.kr November 13, 2015 Research Performed: ∼ November 13, 2015 Supporter: Changyong Lee 1 목적 사회 연결망의 링크를 예측하는 많은 방법들이 존재한다. 그 방법들에 대하여 정리하여 논하고, 실제 어떻게 시뮬레이션을 할 수 있는지 시도한다. 1.1 정의 사회 연결망 Social networks 소셜 네트워크(Social networks)는 한국어로 사회 망 또는 사회 연결망이라고 불린다. 사회 연결망이란 도로망, 철도망, 통신 망과 같이 인간이 모여 살기 때문에 생겨나는 사회적 하부구조를 포괄적으로 의미하기 때문에 그 의미가 폭 넓다고 할 수 있다. 사회 연결망은 행위자와 행위자들 사이의 관계로 구성되는 사회적 구조이며, 이러한 사회 연결망은 행위자를 점으로 하고 관계를 선으로 한 그래프로 표현될 수 있다. 사회 연결망 분석 Social network analysis 사회 연결망 분석은 연결망 안의 행 위자들의 관계를 수치화, 통계화, 그래프화하여 관계에 대한 해석을 가능하도 록 한다. 1980년대까지 사회 연결망 분석은 사회과학에서 확립된 분야였다. 1990년대에 연결망 분석은 더 많은 분야로 확산되었는데, 물리학과 생물학도 포함된다. 응용분야로는 경영상담, 공공보건, 범죄/전쟁 방지가 있다. 경영상 담에서 연결망 분석은 종종 지식경영의 맥락에 적용되는데, 목적은 조직들이 그 구성원들 사이에 분포한 정보와 능력들을 더 잘 뽑아낼 수 있게 도와주는 것이다. 공공보건에서 연결망접근은 전염병 확산을 막고 건강관리와 사회적 지지를 제공하는데 중요했다. 모든 응용분야 중 국가안보는 아마도 사회연결망분석을 가장 많이 끌어안은 영역일 것이다. 범죄, 그 중에서도 조직범죄에 맞선 사람들은 오랫동안 연결 망관점을 이용했다. 그들은 “관심 인물”들 사이의 링크로 이루어진 연결망을 벽을 덮을 만큼 큰 지도로 만들어 붙였다. 이 연결망접근은 사담 후세인을 잡는데 기여했다고 한다. 덧붙여, 테러그룹들은 조직보다는 연결망으로 널리 알려져 있으며 기능적인 연결망을 혼란시키는 연구에 불을 붙였다. 동시에 1
  • 2. 연결망에 맞서기 위해 연결망이 필요하다고 주장되기도 하는데, 이는 분산된 단위를 이용한 군사 실험으로 이어진다.(Borgatti et al., 2009) 링크 예측 소셜 네트워크에서의 링크 예측은 현재 주어진 네트워크에서 빠진 링크를 예측하거나, 미래의 네트워크에서 새롭게 나타나거나 사라질 링크를 예측하는 것을 의미한다. 이것은 소셜 네트워크의 진화를 분석하는 데 중요하다. 특정한 시간 t에서 다음과 같은 사회망을 정의하자. G(V, E) (1) 여기서 V 는 노드들의 집합, E 는 링크들의 집합이다. 링크 예측은 1. 미래 시간 t′ (t′ > t)에서 노드들 사이에 나타날 링크나 지워질 링크 2. 현재 시간 t에 빠진 링크 또는 관찰되지 않은 링크 를 예측하는 것을 목표로 한다. 이 링크 예측 문제를 해결하기 위한 방법들을 하나의 프레임워크로 정리한 것은 Figure 1.1과 같다.(Wang et al., 2015) Figure 1: 일반적인 링크 예측 프레임워크 2 링크 예측 기법 링크 예측을 위한 방법에는 크게 노드의 정보를 사용하는 방법, 위상적 구조를 사용하는 방법 그리고 사회과학 이론을 사용하는 방법 등 기본적인 링크 예측 방법과 약간 복잡하지만 학습 기반의 링크 예측 방법 등이 존재한다. 여기서 그 방법들을 한 번 살펴보자. 본 절에서 사용하는 파이썬 코드는 다음 라이브러리들을 가정하고 있다. 1 %pylab inline 2 import numpy as np 3 import pandas as pd 4 import networkx as nx 5 import networkx_addon # it's not a public library 2
  • 3. networkx_addon은 https://github.com/hhchen1105/networkx_addon.git 에서 다운받을 수 있다. git clone https://github.com/hhchen1105/networkx_addon.git cd networkx_addon python setup.py install 2.1 노드 기반 링크 예측 링크 예측에 있어 노드 쌍의 유사도를 계산하는 것은 가장 직관적인 해결책일 것이다. 노드 쌍의 유사도가 높을 수록 링크가 있을 가능성(likelihood)이 높다는 아이디어이다. 여기서 유사도를 계산하기 위해 노드가 가진 특성을 이용하는 것이 노드 기반 링크 예측이다. 예를 들어, 노드를 사람이라고 했을 때, 사람이 가진 종교, 취미, 위치 등을 특성(attributes)으로 하여 그 특성의 유사도를 계산하는 것이다. 이것은 링크를 가지지 않은 비슷한 특성을 가진 사람들은 서로 링크될 가능성이 높다는 것을 가정으로 한다. 실제로 사회 연결망 서비스(Social network service)의 하나인 페이스북에서는 유저의 프로필을 참고하여 유저들의 유사성을 계산해 친구일 가능성이 높은 유저를 추천해 줄 수 있다. 다른 예로, 위키페디아 페이지를 수정하는 사용자 행동를 특징으로 하여 그 행동의 유사성을 이용해 링크를 예측하는 연구가 있다. (Anderson et al., 2012) 결론적으로, 노드 기반 링크 예측은 노드의 특성(attributes)이나 행동(action)을 사용하여 노드 쌍의 유사성을 계산한다. 지금까지 유사성을 계산하기 위해 많은 방법들이 제안되어 왔으며(Jones and Furnas, 1987), 유사성을 계산하기 위한 방법 으로는 유클리디안 거리(Euclidean distance)와 코사인 유사도(Cosine similarity) 가 많이 사용된다. 유저의 특성을 벡터 형태로 표현하는 것을 벡터 공간 모델 (Vector space model, VSM)이라고 하며, 임의의 두 벡터 사이의 거리를 계산하는 것이 유클리디안 거리이고, 각도를 계산하는 것이 코사인 유사도이다. 계산을 위해 다음을 가정하자. 두 개의 벡터 x, y가 각각 n개의 원소를 갖는다고 하자. x =< x1, x2, · · · , xn > (2) y =< y1, y2, · · · , yn > (3) Definition 2.1 (유클리디안 거리) d(x, y) = d(y, x) = √ (y1 − x1)2 + (y2 − x2)2 + · · · + (yn − xn)2 = n∑ i=1 (yi − xi)2 (4) 3
  • 4. Definition 2.2 (코사인 유사도) x와 y 사이의 각도 θ 의 코사인은 다음과 같이 계산된다. cos(x, y) = ∑n i=1 xi · yi √∑n i=1 x2 i · ∑n i=1 y2 i = x · y √ x · x · √ y · y = x ∥x∥ · y ∥y∥ (5) 벡터 공간 모델에 대한 수학적인 해석은 SIAM의 Berry et al. (1999), 매력적인 성질과 그 응용은 AAAI의 Turney et al. (2010)을 참고하면 된다. Example 2.1 철수는 울산과기원을 다니고 독서를 취미로 하며 울산에 있다. 영 희는 울산과기원을 다니고 음악감상을 취미로 하며 울산에 있다. 철수와 영희의 벡터 공간 모델에서의 유사도를 구해보자. 철수 영희 교육 울산과기원 울산과기원 취미 독서 음악감상 위치 울산 울산 ⇒ 철수 영희 울산과기원 1 1 독서 1 0 음악감상 0 1 울산 1 1 Table 1: 벡터 공간 모델의 예 벡터 공간 모델에 의해 만들어진 두 벡터 ⃗V철수 =     1 1 0 1    , ⃗V영희 =     1 0 1 1    에 대해, 유클리디안 거리는 다음과 같이 계산할 수 있다.. 1 def euclidean(x,y): 2 return np.sqrt(np.sum((x-y)**2)) 3 4 a = np.array([1,1,0,1]) 5 b = np.array([1,0,1,1]) 6 dist = euclidean(a, b) 코사인 유사도의 경우 scikit-learn 라이브러리를 쓰면 쉽게 계산할 수 있다. 1 from sklearn.metrics.pairwise import cosine_similarity 2 sim = cosine_similarity(a, b) 3 print sim 이 때의 결과 값은 1 array([[ 0.66666667]]) 과 같이 나오는데, 값만 가져오기 위해서는 sim[0][0] 또는 sim[0,0]과 같이 배열에 직접 접근하여 얻어낸다. scikit-learn을 사용하지 않고 직접 계산하는 방법은 다음과 같이 한다. 4
  • 5. 1 import math 2 def cosine_similarity(v1,v2): 3 sumxx, sumxy, sumyy = 0, 0, 0 4 for i in range(len(v1)): 5 x = v1[i]; y = v2[i] 6 sumxx += x*x 7 sumyy += y*y 8 sumxy += x*y 9 return sumxy/math.sqrt(sumxx*sumyy) 10 11 sim = cosine_similarity(a, b) 2.2 위상 기반 링크 예측 노드나 링크에 특성(attributes)이 없더라도 위상적 정보(topological information) 를 기반으로 두 노드의 유사도를 계산할 수 있는 많은 방법들이 존재한다. Liben- Nowell and Kleinberg (2007) 논문 이후로 그래프의 구조적 특징을 기반으로 한 여러 가지 측정법 (metric) 들이 논의되었고, 이후에는 위상 기반의 측정법들이 제안되었다. 이 측정법들은 크게 세 가지 분류로 나누어 볼 수 있는데, 그 각각을 살펴보도록 하자. 먼저 기본적인 표기법은 다음과 같다. • 소문자 = 노드 • 대문자 = 인접행렬 • Γ(x) = 노드 x의 이웃들의 집합 • |Γ(x)| = 노드 x의 이웃들의 개수 2.2.1 이웃 기반 링크 예측 이웃을 기반으로 한 링크 예측은 Table 2에서 그 특징들을 살펴볼 수 있다. Definition 2.3 공통 이웃 Common Neighbors (CN) CN은 간단한 형태 때문에 링크 예측 문제에서 가장 많이 쓰여지는 측정법 중 하 나이다.(Newman, 2001) 이 방법은 두 개의 노드 x, y 가 공통적으로 가지고 있는 이웃의 개수를 센다. CN(x, y) = |Γ(x) ∩ Γ(y)| (6) 1 >>> G = nx.complete_graph(5) 2 >>> sorted(nx.common_neighbors(G, 0, 1)) 3 [2, 3, 4] 함수의 파이썬 코드는 다음과 같다. 1 def common_neighbors(G, u, v): 2 if u not in G: 3 raise nx.NetworkXError('u is not in the graph.') 5
  • 6. Table 2: 이웃 기반 링크 예측 비교표 측정법 정규화 시간 복잡도 특징 CN No O(n2 ) 간단하고 직관적 JC Yes O(2n2 ) 이웃의 전체 개수와 공통 이웃의 비율 SI Yes O(n2 ) 노드의 Degree가 낮을 수록 링크를 가질 가능성이 크다 SC Yes O(n2 ) 코사인 유사도 사용 HP Yes O(n2 ) 링크를 가질 가능성은 낮은 Degree 일수록 높다 HD Yes O(n2 ) 링크를 가질 가능성은 높은 Degree 일수록 높다 LHN Yes O(n2 ) 많은 공통 이웃을 가질수록 링크 가능성이 높다 PD Yes O(n2 ) 대중적인 노드인지 예측의 정확도를 향상시킨다 AA No O(2n2 ) 적은 이웃을 가지는 공통 이웃들은 가중치가 높다 PA No O(2n) 높은 도수를 갖는 노드와의 링크 가능성이 높다 RA No O(2n2 ) AA와 비슷하나, 높은 공통 이웃을 가진 것을 억압한다 4 if v not in G: 5 raise nx.NetworkXError('v is not in the graph.') 6 7 return (w for w in G[u] if w in G[v] and w not in (u, v)) Definition 2.4 자카드 계수 Jaccard Coefficient (JC) JC는 CN의 정규화된 값이다. JC(x, y) = |Γ(x) ∩ Γ(y)| |Γ(x) ∪ Γ(y)| (7) jaccard_coefficient(G, ebunch=None) 여기서 ebunch는 선택된 노드쌍만 계산되도록 하는 변수이다. (default = None) 1 for u in G.nodes_iter(): 2 candidates = [(u, v) for v in nx.non_neighbors(G, u)] 3 preds = nx.jaccard_coefficient(G, candidates) 4 for source, target, value in preds: 5 index_data[source][target]['j'] = value 위 함수의 파이썬 코드는 다음과 같으며, 다른 측정법 역시 유사하게 함수를 작성할 수 있다. 1 def _apply_prediction(G, func, ebunch=None): 2 """Applies the given function to each edge in the 3 specified iterable of edges. 4 5 ``G`` is an instance of :class:`networkx.Graph `. 6 7 ``func`` is a function on two inputs , each of which is a 8 node in the graph. The function can return anything , but 6
  • 7. 9 it should return a value representing a prediction of the 10 likelihood of a "link" joining the two nodes. 11 12 ``ebunch `` is an iterable of pairs of nodes. If not 13 specified , all non-edges in the graph ``G`` will be used. 14 """ 15 if ebunch is None: 16 ebunch = nx.non_edges(G) 17 return ((u, v, func(u, v)) for u, v in ebunch) 18 19 def jaccard_coefficient(G, ebunch=None): 20 def predict(u, v): 21 union_size = len(set(G[u]) | set(G[v])) 22 if union_size == 0: 23 return 0 24 return len(list(nx.common_neighbors(G, u, v))) / union_size 25 return _apply_prediction(G, predict , ebunch) Definition 2.5 소렌슨 인덱스 Sørensen Index (SI) 공통 이웃의 개수를 고려함과 동시에, 낮은 도수의 노드는 링크가 생길 가능성이 높음을 나타냈다. SI(x, y) = |Γ(x) ∩ Γ(y)| |Γ(x)| + |Γ(y)| (8) Definition 2.6 살톤 코사인 유사도 Salton Cosine Similarity (SC) SC는 노드 x와 y 사이의 유사도를 계산하기 위해서 일반적인 코사인 방법을 적용 했다. SC(x, y) = |Γ(x) ∩ Γ(y)| √ |Γ(x)| · |Γ(y)| (9) Definition 2.7 Hub Promoted (HP) HP는 노드 x와 y 의 위상적인 겹침을 정의했다(Ravasz et al., 2002). HP의 값은 도수가 낮은 노드에 의해 결정된다. HP(x, y) = |Γ(x) ∩ Γ(y)| min(|Γ(x)|, |Γ(y)|) (10) Definition 2.8 Hub Depressed (HD) Zhou et al. (2009)는 HP와 유사하지만 HD의 값이 도수가 높은 노드에 의해 결정 되도록 정의했다. HD(x, y) = |Γ(x) ∩ Γ(y)| max(|Γ(x)|, |Γ(y)|) (11) Definition 2.9 Leicht-Holme-Newman (LHN) LHN은 JC보다 높은 도수를 갖는 노드에 패널티를 주는(punish) 방법이다. (Leicht et al., 2006) LHN(x, y) = |Γ(x) ∩ Γ(y)| |Γ(x)| · |Γ(y)| (12) 7
  • 8. LHN은 networkx_addon을 사용해서 쉽게 계산할 수 있다. networkx_addon의 설치는 2절을 참고하자. 1 G=nx.Graph() 2 G.add_edges_from([(0,7), (0,1), (0,2), (0,3), (1,4), (2,4)]) 3 networkx_addon.similarity.lhn(G) 함수의 파이썬 코드는 다음과 같다. 1 def lhn(G, c=0.9, remove_neighbors=False, inv_method=0): 2 if type(G) == nx.MultiGraph or type(G) == nx.MultiDiGraph: 3 raise Exception("lhn() not defined for graphs with multiedges.") 4 5 if G.is_directed(): 6 raise Exception("lhn() not defined for directed graphs.") 7 8 A = nx.adjacency_matrix(G, nodelist=G.nodes(), weight=None) 9 w, v = numpy.linalg.eigh(A) 10 lambda1 = max([abs(x) for x in w]) 11 I = numpy.eye(A.shape[0]) 12 S = None 13 if inv_method == 1: 14 S = scipy.linalg.pinv(I - c/lambda1 * A) 15 elif inv_method == 2: 16 S = numpy.linalg.inv(I - c/lambda1 * A) 17 else: 18 S = numpy.linalg.pinv(I - c/lambda1 * A) 19 deg = numpy.array(sum(A)).reshape(-1,) 20 for i in range(S.shape[0]): 21 for j in range(S.shape[1]): 22 S[i,j] /= (deg[i]*deg[j]) 23 return S, G.nodes() Definition 2.10 Parameter-Dependent (PD) 대중적(popular)인지 아닌지를 예측하는 정확도를 높이기 위해서 Zhu et al. (2012) 이 제안한 방법이다. 여기서 λ는 free parameter이다. λ = 0일 때는 CN, λ = 0.5 일 때는 SC, λ = 1일 때는 LHN이다. PD(x, y) = |Γ(x) ∩ Γ(y)| (|Γ(x)| · |Γ(y)|)λ (13) Definition 2.11 아다믹-아다르 계수 Adamic-Adar Coefficient (AA) 처음에는 Adamic과 Adar가 두 웹 페이지의 유사성을 계산하기 위해서 제안한 공식이다. 적은 이웃을 갖는 공통 이웃의 비중을 높여주었다. AA(x, y) = ∑ z∈Γ(x)∩Γ(y) 1 log |Γ(z)| (14) adamic_adar_index(G, ebunch=None) 8
  • 9. 1 for u in G.nodes_iter(): 2 candidates = [(u, v) for v in nx.non_neighbors(G, u)] 3 preds = nx.adamic_adar_index(G, candidates) 4 for source, target, value in preds: 5 index_data[source][target]['a'] = value 함수의 파이썬 코드는 다음과 같다. 1 def adamic_adar_index(G, ebunch=None): 2 def predict(u, v): 3 return sum(1 / log(G.degree(w)) for w in nx.common_neighbors(G, u, v)) 4 return _apply_prediction(G, predict , ebunch) Definition 2.12 선호적 연결 Preferential Attachment (PA) 낮은 도수를 갖는 노드보다 높은 도수를 갖는 노드에 연결될 가능성이 높음을 표현 한다. PA(x, y) = |Γ(x)| · |Γ(y)| (15) preferential_attachment(G, ebunch=None) 1 for u in G.nodes_iter(): 2 candidates = [(u, v) for v in nx.non_neighbors(G, u)] 3 preds = nx.preferential_attachment(G, candidates) 4 for source, target, value in preds: 5 index_data[source][target]['p'] = value 함수의 파이썬 코드는 다음과 같다. 1 def preferential_attachment(G, ebunch=None): 2 def predict(u, v): 3 return G.degree(u) * G.degree(v) 4 return _apply_prediction(G, predict , ebunch) 예를 들어, 다음과 같은 그래프를 가정하자. (Figure 2) 1 G = nx.Graph() 2 G.add_edges_from([('A','B'), ('A','C'), ('A','D'), ('A','E') 3 , ('A','F'), ('F','E')]) 4 pos = nx.circular_layout(G) 5 nx.draw(G, with_labels=True, pos=pos) 링크가 없는 노드 쌍마다 PA를 계산한 후, 그 값이 3 이상이면 빨간색 선(링크 예측 선)으로 보이도록 하자. (threshold> 3) 1 plt.figure(figsize=(15, 5)) 2 threshold = 3 3 pos = nx.circular_layout(G) 4 nx.draw_networkx_nodes(G, pos, node_size=500, node_color='yellow') 5 nx.draw_networkx_edges(G, pos, alpha=0.2) 6 nx.draw_networkx_labels(G, pos, font_size=20); 9
  • 10. Figure 2: 주어진 그래프 7 8 selected_lines = [] 9 for u in G.nodes_iter(): 10 preds = nx.preferential_attachment(G, [(u, v) for v in nx.non_neighbors(G, u)]) 11 largest = heapq.nlargest(5, preds, key = lambda x: x[2]) 12 for l in largest: 13 selected_lines.append(l) 14 15 subG = nx.Graph() 16 for line in selected_lines: 17 print line[0], line[1], line[2] 18 if line[2]>threshold: 19 subG.add_edge(line[0], line[1]) 20 21 pos_subG = dict() 22 for s in subG.nodes(): 23 pos_subG[s] = pos[s] 24 25 nx.draw_networkx_edges(subG, pos_subG , edge_color='red'); 26 plt.axis('off'); 위 코드의 실행 결과는 다음과 같이 나타난다. 1 C E 4 2 C F 4 3 C D 2 4 B E 4 5 B F 4 6 B D 2 7 E C 4 8 E B 4 9 E D 2 10 D C 2 11 D B 2 12 D E 2 13 D F 2 14 F C 4 10
  • 11. 15 F B 4 16 F D 2 Figure 3: PA 링크예측(빨간색 선) PA의 특징이 좀 더 잘 나타날 수 있도록 그래프의 노드 크기를 조절하자. 1 degree = nx.degree_centrality(G) 2 pos = nx.circular_layout(G) 3 nx.draw_networkx_nodes(G, pos, node_color='yellow', 4 nodelist=degree.keys(), 5 node_size=np.array(degree.values())*10000) 6 nx.draw_networkx_edges(G, pos, alpha=0.2) 7 nx.draw_networkx_labels(G, pos, font_size=20); Figure 4: PA 링크예측(빨간색 선)과 노드 크기 조절 Definition 2.13 리소스 할당 Resource Allocation (RA) Zhou et al. (2009)이 제안한 방법은 자원 할당의 물리적인 프로세스에서 영감을 받았다. 높은 공통 이웃을 가지는 비중을 줄인다는 점에서, RA는 AA와 비슷한 형태이다. 하지만 RA는 AA보다 더 강하게 높은 공통 이웃을 가지는 노드를 억압 한다. 따라서 평균 도수(average degree)가 작은 네트워크에서는 RA, AA 둘 다 비슷한 링크 예측 결과를 보이지만, 높은 평균 도수를 갖는 네트워크에서는 RA가 더 나은 결과를 보여준다. RA(x, y) = ∑ z∈Γ(x)∩Γ(y) 1 |Γ(z)| (16) 11
  • 12. resource_allocation_index(G, ebunch=None) 1 for u in G.nodes_iter(): 2 candidates = [(u, v) for v in nx.non_neighbors(G, u)] 3 preds = nx.resource_allocation_index(G, candidates) 4 for source, target, value in preds: 5 index_data[source][target]['r'] = value 함수의 파이썬 코드는 다음과 같다. 1 def resource_allocation_index(G, ebunch=None): 2 def predict(u, v): 3 return sum(1 / G.degree(w) for w in nx.common_neighbors(G, u, v)) 4 return _apply_prediction(G, predict , ebunch) 2.2.2 경로 기반 링크 예측 Definition 2.14 국소 경로 Local Path (LP) LP는 말 그대로 국소적인 부분에 대해서 계산하는 방법이다. Lü et al. (2009) 에 따르면 CN, Katz에 비해 우수하다고 평가한다. 이웃들의 정보만을 사용하는 방법과는 달리, 경로 길이가 2 또는 3인 노드까지를 포함하여 정보를 사용한다는 것이 특징이다. 명백하게도, 경로 길이가 2인 것은 3인 것보다 더 관련이 있을 것이므로, 경로길이 3인 경우는 매개변수 α를 주어 그 비중을 낮춘다. 여기서 α는 0에 가까운 값이다. LP = A2 + αA3 (17) 행렬의 곱은 다음과 같이 표현할 수 있다. 1 A = np.matrix('1 2; 3 4') 2 A = np.matrix([[1, 2], [3, 4]]) 3 A_2 = A*A 4 A_3 = A_2*A Networkx의 그래프 구조를 행렬로 바꾸어, 그 행렬을 제곱하기 위해서는 다음과 같이 사용한다. 1 G = nx.path_graph(5) 2 A = nx.to_numpy_matrix(G) 3 A_2 = A**2 4 A_3 = A**3 Definition 2.15 Katz Katz metric은 상당히 오래 전에 나온 개념으로 Katz (1953)가 제안한 방식이다. Katz는 모든 경로의 닮음을 기반으로 하며, 두 노드 사이의 모든 경로를 센다. 경로의 길이가 짧을수록 더 많은 비중을 주기 위해 감쇠비(damping factor)로 β 를 사용한다. 만약 β 가 매우 작다면, Katz의 결과는 CN과 매우 유사할 것이다. Katz(x, y) = ∞∑ l=1 βl · |pathl x,y| = βA + β2 A2 + β3 A3 + · · · . = (I − βA)−1 − I (18) 12
  • 13. networkx에서 쓰이는 파라미터와 공식은 다음과 같다. katz_centrality(G, alpha=0.1, beta=1.0, max_iter=1000, tol=1e-06, nstart=None, normalized=True, weight='weight') xi = α ∑ j Aijxj + β (19) 1 >>> G = nx.path_graph(5) 2 >>> centrality = nx.katz_centrality(G) 3 >>> for n,c in sorted(centrality.items()): 4 ... print("%d %0.2f"%(n,c)) Definition 2.16 Relation Strength Similarity (RSS) Chen et al. (2012)가 제안한 RSS는 가중치 사회 연결망을 위한 비대칭 측정법이다. 이것의 계산은 연결 강도 R(x, y)를 기반으로 하는데, 이웃 노드들 사이의 상대적인 유사정도로 정규화된 가중치 점수로 계산된다. 다음과 같이 가정하자. 노드 x에서 y 로 가는 r 보다 짧은 L개의 단순 경로 p1, p2, · · · , pL 가 있다고 하자. 그리고 경로 pl 은 K 개의 노드 z1, z2, · · · , zk−1, zk 로 구성된다고 하자. 그러면 RSS는 다음과 같이 정의된다. RSS(x, y) = L∑ l=1 R∗ pl (x, y) (20) R∗ pl (x, y) = { ΠK k=1R(zk, zk+1), K ≤ r 0, otherwise (21) L을 2로 두었을 때 networkx_addon을 이용해 다음과 같이 계산할 수 있다. 1 G=nx.Graph() 2 G.add_edges_from([(0,1), (0,2), (1,3), (2,3)], weight=1) 3 networkx_addon.similarity.rss2(G) 함수의 파이썬 코드는 다음과 같다. 1 def rss2(G, remove_neighbors=False, dump_process=False, 2 disregard_weight=False): 3 if type(G) == nx.MultiGraph or type(G) == nx.MultiDiGraph: 4 raise Exception("rss2() not defined for graphs with 5 multiedges.") 6 7 if G.is_directed(): 8 raise Exception("rss2() not defined for directed graphs.") 9 10 weighted_deg = G.degree(weight='weight') 11 rss2 = { } 12 cur_iter = 0 13
  • 14. 13 total_iter = G.number_of_nodes() 14 for a in G.nodes(): 15 if dump_process: 16 cur_iter += 1 17 print cur_iter , '/', total_iter 18 for b in G.neighbors(a): 19 for c in G.neighbors(b): 20 if a == c: 21 continue 22 if remove_neighbors and c in G.neighbors(a): 23 continue 24 if disregard_weight: 25 t1 = float(1) 26 t2 = float(1) 27 s1 = len(set(G.neighbors(a))) 28 s2 = len(set(G.neighbors(b))) 29 else: 30 t1 = float(G[a][b]['weight']) 31 t2 = float(G[b][c]['weight']) 32 s1 = weighted_deg[a] 33 s2 = weighted_deg[b] 34 if a not in rss2: 35 rss2[a] = { } 36 if c not in rss2[a]: 37 rss2[a][c] = t1/s1 * t2/s2 38 else: 39 rss2[a][c] += t1/s1 * t2/ s2 40 return rss2 Definition 2.17 FriendLink (FL) Papadimitriou et al. (2012)가 제안한 FL은 노드 x와 y 사이의 정해진 길이 l 안에 서 지나가는 모든 경로에 의한 유사도이다. FL(x, y) = l∑ i=1 1 i − 1 · |pathsi x,y| Πi j=2(n − j) (22) 2.2.3 무작위 걷기 기반 링크 예측 사회망에서 노드들 사이의 사회적 상호작용은 무작위 걷기(random walk)로 모델 링될 수 있다. 이 예측 방법들은 노드에서 이웃 노드로 가는 전이 확률(transition probabilities)를 이용한다. Definition 2.18 Hitting Time (HT) 노드 x에서 y 로 랜덤 워크로 이동할 때 필요한 기대값(expected number of steps) 이다. (Fouss et al., 2007) A의 대각 행렬(diagonal matrix) DA 가 값 (DA)i,i = ∑ j Ai,j 를 가지고, Pi,j 가 14
  • 15. 노드 i에서 j 로 가는 이동(stepping) 확률이라면, P = D−1 A A라 하자. HT(x, y) = 1 + ∑ ω∈Γ(x) Px,ωHT(ω, y) (23) Definition 2.19 Commute Time (CT) HT는 대칭이 아니기 때문에, CT는 x 에서 y 로, y 에서 x 로 가는 두 가지 기대값을 모두 쓰고자 한다. L = DA − A 의 의사역행렬(pseudo inverse matrix)을 L† 라 하고, m은 사회 연결망의 링크의 개수를 세는 함수라 하자. CT(x, y) = HT(x, y) + HT(y, x) = m(L† x,x + L† y,y − 2L† x,y) (24) Definition 2.20 Cosine Similarity Time (CST) CST는 의사역행렬 L† 를 이용하여 계산한다. CST(x, y) = L† x,y √ L† x,xL† y,y (25) Definition 2.21 SimRank 두 개의 노드가 유사한 노드에 연결되어있는 경우, 두 노드들은 유사하다고 가정 하자. (Jeh and Widom, 2002) 파라미터 γ 는 원래 노드에서 부터 먼 정도에 따라 연결된 노드의 가중치를 얼마나 빠르게 감소시킬지를 결정한다. simRank(x, y) = { 1, x = y γ · ∑ a∈Γ(x) ∑ b∈Γ(y) simRank(a,b) |Γ(x)|·|Γ(y)| , otherwise (26) 이 방법은 무작위 서퍼쌍 모델(random surfer-pairs model)로 설명할 수 있는데, 독립적으로 출발한 두 개의 랜덤 서퍼가 같은 노드에서 만날 기대값을 구하는 것이다. 계산 복잡도는 O(n4 )로 큰 규모의 네트워크에는 적합하지 않다(high computation cost). SimRank는 많이 알려진 방법으로, 많은 코드들이 공개되어 있다. 여기서는 networkx_addon을 사용하자. 1 G = nx.Graph() 2 G.add_edges_from([('a','b'), ('b','c'), ('a','c'), ('c','d')]) 3 s = networkx_addon.similarity.simrank(G) 함수의 파이썬 코드는 다음과 같다. 1 def simrank(G, c=0.9, max_iter=100, remove_neighbors=False, 2 remove_self=False, dump_process=False): 3 if type(G) == nx.MultiGraph or type(G) == nx.MultiDiGraph: 4 raise Exception("simrank() not defined for graphs 5 with multiedges.") 6 7 if G.is_directed(): 8 raise Exception("simrank() not defined for directed 15
  • 16. 9 graphs.") 10 11 sim_old = defaultdict(list) 12 sim = defaultdict(list) 13 for n in G.nodes(): 14 sim[n] = defaultdict(int) 15 sim[n][n] = 1 16 sim_old[n] = defaultdict(int) 17 sim_old[n][n] = 0 18 19 # calculate simrank 20 for iter_ctr in range(max_iter): 21 if _is_converge(sim, sim_old): 22 break 23 sim_old = copy.deepcopy(sim) 24 for i, u in enumerate(G.nodes()): 25 if dump_process: 26 sys.stdout.write("r%d : % d / %d" % 27 (iter_ctr , i, G.number_of_nodes())) 28 for v in G.nodes(): 29 if u == v: 30 continue 31 s_uv = 0.0 32 for n_u in G.neighbors(u): 33 for n_v in G.neighbors(v): 34 s_uv += sim_old[n_u][n_v] 35 sim[u][v] = (c * s_uv / (len(G.neighbors(u))* 36 len(G.neighbors(v)))) 37 if len(G.neighbors(u)) * 38 len(G.neighbors(v)) > 0 else 0 39 if dump_process: 40 print '' 41 42 if remove_self: 43 for m in G.nodes(): 44 G[m][m] = 0 45 46 if remove_neighbors: 47 for m in G.nodes(): 48 for n in G.neighbors(m): 49 sim[m][n] = 0 50 51 return sim 52 53 def _is_converge(s1, s2, eps=1e-4): 54 for i in s1.keys(): 55 for j in s1[i].keys(): 56 if abs(s1[i][j] - s2[i][j]) >= eps: 57 return False 58 return True 16
  • 17. Definition 2.22 Rooted PageRank (RPR) RPR은 하이퍼링크로 구성된 네트워크 검색을 위한 페이지 랭크(PageRank)1 알고 리즘의 수정된 버전이다. 네트워크에서 노드의 순위(rank)는 노드들이 랜덤워크를 통해 도달하게 되는 확률에 비례한다. 여기서 매개변수 ϵ은 출발한 뒤로 얼마나 잘 이웃 노드에 방문하는지를 나타낸다. 대각행렬 D 의 원소를 Di,i = ∑ j Ai,j 라 하면, 다음과 같이 정의할 수 있다. RPR = (1 − ϵ)(I − ϵD−1 A)−1 (27) 일반적인 페이지랭크 알고리즘은 손쉽게 돌려볼 수 있다. 1 >>> G = nx.DiGraph(nx.path_graph(4)) 2 >>> pr = nx.pagerank(G, alpha=0.85) 이 함수의 파이썬 코드2 는 다음과 같다. 이를 변형하여 RPR로 바꿀 수 있다. 또는 라이브러리 Numpy 등을 활용해 행렬 연산을 하도록 하자. 1 def pagerank(G, alpha=0.85, personalization=None, 2 max_iter=100, tol=1.0e-6, nstart=None, weight='weight', 3 dangling=None): 4 if len(G) == 0: 5 return {} 6 7 if not G.is_directed(): 8 D = G.to_directed() 9 else: 10 D = G 11 12 # Create a copy in (right) stochastic form 13 W = nx.stochastic_graph(D, weight=weight) 14 N = W.number_of_nodes() 15 16 # Choose fixed starting vector if not given 17 if nstart is None: 18 x = dict.fromkeys(W, 1.0 / N) 19 else: 20 # Normalized nstart vector 21 s = float(sum(nstart.values())) 22 x = dict((k, v / s) for k, v in nstart.items()) 23 24 if personalization is None: 25 # Assign uniform personalization vector if not given 26 p = dict.fromkeys(W, 1.0 / N) 27 else: 28 missing = set(G) - set(personalization) 29 if missing: 30 raise NetworkXError('Personalization dictionary ' 1x = (I − αAD−1)−11 = D(D − αA)−11 2https://networkx.github.io/documentation/latest/_modules/networkx/algorithms/ link_analysis/pagerank_alg.html 17
  • 18. 31 'must have a value for every node. ' 32 'Missing nodes %s' % missing) 33 s = float(sum(personalization.values())) 34 p = dict((k, v / s) for k, v in personalization.items()) 35 36 if dangling is None: 37 # Use personalization vector if dangling vector not specified 38 dangling_weights = p 39 else: 40 missing = set(G) - set(dangling) 41 if missing: 42 raise NetworkXError('Dangling node dictionary ' 43 'must have a value for every node. ' 44 'Missing nodes %s' % missing) 45 s = float(sum(dangling.values())) 46 dangling_weights = dict((k, v/s) for k, v in dangling.items()) 47 dangling_nodes = [n for n in W if W.out_degree(n, weight=weight) == 0.0] 48 49 # power iteration: make up to max_iter iterations 50 for _ in range(max_iter): 51 xlast = x 52 x = dict.fromkeys(xlast.keys(), 0) 53 danglesum = alpha * sum(xlast[n] for n in dangling_nodes) 54 for n in x: 55 # this matrix multiply looks odd because it is 56 # doing a left multiply x^T=xlast^T*W 57 for nbr in W[n]: 58 x[nbr] += alpha * xlast[n] * W[n][nbr][weight] 59 x[n] += danglesum * dangling_weights[n] + (1.0 - alpha) * p[n] 60 # check convergence , l1 norm 61 err = sum([abs(x[n] - xlast[n]) for n in x]) 62 if err < N*tol: 63 return x 64 raise NetworkXError('pagerank: power iteration failed to converge ' 65 'in %d iterations.' % max_iter) Definition 2.23 PropFlow PropFlow는 RPR과 비슷하지만, 더 국소적으로 계산되는 특징을 가지고 있다. PF(x, y) = PF(a, x) wxy ∑ k∈Γ(x) wxk (28) 2.3 사회과학 이론 기반 링크 예측 최근 많은 연구들은 링크 예측 문제를 해결하기 위해 커뮤니티(community), 삼각 닫힘 (triadic closure), 강한 연결과 약한 연결 (strong and weak ties), 유유상종 (homophily), 구조적 균형(structural balance)과 같은 고전적인 사회과학 이론들 을 이용하고 있다. 노드나 위상 기반의 링크 예측과 달리 추가적인 사회적 상호작용 18
  • 19. 정보를 잡아내기 때문에 성능을 향상시킬 수 있다. 특히, 규모가 큰 네트워크에서 효과적이다. 2.3.1 커뮤니티 발견 Community detection Valverde-Rebaza and de Andrade Lopes (2013)는 규모가 큰 네트워크에서 구조 적 정보만으로 링크 예측에서 좋은 성능을 내기에는 충분하지 않기 때문에, 노드가 그들의 커뮤니티 안에서 갖는 행동이나 관심사 같은 추가적인 정보를 활용하였다. 이들은 트위터 네트워크에서의 미래 시간에 생길 링크 예측을 실험하였다. 트위터는 상호적인 관계를 요구하지 않으면서, 수많은 유저들이 활발하게 정보를 공유하는 서비스이다. 이 트위터 네트워크는 방향성을 가지면서 비대칭이고 규모가 매우 큰 특징을 갖는다. WIC 와 W form measures를 사용하는데(Valverde-Rebaza and de Andrade Lopes, 2012), 이 접근 방법을 사용하기 위해서는 커뮤니티 발견 (community detection)이 선행되어야 한다. 여기서는 시간 복잡도를 줄이기 위해 선형시간에 가까운 Raghavan et al. (2007)의 label propagation algorithm(LPA) 를 사용했다. 커뮤니티 발견을 위해 Newman (2006)과 같은 다른 알고리즘을 썼을 때 그 성능향상을 기대할 수도 있다. 커뮤니티 발견을 위해 Blondel et al. (2008)의 방법(Louvain Community Detec- tion)을 사용해 보자. 코드는 https://bitbucket.org/taynaud/python-louvain 에서 다운받을 수 있다. 다운받은 후 폴더 안에서 다음 명령을 실행하여 라이브러 리를 설치하자. $ python setup.py install 설치된 라이브러리 community를 불러오고, community.best_partition 함수를 이용해 쉽게 계산할 수 있다. 1 import community 2 G = nx.karate_club_graph() 3 plt.figure(figsize=(10, 5)) 4 #first compute the best partition 5 partition = community.best_partition(G) 6 7 #drawing 8 size = float(len(set(partition.values()))) 9 pos = nx.spring_layout(G) 10 count = 0. 11 for com in set(partition.values()) : 12 count = count + 1. 13 list_nodes = [nodes for nodes in partition.keys() 14 if partition[nodes] == com] 15 nx.draw_networkx_nodes(G, pos, list_nodes , node_size = 50, 16 node_color = str(count / size)) 17 18 nx.draw_networkx_edges(G,pos, alpha=0.5) 19 plt.axis('off'); 19
  • 20. Figure 5: 가라테 클럽의 Louvain Community Detection 2.3.2 중심성 Centrality Liu et al. (2013)은 약한 연결(weak ties)과 공통 이웃의 세 가지 노드 중심성(도수 중심성 degree centrality, 근접 중심성 closeness centrality, 매개 중심성 betweeness centrality)을 사용하여 링크 예측 방법을 제안하였다. LCS(x, y) = ∑ z (w(z) · f(z))β (29) f(z) = { 1, z ∈ Γ(x) ∩ Γ(y), 0, otherwise (30) w(z)는 노드의 중심성을 의미하고, f(z)는 전환 함수(switch function)을 말한다. β 는 공통된 이웃이 두 노드 사이 링크 가능성에 기여하는 정도를 조절한다. 만약 β 가 1보다 크다면, 큰 중심성이 작은 중심성보다 더 중요한 비중을 차지한다. 만약 β 가 0보다 작다면, 큰 중심성은 작은 중심성보다 더 억제된다. β 가 (0, 1) 사이에 있다면, 모든 노드가 동등하게 억제된다. 중심성이 중요한 역할을 한다는 것을 보여준 연구는 또 있다. Li et al. (2011)는 지금까지의 연구들은 유사한 노드를 찾는데 집중했지만, 노드의 중심성 또한 링크 예측에 중요한 역할을 한다는 사실을 보여준 연구이다. 이 사실을 보여주기 위해 극대 엔트로피 무작위 걷기(Maximal entropy random walk, MERW)를 이용한다. MERW를 사용하는 이유는 MERW의 전이 확률이 노드의 고유벡터(eigenvector) 중심성에 비례하기 때문이다. 도수, 매개, 근접 중심성이 가지는 아이디어들과는 다르게, 고유벡터 중심성은 중요한 이웃을 많이 가질수록 그래프에서 중요한 노드 라는 것을 알려주는 측정법이다. 다시 말해, 고유벡터 중심성은 노드의 구조적 문맥 (structural context)을 잡아낸다고 할 수 있다. 게다가 노드의 중심성을 얻기 위해 서 MERW는 두 가지 좋은 성질을 가지고 있다. 첫 번째는 주어진 두 노드 사이의 같은 길이를 같는 경로는 같은 확률을 갖는다. 두 번째는 주어진 두 노드 사이의 가장 긴 경로는 낮은 확률을 갖는다. 따라서, 전통적인 무작위 걷기 (Traditional random walk, TRW)보다 MERW가 목적에 더 적합하다고 할 수 있다. 여기에서 사용하는 중심성들을 계산해 보자. 1 import operator 20
  • 21. 2 3 G = nx.karate_club_graph() 4 print "::: Betweenness Centrality" 5 x = nx.betweenness_centrality(G) 6 sorted_list = sorted(x.iteritems(), key=operator.itemgetter(1), 7 reverse=True) 8 for s in sorted_list[:5]: 9 print s[0], s[1] 그래프의 매개 중심성을 계산하여 변수 x에 넣고, 매개 중심성이 높은 순서대로 정렬하여 가장 높은 순서로 5개만 출력하는 코드이다. 위 코드의 결과는 다음과 같이 출력된다. 1 ::: Betweenness Centrality 2 0 0.437635281385 3 33 0.30407497595 4 32 0.145247113997 5 2 0.143656806157 6 31 0.138275613276 도수 중심성, 근접 중심성은 nx.betweenness_centrality 대신 nx.degree_centrality, nx.closeness_centrality를 사용한다. 더 많은 중심성들은 3.4.9절을 참고하자. 2.3.3 성장 역학 Growth Dynamics 좀 더 복잡한 형태로 같은 이벤트에 있는 구성원끼리의 관계 등을 고려하여 사회 연결망의 진화 과정을 예측하는 모형들이 있다.(Qiu et al., 2010), (Qiu et al., 2011) 2.3.4 기타 사회과학 이론 이외에도 유유상종(homophily)을 사용한 Yang et al. (2011), 이질적인 사회 연 결망(heterogeneous social network)에서의 사회적 패턴을 찾기 위해 사회적 균형 등을 사용한 Dong et al. (2012) 등의 연구가 있다. 2.4 학습 기반 링크 예측 학습 기반의 링크 예측은 최근에 연구되고 있는 분야이다. 이 분야의 연구들은 크 게 특징 기반 분류(feature-based classification), 확률적 그래프 모델(probabilistic graph model) 그리고 행렬 인수분해(matrix factorization)로 나눌 수 있다. 2.4.1 특징 기반 분류 그래프 G(V, E)에서 x, y ∈ V 를 노드라 하고, 노드 쌍 (x, y)의 레이블(label)을 l(x,y) 라 하자. 링크 예측을 위해, 각각의 연결되지 않은 노드 쌍의 레이블을 두 가지 경우로 나누자. 양수(+1)이면 링크가 있고, 음수(−1)면 링크가 없는 경우다. l(x,y) = { +1, if (x, y) ∈ E −1, if (x, y) /∈ E (31) 21
  • 22. Figure 6: 그래프 커널 기반 추천 시스템 프레임워크 이것은 전형적인 이진 분류 문제이고, 해결법으로 다양한 지도 분류 학습 모델 (supervised classification learning model)들을 사용할 수 있다. 많이 알려진 방법 으로는 의사 결정 나무(decision tree), 지지 벡터 머신(support vector machine), 나이브 베이즈(naive Bayes) 등이 있다. 효율적인 분류자(classifier)를 구축하기 위해서는 사회 연결망에서 적절한 특징 들을 어떻게 정의하고 추출하느냐가 중요하다. 쉽게 생각해서는, 우리가 이미 위 절에서 살펴보았던 노드, 위상, 사회 이론을 기반으로 한 측정법들을 특징으로 삼아 분류 학습 모델을 구축할 수 있다. 예를 들어, 노드와 링크의 특성(사용자의 나이, 관심사, 친구관계 등)을 사용하여 성능 향상을 꾀한다. 특징을 잡는 다른 예로써, Lichtenwalter and Chawla (2012)는 지역적 위상 정보 (local topology information)를 특징으로 잡아 점배열프로필(Vertex collocation profile, VCP)을 구축했다. VCP는 V CPn,r i,j 로 구성되며, n개의 노드와 r 개의 링크를 가지는 모든 가능한 서브그래프에서 그들의 공통 원소에 대해 두 점 vi, vj 사이의 관계를 벡터로 표현한 것이다. VCP는 그 성능을 인정받아 링크 예측 라이브러리 LPmade의 1.2 버전3 에 포함되었다. 다른 방법으로는 그래프 커널 기반 학습 방법이 있다. 추천 시스템은 제품, 서비스, 콘텐츠 등을 유저에게 추천하기 위해 다양한 곳에 적용되어 왔다. 협력적 필터링 (Collaborative filtering, CF)은 현재도 많은 곳에서 쓰이는 성공적인 추천 패러다 임으로, 유저와 아이템 간의 거래 정보를 활용하는 시스템이다. 이 때 거래가 일어 나는 것은 유저와 아이템 사이에서만 일어나므로 이것은 이분(bipartite) 그래프 구조를 가지며, 추천 문제는 링크 예측 문제로 바라볼 수 있다. 이 문제를 해결하기 위해 Li and Chen (2013)는 커널 기반 학습 방법을 사용했다. 커널 학습 방법의 핵심 아이디어는 데이터들을 비선형 매핑을 통해 정보가 풍부한 (informative) 고차원 특징 공간으로 보내는 것이다. 이 방법은 커널 함수가 무엇이 냐가 중요하다. k : χ × χ → R (32) Li and Chen (2013)에서 커널 함수는 데이터를 입력 공간 χ 에서 특징 공간 H(reproducing kernel Hilbert space, RKHS) 으로 보낸 Φ(x) : χ → H 으로 정 의한다. 그리고 다음 조건을 만족한다. k(x, x′ ) =< Φ(x), Φ(x′ ) > 이에 대한 일반적인 프레임워크는 Figure 6와 같다. 3http://mloss.org/revision/view/864/ 22
  • 23. 그 외의 다른 특징 기반 분류 방법들은 각각의 학습 방법들이 주어진 데이터에 맞게 구성되어 있어 그 각각을 기술하기에 복잡하므로, 다음 Table 34 요약본을 참고하자. Table 3: 특징 기반 분류 방법들 방법 특징 학습 모델 네트워크 형태 장단점 VCP Vertex collocation profile Classification models in WEKA, HPLP su- pervised link predic- tion framework Directed, weighted, temporal, multi- relational networks Preserves as much topo- logical information as pos- sible; low performance in featuring and training Generic kernel- based machine learning Topological features: random walk paths; node features: re- flecting users’ deci- sions One-class SVM ker- nel machine User-item bipartite network Do not require explicit feature generation; perfor- mance is highly dependent on kernel functions Scellato et al. (2011) Place features, social features, global fea- tures Classifiers in WEKA: J48, NaÅNıve Bayes, model trees, random forests Location-based social networks Achieve high precision Pavlov and Ichise (2007), Wohl- farth and Ichise (2008) Topological features, semantic and event- based features SVM, decision trees, J48, decision stump, boosting Co-authorship net- works Performance is dependent on classification models Scripps et al. (2008) Node attributes, neighborhood topo- logical features Discriminative classi- fiers General networks Flexible framework that automatically determines the most predictive fea- tures De Sá and Prudên- cio (2011) Features of topology- based metrics J48, NaÅNıve Bayes, IBk, libSVM, LibLin- ear Weighted networks Using weights can improve supervised link prediction Kunegis and Lom- matzsch (2009) Adjacency matrix, number and length of paths Laplacian Kernels Undirected, weighted, un- weighted, unipartite and bipartite large networks General graph kernels and dimensionality reduction; runtime only depends on the chosen reduced rank, and is independent of the original graph size Pujari and Kanawati (2012) Topological features Supervised rank ag- gregation, decision tree, naÅNıve Bayes, kNN General networks Aggregate features as many as possible; high time complexity 4Wang et al. (2015) 23
  • 24. Chiang et al. (2011) Features from longer cycles Logistic regression Signed networks Not only achieves good ac- curacy for sign prediction but is also effective in low- ering the false positive rate Leskovec et al. (2010) Degrees of the nodes, triad Logistic regression Signed networks Signs of links can be pre- dicted with high accuracy Cao et al. (2010) No specific features restricted Nonparametric Bayesian model, transfer learning Large user-item net- works Transfer learning could help boost the performance Brouard et al. (2011) No specific features restricted Output kernel regres- sion General networks Uses the unlabeled data to improve performances for a low percentage of known links Lu et al. (2010) Path-based features Logistic regression Social networks with multiple auxiliary networks Prediction accuracy is im- proved; do not consider other features Wu et al. (2013) Statistics of co- inventors, link homophily, inter- est homophily, and correlation Ranking factor graph model; interactive learning Enterprise social net- works Significantly improves the performance for rec- ommending co-invention relationships Kashima et al. (2009) Node features: Kro- necker sum similar- ity, Kronecker prod- uct similarity Link propagation Multi-relational net- works Handles strength and types of links; high computa- tional time and space Raymond and Kashima (2010) Node features: Kro- necker sum and prod- uct Link propagation; matrix factorization and approximation Large dynamic net- works Less computational cost while maintaining accu- racy 2.4.2 확률적 그래프 모델 사회 연결망에서 노드 쌍 사이의 링크는 랜덤 워크의 전이 확률이나 위상적 유사성 을 계산했던 것처럼 확률로써 값을 할당할 수 있다. 이것을 확률적 그래프라 한다. 연구들 중에는 많은 네트워크들이 계층적 구조(hierarchical structure)를 가진다고 그 결과를 제안한다. 여기서 계층적 구조란 노드들이 그룹에 그룹에 다시 그룹에 속하는 것과 같은 구조를 말한다. Clauset et al. (2008)는 네트워크에서 계층적 구조를 추론하고 이것을 링크 예측을 푸는데 적용하는 방법을 제안했다. Figure 7과 같이 계층적 네트워크는 계층적 랜덤 그래프라고 불리는 계통수(dendrogram)로 표현될 수 있다. 네트워크의 노드는 N 개의 잎으로 표현되고, N − 1개에 해당하는 확률 pr 이 존재한다. 노드 쌍이 연결될 확률을 pr 로 나타내는데, r 은 두 노드의 가장 낮은 공통된 조상 (ancestor)이다. 예를 들어, Figure 7에서 노드 a와 c의 연결 확률(링크 예측)은 0.6이고, 노드 b 와 d가 연결될 확률은 0.3이다. 목표는 관찰된 네트워크에 잘 맞는 계통수을 찾는 것이다. 주어진 네트워크 G와 계통수 D 에 대해, Er 은 링크의 개수라 하자. Lr 과 Rr 은 각각 r 에서 왼쪽, 오른쪽 뿌리 방향으로의 서브 트리의 나뭇잎의 개수다. 24
  • 25. 그러면 링크 예측 가능성은 다음과 같이 정의하자. L(D, {Pr}) = ΠrpEr r (1 − pr)LrRr−Er (33) 내부 노드의 확률은 L(D, {Pr})을 극대화함으로써 쉽게 결정된다. 연결되지 않은 노드 x, y 가 연결될지 예측하기 위해, 먼저 그들의 가능성에 비율적인 확률로 계통 수의 집합을 샘플링한다. 그리고 이것을 계속 반영해서 평균 확률 pxy 를 계산한다. CN 같은 전통적인 측정법과 비교해 보면, 계층적 랜덤 그래프 모델은 종류별로 나누는 구조(assortative)인지 아닌지(disassortative)표현할 수 있고, 네트워크의 넓은 범위에 대해 좀 더 링크 예측의 정확도를 높일 수 있다. 하지만 계산 시간이 오래 걸리기 때문에, 수 천개의 노드 정도로 구성된 네트워크 정도에서만 사용한다. Figure 7: 네트워크의 계통수(dendrogram) 이 외에도 확률적 블록 모델(stochastic block model, Guimerà and Sales-Pardo (2009)), 베이즈 이론(Bayes’ Theorem)을 사용한 모델, 마코브 랜덤 필드(Markov Random Fields, MRF)를 사용한 모델 등 많은 방법들이 존재하며, 요약된 내용은 Table 45 를 참고하자. Table 4: 확률적 그래프 모델 방법들 방법 그래프 모델 네트워크 형태 특징 Clauset et al. (2008) Hierarchical random graph, maximum likelihood, Monte Carlo sampling Hierarchical networks Accurately predict missing links; performs poorly for networks have no hierarchical structure Guimerà and Sales- Pardo (2009) Stochastic block model Noisy networks Outperforms at identifying both missing links and spurious links; high computation time Chen and Zhang (2014) Marginalized denoising model General large networks Models the dense and smooth affin- ity matrices; is scalable to large net- works 5Wang et al. (2015) 25
  • 26. Wang et al. (2007) Maximum entropy Markov random fields Co-authorship net- works Co-occurrence probability feature is effective for link prediction, and combining with topology features and semantic features can improve the performance Kashima and Abe (2006) Parameterized probabilistic model, incremental learning Dynamic networks Achieves better performance than basic topology-based metrics Yang et al. (2011) Friendship-interest propa- gation framework devises a factor-based random walk model Interest networks, friendship networks Bridges collaborative filtering in rec- ommendation systems and random walk Backstrom and Leskovec (2011) Supervised random walks General networks Combines network structure with the attributes of nodes and links; requires no network feature gener- ation Marchette and Priebe (2008) Constrained random dot prod- uct graph Incomplete networks Predicts the possible unobserved links that actually present in the network Leroy et al. (2010) Bootstrap probabilistic graph Networks without the initial status and with other information Handle the cold start link predic- tion: predicting the structure of a social network when the net- work itself is totally missing while some other information regarding the nodes is available Kuo et al. (2013) Factor graph model Networks with aggrega- tive statistics of links Link prediction with aggregative statistics problem 2.4.3 행렬 인수분해 행렬을 인수분해하는 것은 때때로 행렬 내에 숨겨진 정보를 드러나게 하는 역할을 한다. 이를 이용해 링크 예측을 하는 것은 Menon and Elkan (2011)에서 제안되 었다. 행렬을 인수분해하는 다양한 방법 중에 특이값 분해(Singular value decomposi- tion, SVD)와 LU 분해(Decomposition)를 해보자. SVD는 라이브러리 Numpy를 이용해서 할 수 있다. 1 A = nx.to_numpy_matrix(G) 2 U, s, Vh = np.linalg.svd(A, full_matrices=True) 분해된 값이 행렬 A와 같은지 확인해 보자. 1 >>> np.allclose(A, np.dot(U, np.dot(np.diag(s), Vh))) 2 True 최적 근사(Best approximation)를 위해서 고유값을 잘라내 보자. 1 s[-1]=s[-2]=0 2 approx = np.dot(U, np.dot(np.diag(s), Vh)) 26
  • 27. 이 외에도 다양한 행렬 연산 함수들을 사용해서 원하는 작업을 할 수 있다. 자 세한 것은 Numpy 메뉴얼을 참고하자. http://docs.scipy.org/doc/numpy/ reference/routines.linalg.html LU 분해를 위해서는 라이브러리 scipy가 필요하다. 설치가 되어 있지 않은 경우 명령어 pip을 이용해 설치하자. $ pip install scipy scipy의 선형대수 패키지를 사용한다. 1 import scipy 2 A = nx.to_numpy_matrix(G) 3 scipy.linalg.lu(A) 3 시뮬레이션 3.1 네트워크 데이터 링크 예측을 위해 공개된 인기 있는 네트워크 데이터들은 다음과 같다. (Wang et al., 2015) 데이터 설명 크기 링크 노드 링크 DBLP Co-authorship network 317080 1049866 snap.stanford.edu/data/com-DBLP.html Paper citation network 324339 812740 arnetminer.org/citation Heterogeneous bibliographic 28702 authors; 28569 docs 103201 www.cs.uiuc.edu/hbdeng/data/kdd2011.htm Arxiv High energy physics paper citation network 34546 421578 snap.stanford.edu/data/cit-HepPh.html snap.stanford.edu/data/cit-HepTh.html NIPS 1-17 Co-authorship networks in NIPS 2865 4733 ai.stanford.edu/gal/data.html Enron email Email communi- cation network 28000 36692 250000 183831 www.cs.cmu.edu/enron/ snap.stanford.edu/data/email-Enron.html Patents cita- tion Citation net- work among US patents 3774768 16518948 snap.stanford.edu/data/cit-Patents.html Facebook Interactions be- tween users on Facebook 4039 60290 3694 88234 1545686 13692 snap.stanford.edu/data/egonets-Facebook.html socialnetworks.mpi-sws.org/datasets.html delab.csd.auth.gr/ symeon/facebook.txt Twitter Interactions be- tween users on Twitter 81306 124501 1768149 22169689 snap.stanford.edu/data/egonets-Twitter.html lsir.epfl.ch/aberer/ Foursquare Location-based social network 269279 1101504 www.csie.ntu.edu.tw/ d97944007/aggregative/ 27
  • 28. MovieLens Movie rating net- work 72000 users; 10000 movies 10000000 ratings grouplens.org/datasets/movielens/ Book- Crossing Book ratings net- work 278858 users; 271379 books 1149780 ratings www2.informatik.uni-freiburg.de/ cziegler/BX/ Wikipedia Vote network 7115 103689 snap.stanford.edu/data/wiki-Vote.html Epinions Trust social net- work 131828 841372 snap.stanford.edu/data/soc-sign-epinions.html Slashdot Signed network 82140 549202 snap.stanford.edu/data/soc-sign- Slashdot090221.html Plurk Micro-blog social network 543329 3660507 www.csie.ntu.edu.tw/ d97944007/diffusion/ 3.2 Python 파이썬을 http://www.python.org를 통해 설치하면 필요한 라이브러리를 설치 하는 데 많은 시간을 소모하게 되므로, 여기서는 라이브러리가 미리 통합되어 있는 파이썬 배포판6 중 하나인 Anaconda를 사용하도록 한다. Anaconda는 레드햇에서 만들었으며 칼데라 오픈리눅스 설치 소프트웨어 이름이 리자드(도마뱀)인 것에서 도마뱀을 먹는 비단뱀을 뜻하는 아나콘다라는 이름이 지어졌다. 윈도우, 맥, 리눅스 버전을 제공한다. 여기서는 Python 2.7을 사용하도록 하자. Anaconda Download : https://www.continuum.io/downloads 라이브러리에 대한 명령은 다음과 같이 이용하자. Theorem 3.1 윈도우 유저의 경우, 윈도우 키를 누르고 cmd 입력, 엔터 후 나오는 화면에서 아래의 명령어 입력한다. 맥 또는 리눅스 유저의 경우, 터미널에서 명령 어를 사용하자. • python -m pip install -U pip # pip의 버전 업그레이드 • pip install -U ipython # ipython의 버전 업그레이드 – pip install <라이브러리 이름> # 설치 – pip install -U <라이브러리 이름> # 업그레이드 – pip uninstall <라이브러리 이름> # 제거 윈도우 유저의 경우, ASCII 에러가 날 수 있다. 이 경우 아래의 내용을 수정해야 한다. • 텍스트 에디터로 다음 파일 열기 ‘C:AnacondaLibsite.py’ • 아래 내용을 찾아 def setencoding(): encoding = “ascii” 6Enthought Canopy, Continuum Analytics Anaconda, Python(x,y), WinPython 28
  • 29. • 아래처럼 변경 def setencoding(): encoding = “mbcs” 3.3 IPython IPython은 인터랙티브 컴퓨팅을 위한 명령 쉘을 제공한다. IPython notebook 을 이용하면 웹 상에서 입력, 출력 셀을 통해 리치 미디어를 다룰 수 있어 매우 편리하다. 최신 버전을 사용하는 경우, Jupyter라는 이름으로 바뀌었을 수 있다. IPython notebook의 사용은 Anaconda Launcher에서 실행하거나 터미널 또는 cmd에서 명령어를 입력하여 시작한다. $ ipython notebook 실행 후, 크롬 등의 인터넷 브라우져를 통해 http://localhost:8888 또는 실행 화 면에서 나오는 주소를 통해 접속한다. IPython에 대한 학습은 다음 사이트를 참고하자. https://github.com/jrjohansson/scientific-python-lectures 3.4 Networkx 네트워크(그래프) 계산을 하기 위한 라이브러리로 Networkx를 이용할 수 있다. 만약 설치가 되어있지 않다면 다음과 같이 Command Mode에서 쉽게 설치할 수 있다. $ pip install networkx or $ easy_install networkx or $ sudo apt-get install python-networkx 수동으로 설치할 경우 pypi7 를 참고하자. Networkx를 이용하기 위한 기본적인 방법은 다음과 같다. 1 >>> import networkx as nx # Import Library 2 >>> G = nx.Graph() # Generate graph type 3 >>> G.add_edge(1,2) # Add link 4 >>> nx.draw(G) # Draw graph 3.4.1 Graph 만들기 그래프의 형태를 먼저 정의하고, 노드와 링크를 추가한다. 1 >>> import networkx as nx # Import Library 2 >>> G=nx.Graph() # Define Graph Type 3 >>> G.add_node('a', 'b', 'c') 4 >>> G.add_edge('a', 'b') 7https://pypi.python.org/pypi/networkx/ 29
  • 30. Networkx에서 지원하는 그래프의 형태는 총 네 가지로 Graph(), DiGraph(), MultiGraph(), MultiDiGraph()8 이다. 3.4.2 노드를 정의하는 방법 1 >>> G = nx.Graph() 2 >>> G.add_node('apple') % 노드 'apple' 추가 3 >>> G . add_nodes_from(['banana' ,'kiwi' ,'mango']) % 리스트로추가 1 4 or 5 >>> fruits = ['banana' ,'kiwi' ,'mango'] 6 >>> G . add_nodes_from(fruits) % 리스트로추가 2 7 8 >>> G . nodes() % 노드들보기 9 ['apple' , 'kiwi' , 'mango' , 'banana'] 3.4.3 노드의 속성 부여하기 1 >>> G.nodes() 2 ['kiwi', 'mango', 'apple', 'banana'] 3 >>> G.node['kiwi'] 4 {} 5 >>> G.node['kiwi']['kind'] = 'fruit' 6 >>> G.node['kiwi'] 7 {'kind': 'fruit'} 8 >>> G.nodes(data=True) 9 [('kiwi', {'kind': 'fruit'}), ('mango', {}), ('apple', {}), 10 ('banana', {})] 11 12 >>> G.add_node('kiwi', kind='fruit') 13 >>> G.add_nodes_from(['banana', 'apple'], kind='fruit') 14 >>> G.node['banana'] 15 {'kind': 'fruit'} 3.4.4 엣지를 정의하는 방법 1 >>> G = nx.Graph() 2 >>> G.add_edge('apple', 'banana') % 'apple'과 'banana'의 관계추가 3 >>> G . add_edges_from([('apple' ,'mango'),('apple' ,'kiwi')]) % 리 스트로추가 1 4 or 5 >>> relations = [('apple' ,'mango'),('apple' ,'kiwi')] 6 >>> G . add_edges_from(relations) % 리스트로추가 2 7 8 >>> G . edges() % 엣지들보기 9 [('apple' , 'banana'), ('kiwi' , 'apple'), ('mango' , 'apple')] 3.4.5 엣지의 속성 부여하기 8https://networkx.github.io/documentation/latest/reference/classes.html 30
  • 31. 1 >>> G.edges() 2 [('kiwi', 'apple'), ('mango', 'apple'), ('apple', 'banana')] 3 >>> G.edges(data=True) 4 [('kiwi', 'apple', {}), ('mango', 'apple', {}), ('apple', 5 'banana', {})] 6 7 >>> G.add_edge('apple', 'mango', weight=2.5) 8 >>> G.add_edges_from(relations , color='blue') 9 >>> G['apple']['mango']['weight']=5 10 >>> G.edge['apple']['kiwi']['weight']=2 11 >>> G.edges(data=True) 12 [('kiwi', 'apple', {'color': 'blue'}), 13 ('mango', 'apple', {'color': 'blue', 'weight': 5}), 14 ('apple', 'banana', {})] 3.4.6 네트워크 그리기 네트워크를 그리기 위해서는 크게 세 가지가 정의되어 있어야 한다. a. 점 b. 선 c. 점의 위치 a와 b는 위에서 살펴 보았으므로, c를 알아보도록 하자. 기본적인 명령어 nx.draw 를 사용했을 때는 점의 위치를 spring layout으로 계산 하여 그림을 그려준다. 1 >>> G = nx.Graph() 2 >>> relations = [('apple', 'banana'), ('kiwi', 'apple'), 3 ('mango', 'apple')] 4 >>> G.add_edges_from(relations) # Generate nodes, edges 5 >>> nx.draw(G) # Generate positions of nodes with spring layout 만약 원하는 그래프 레이아웃이 있는 경우, 다음의 명령어들을 사용한다. 1 >>> nx.draw(G) # 기본그리기 2 >>> nx.draw_circular(G) # 원위에노드놓기 3 >>> nx.draw_graphviz(G) # Graphviz 사용 4 >>> nx.draw_random(G) # 균등분포를이용한랜덤 5 >>> nx.draw_shell(G) # 동심원위에노드놓기 6 >>> nx.draw_spectral(G) # 그래프라플라시안의고유벡터기반 7 >>> nx.draw_spring}}(G) # Fruchterman -Reingold force-directed 예를 들어, 다음과 같이 pos 변수를 점들의 위치로 지정하고, 그 변수를 draw할 때 position으로 사용한다. 1 >>> pos = nx.spectral_layout(G) 2 >>> print pos 3 {'kiwi': array([ 1., 0.]), 'mango': array([ 0., 1.]), 4 'apple': array([ 0.66666667, 0.66666667]), 'banana': 5 array([ 1., 1.])} 6 7 >>> nx.draw(G, pos) 31
  • 32. 3.4.7 한글이 들어간 네트워크 그리기 네트워크 그림에서 한글이 표시되지 않을 때는, 한글이 패치된 버전을 사용하면 일시적으로 해결할 수 있다. pip install -U git+https://github.com/koorukuroo/networkx_for_unicode 한국어 폰트를 사용하기 위해서 아래와 같이 폰트의 위치를 설정한다. 1 import matplotlib.font_manager as fm 2 # fp1 = fm.FontProperties(fname="./NanumGothic.otf") 3 fp1 = fm.FontProperties(fname="./NotoSansKR -Regular.otf") 4 nx.set_fontproperties(fp1) 5 G = nx.Graph() 6 G.add_edge(u'한국어',u'영어') 7 nx.draw(G, with_labels=True) 폰트가 마땅한 것이 없을 때에는 https://www.google.com/get/noto/pkgs/ NotoSansKorean-windows.zip 사용을 추천한다. 3.4.8 네트워크 정보 보기 1 print "Number of Nodes : ", nx.number_of_nodes(G) 2 print "Number of Edges : ", nx.number_of_edges(G) 3 degreelist = list(G.degree().values()) 4 print "Avg. Node Degree : ", float(sum(degreelist))/ 5 nx.number_of_nodes(G) 6 try: 7 print "Avg. Path Length : ", 8 nx.average_shortest_path_length(G) 9 except nx.NetworkXError as e: 10 print e 11 print "Avg. Clustering Coefficient : ", 12 nx.average_clustering(G) 13 Number of Nodes : 5242 14 Number of Edges : 67806 15 Avg. Node Degree : 25.8702785196 16 Avg. Path Length : Graph is not connected. 17 Avg. Clustering Coefficient : 0.259480104154 3.4.9 네트워크의 중심성 계산하기 Networkx에서는 다양한 중심성 계산 함수들을 제공한다.9 도수 중심성 Degree 1 nx.degree_centrality(G) 2 nx.in_degree_centrality(G) 3 nx.out_degree_centrality(G) 근접 중심성 Closeness 9https://networkx.github.io/documentation/latest/reference/algorithms. centrality.html 32
  • 33. 1 nx.closeness_centrality(G[, u, distance , ...]) 매개 중심성 Betweenness 1 nx.betweenness_centrality(G[, k, normalized , ...]) 2 nx.edge_betweenness_centrality(G[, k, ...]) Current Flow Closeness 1 nx.current_flow_closeness_centrality(G[, ...]) Current-Flow Betweenness 1 nx.current_flow_betweenness_centrality(G[, ...]) 2 nx.edge_current_flow_betweenness_centrality(G) 3 nx.approximate_current_flow_betweenness_centrality(G) 고유벡터 중심성 Eigenvector 1 nx.eigenvector_centrality(G[, max_iter , tol, ...]) 2 nx.eigenvector_centrality_numpy(G[, weight]) 3 nx.katz_centrality(G[, alpha, beta, max_iter , ...]) 4 nx.katz_centrality_numpy(G[, alpha, beta, ...]) Communicability 1 nx.communicability(G) 2 nx.communicability_exp(G) 3 nx.communicability_centrality(G) 4 nx.communicability_centrality_exp(G) 5 nx.communicability_betweenness_centrality(G[, ...]) 6 nx.estrada_index(G) Load 1 nx.load_centrality(G[, v, cutoff, normalized , ...]) 2 nx.edge_load(G[, nodes, cutoff]) Dispersion 1 nx.dispersion(G[, u, v, normalized , alpha, b, c]) 3.5 Gephi Gephi는 공개된 그래프 네트워크 시각화 프로그램이다. Gephi의 발음은 gϵfi10 로 한다. Gephi는 http://gephi.github.io에서 다운 받을 수 있다. 만약 Java8이 설치되어 있다면 Gephi가 올바르게 실행되지 않을 수 있다. 아쉽지만 Gephi 0.8.2 beta에서는 Java7을 사용해야 한다. http://www.oracle.com/technetwork/ java/javase/downloads/jdk7-downloads-1880260.html을 참고하여 Java SE Development Kit 7u79을 설치하자. 네트워크를 GUI(Graphic User Interface) 환경에서 다루고 싶을 때, Networkx에서 생성한 네트워크를 gephi로 가져올 수 있다. Networkx의 가라테 도장11 (Zachary, 1977) 데이터를 사용하자. 10https://en.wikipedia.org/wiki/Pronunciation_respelling_for_English 11http://vlado.fmf.uni-lj.si/pub/networks/data/Ucinet/UciData.htm 33
  • 34. Figure 8: Gephi 실행 화면 1 G = nx.karate_club_graph() 2 nx.draw(G, with_labels=True) Figure 9: 가라테 클럽의 networkx 그림 이 데이터를 Gephi에서 사용할 수 있도록 변환하자. 1 nx.write_gexf(G, 'karate.gexf') IPython notebook이 실행된 위치(ipynb 파일이 있는 곳)에 gexf 파일이 생성되 었다. 그 파일을 찾아 Gephi에서 불러오자. 이것을 적당히 조절하면 Figure 11 와 같이 그릴 수 있다. 자세한 사용법은 http://gephi.github.io/users/ 또는 Gephi Cookbook12 등을 참고하자. 12https://www.packtpub.com/big-data-and-business-intelligence/gephi-cookbook 34
  • 35. Figure 10: 가라테 클럽의 Gephi 그림 Figure 11: 가라테 클럽의 Gephi 그림 3.6 Pynetviz Networkx에서 그래프를 그리기 위해 nx.draw 함수를 사용하는 것은 라이브러리 Matplotlib의 pyplot을 이용한 기능이다. 간단한 네트워크라면 상관 없지만, 만약 규모가 큰 네트워크라면 그림을 그리는 데 상당히 많은 시간이 소요되며, 그림의 모양이 보기 좋지 않을 경우 다시 그려야 하는 불편함이 있다. 이 불편함을 해소하기 위해, 데이터 시각화 라이브러리 D3.js를 사용한 라이브러리 pynetviz를 사용해서 네트워크를 그려보도록 하자. https://pypi.python.org/pypi/pynetviz $ pip install pynetviz 가장 기본적인 사용법은 다음과 같다. 35
  • 36. 1 import pynetviz.sigmajs as nvs 2 G = nx.karate_club_graph() 3 layout = nx.spring_layout(G) 4 nvs.make_gexf(G, layout) 5 nvs.make_html(drawEdges='true') 6 nvs.view_html(height=1000) Figure 12: 가라테 클럽의 Pynetviz 그림 중심성 등을 반영한 노드의 사이즈 조절은 다음과 같이 할 수 있다. 1 layout = nx.spring_layout(G) 2 nvs.make_gexf(G, layout, size=nx.betweenness_centrality(G)) 3 nvs.make_html(drawEdges='true') 4 nvs.view_html(height=500) 자세한 사용법은 https://github.com/koorukuroo/pynetviz 또는 http:// goo.gl/7U2IlV을 참고하자. 3.7 Scikit-Learn Scikit-Learn은 파이썬의 기계학습 (Machine learning) 라이브러리이다. Clas- sification, Regression, Clustering, Dimensionality reduction, Model selection, 36
  • 37. Figure 13: 가라테 클럽의 Pynetviz 그림 with Centrality Preprocessing 등 전통적인 방법들을 대다수 지원하고 있으며, 일부 함수들의 경우 병렬 계산도 지원한다. 사용 방법은 http://scikit-learn.org/stable/documentation.html을 참고 하자. 4 Conclusions 링크 예측을 하는 주요 방법들과 그 방법들을 파이썬으로 구현하는 방법에 대해 살펴봤다. 링크 예측의 전통적인 방법이나 유명한 방법이 아닌 경우 코드로 구현되어 있지 않아 직접 구현을 해야 하지만, 파이썬에서 Numpy, Networkx, Scikit-learn 등을 이용해 어렵지 않게 구현할 수 있음을 알 수 있다. 네트워크의 시각화는 Pyplot, Gephi, Pynetviz 등을 통해 가능함을 살펴보았다. C언어로 작성된 LPmade13 를 파이썬에서 사용하고 싶은 경우 작성되어 있는 Python Wrapper를 이용하여 사용할 수 있다. 다음을 참고하자. https://github. com/jtreanor/LPmade-Python References Anderson, A., Huttenlocher, D., Kleinberg, J., and Leskovec, J. (2012). Effects of user similarity in social media. In Proceedings of the fifth ACM international conference on Web search and data mining, pages 703–712. ACM. Backstrom, L. and Leskovec, J. (2011). Supervised random walks: predicting and recommending links in social networks. In Proceedings of the fourth ACM international conference on Web search and data mining, pages 635– 644. ACM. Berry, M. W., Drmac, Z., and Jessup, E. R. (1999). Matrices, vector spaces, and information retrieval. SIAM review, 41(2):335–362. 13http://mloss.org/software/view/307/ 37
  • 38. Blondel, V. D., Guillaume, J.-L., Lambiotte, R., and Lefebvre, E. (2008). Fast unfolding of communities in large networks. Journal of Statistical Mechanics: Theory and Experiment, 2008(10):P10008. Borgatti, S. P., Mehra, A., Brass, D. J., and Labianca, G. (2009). Network analysis in the social sciences. science, 323(5916):892–895. Brouard, C., Szafranski, M., et al. (2011). Semi-supervised penalized output kernel regression for link prediction. In Proceedings of the 28th International Conference on Machine Learning (ICML-11), pages 593–600. Cao, B., Liu, N. N., and Yang, Q. (2010). Transfer learning for collective link prediction in multiple heterogenous domains. In Proceedings of the 27th International Conference on Machine Learning (ICML-10), pages 159–166. Chen, H.-H., Gou, L., Zhang, X. L., and Giles, C. L. (2012). Discovering missing links in networks using vertex similarity measures. In Proceedings of the 27th Annual ACM Symposium on Applied Computing, pages 138–143. ACM. Chen, Z. and Zhang, W. (2014). A marginalized denoising method for link prediction in relational data. In Proceedings of the 2014 SIAM International Conference on Data Mining, Philadelphia, pages 298–306. Chiang, K.-Y., Natarajan, N., Tewari, A., and Dhillon, I. S. (2011). Exploiting longer cycles for link prediction in signed networks. In Proceedings of the 20th ACM international conference on Information and knowledge management, pages 1157–1162. ACM. Clauset, A., Moore, C., and Newman, M. E. (2008). Hierarchical structure and the prediction of missing links in networks. Nature, 453(7191):98–101. De Sá, H. R. and Prudêncio, R. B. (2011). Supervised link prediction in weighted networks. In Neural Networks (IJCNN), The 2011 International Joint Con- ference on, pages 2281–2288. IEEE. Dong, Y., Tang, J., Wu, S., Tian, J., Chawla, N. V., Rao, J., and Cao, H. (2012). Link prediction and recommendation across heterogeneous social networks. In Data Mining (ICDM), 2012 IEEE 12th International Conference on, pages 181–190. IEEE. Fouss, F., Pirotte, A., Renders, J.-M., and Saerens, M. (2007). Random-walk computation of similarities between nodes of a graph with application to collaborative recommendation. Knowledge and data engineering, ieee trans- actions on, 19(3):355–369. Guimerà, R. and Sales-Pardo, M. (2009). Missing and spurious interactions and the reconstruction of complex networks. Proceedings of the National Academy of Sciences, 106(52):22073–22078. 38
  • 39. Jeh, G. and Widom, J. (2002). Simrank: a measure of structural-context sim- ilarity. In Proceedings of the eighth ACM SIGKDD international conference on Knowledge discovery and data mining, pages 538–543. ACM. Jones, W. P. and Furnas, G. W. (1987). Pictures of relevance: A geometric anal- ysis of similarity measures. Journal of the American society for information science, 38(6):420–442. Kashima, H. and Abe, N. (2006). A parameterized probabilistic model of network evolution for supervised link prediction. In Data Mining, 2006. ICDM’06. Sixth International Conference on, pages 340–349. IEEE. Kashima, H., Kato, T., Yamanishi, Y., Sugiyama, M., and Tsuda, K. (2009). Link propagation: A fast semi-supervised learning algorithm for link predic- tion. In SDM, volume 9, pages 1099–1110. SIAM. Katz, L. (1953). A new status index derived from sociometric analysis. Psy- chometrika, 18(1):39–43. Kunegis, J. and Lommatzsch, A. (2009). Learning spectral graph transforma- tions for link prediction. In Proceedings of the 26th Annual International Conference on Machine Learning, pages 561–568. ACM. Kuo, T.-T., Yan, R., Huang, Y.-Y., Kung, P.-H., and Lin, S.-D. (2013). Unsu- pervised link prediction using aggregative statistics on heterogeneous social networks. In Proceedings of the 19th ACM SIGKDD international conference on Knowledge discovery and data mining, pages 775–783. ACM. Leicht, E., Holme, P., and Newman, M. E. (2006). Vertex similarity in networks. Physical Review E, 73(2):026120. Leroy, V., Cambazoglu, B. B., and Bonchi, F. (2010). Cold start link predic- tion. In Proceedings of the 16th ACM SIGKDD international conference on Knowledge discovery and data mining, pages 393–402. ACM. Leskovec, J., Huttenlocher, D., and Kleinberg, J. (2010). Predicting positive and negative links in online social networks. In Proceedings of the 19th inter- national conference on World wide web, pages 641–650. ACM. Li, R.-H., Yu, J. X., and Liu, J. (2011). Link prediction: the power of maximal entropy random walk. In Proceedings of the 20th ACM international confer- ence on Information and knowledge management, pages 1147–1156. ACM. Li, X. and Chen, H. (2013). Recommendation as link prediction in bipartite graphs: A graph kernel-based machine learning approach. Decision Support Systems, 54(2):880–890. Liben-Nowell, D. and Kleinberg, J. (2007). The link-prediction problem for social networks. Journal of the American society for information science and technology, 58(7):1019–1031. 39
  • 40. Lichtenwalter, R. N. and Chawla, N. V. (2012). Vertex collocation profiles: subgraph counting for link analysis and prediction. In Proceedings of the 21st international conference on World Wide Web, pages 1019–1028. ACM. Liu, H., Hu, Z., Haddadi, H., and Tian, H. (2013). Hidden link prediction based on node centrality and weak ties. EPL (Europhysics Letters), 101(1):18004. Lü, L., Jin, C.-H., and Zhou, T. (2009). Similarity index based on local paths for link prediction of complex networks. Physical Review E, 80(4):046122. Lu, Z., Savas, B., Tang, W., and Dhillon, I. S. (2010). Supervised link pre- diction using multiple sources. In Data Mining (ICDM), 2010 IEEE 10th International Conference on, pages 923–928. IEEE. Marchette, D. J. and Priebe, C. E. (2008). Predicting unobserved links in incompletely observed networks. Computational Statistics & Data Analysis, 52(3):1373–1386. Menon, A. K. and Elkan, C. (2011). Link prediction via matrix factorization. In Machine Learning and Knowledge Discovery in Databases, pages 437–452. Springer. Newman, M. E. (2001). Clustering and preferential attachment in growing networks. Physical Review E, 64(2):025102. Newman, M. E. (2006). Modularity and community structure in networks. Proceedings of the National Academy of Sciences, 103(23):8577–8582. Papadimitriou, A., Symeonidis, P., and Manolopoulos, Y. (2012). Fast and accurate link prediction in social networking systems. Journal of Systems and Software, 85(9):2119–2132. Pavlov, M. and Ichise, R. (2007). Finding experts by link prediction in co- authorship networks. FEWS, 290:42–55. Pujari, M. and Kanawati, R. (2012). Link prediction in complex networks by supervised rank aggregation. In Tools with Artificial Intelligence (ICTAI), 2012 IEEE 24th International Conference on, volume 1, pages 782–789. IEEE. Qiu, B., He, Q., and Yen, J. (2011). Evolution of node behavior in link predic- tion. In AAAI. Qiu, B., Ivanova, K., Yen, J., and Liu, P. (2010). Behavior evolution and event- driven growth dynamics in social networks. In Social Computing (SocialCom), 2010 IEEE Second International Conference on, pages 217–224. IEEE. Raghavan, U. N., Albert, R., and Kumara, S. (2007). Near linear time algorithm to detect community structures in large-scale networks. Physical Review E, 76(3):036106. 40
  • 41. Ravasz, E., Somera, A. L., Mongru, D. A., Oltvai, Z. N., and Barabási, A.- L. (2002). Hierarchical organization of modularity in metabolic networks. science, 297(5586):1551–1555. Raymond, R. and Kashima, H. (2010). Fast and scalable algorithms for semi- supervised link prediction on static and dynamic graphs. In Machine Learning and Knowledge Discovery in Databases, pages 131–147. Springer. Scellato, S., Noulas, A., and Mascolo, C. (2011). Exploiting place features in link prediction on location-based social networks. In Proceedings of the 17th ACM SIGKDD international conference on Knowledge discovery and data mining, pages 1046–1054. ACM. Scripps, J., Tan, P.-N., Chen, F., and Esfahanian, A.-H. (2008). A matrix alignment approach for link prediction. In ICPR, pages 1–4. Citeseer. Turney, P. D., Pantel, P., et al. (2010). From frequency to meaning: Vector space models of semantics. Journal of artificial intelligence research, 37(1):141–188. Valverde-Rebaza, J. and de Andrade Lopes, A. (2013). Exploiting behaviors of communities of twitter users for link prediction. Social Network Analysis and Mining, 3(4):1063–1074. Valverde-Rebaza, J. C. and de Andrade Lopes, A. (2012). Link prediction in complex networks based on cluster information. In Advances in Artificial Intelligence-SBIA 2012, pages 92–101. Springer. Wang, C., Satuluri, V., and Parthasarathy, S. (2007). Local probabilistic mod- els for link prediction. In Data Mining, 2007. ICDM 2007. Seventh IEEE International Conference on, pages 322–331. IEEE. Wang, P., Xu, B., Wu, Y., and Zhou, X. (2015). Link prediction in social networks: the state-of-the-art. Science China Information Sciences, 58(1):1– 38. Wohlfarth, T. and Ichise, R. (2008). Semantic and event-based approach for link prediction. In Practical Aspects of Knowledge Management, pages 50–61. Springer. Wu, S., Sun, J., and Tang, J. (2013). Patent partner recommendation in enter- prise social networks. In Proceedings of the sixth ACM international confer- ence on Web search and data mining, pages 43–52. ACM. Yang, S.-H., Long, B., Smola, A., Sadagopan, N., Zheng, Z., and Zha, H. (2011). Like like alike: joint friendship and interest propagation in social networks. In Proceedings of the 20th international conference on World wide web, pages 537–546. ACM. Zachary, W. W. (1977). An information flow model for conflict and fission in small groups. Journal of anthropological research, pages 452–473. 41
  • 42. Zhou, T., Lü, L., and Zhang, Y.-C. (2009). Predicting missing links via local information. The European Physical Journal B, 71(4):623–630. Zhu, Y.-X., Lü, L., Zhang, Q.-M., and Zhou, T. (2012). Uncovering missing links with cold ends. Physica A: Statistical Mechanics and its Applications, 391(22):5769–5778. 42