아직 함께 편집하지 않은 공동 편집자 추천하기
마지막으로, 열린 삼각형(open triangles) 개념을 활용해 GitHub에서 협업할 사용자를 추천해 볼 거예요!
이 연습은 강의의 일부입니다
Python으로 시작하는 네트워크 분석
연습 안내
- 서로 협업을 추천해야 할 GitHub 사용자 쌍 목록을 만들어 보세요. 이를 위해 다음을 수행하세요:
- 첫 번째
for루프에서는data=True를 지정해 메타데이터를 포함하여G의 모든 노드를 순회하세요. - 두 번째
for루프에서는size가2인combinations()함수를 사용해 가능한 모든 삼각형 조합을 순회하세요. n1과n2사이에 간선이 없다면, 이 두 노드(사용자) 간의 협업을 추천해야 하므로, 이 경우recommended딕셔너리의(n1), (n2)값을 증가시키세요.n1과n2사이에 간선이 있는지는.has_edge()메서드로 확인할 수 있어요.
- 첫 번째
- 리스트 컴프리헨션을 사용해 협업을 추천해야 할 상위 10개 사용자 쌍을 찾으세요. 반복 가능 객체(iterable) 는
recommended딕셔너리의 키-값 쌍(.items()로 접근)이고, 조건은count가all_counts의 상위 10개보다 큰 경우예요.all_counts는 오름차순으로 정렬되어 있으므로all_counts[-10]으로 상위 10개 기준을 가져올 수 있어요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Import necessary modules
from itertools import combinations
from collections import defaultdict
# Initialize the defaultdict: recommended
recommended = defaultdict(int)
# Iterate over all the nodes in G
for n, d in ____:
# Iterate over all possible triangle relationship combinations
for n1, n2 in ____(list(G.neighbors(n)), ____):
# Check whether n1 and n2 do not have an edge
if not G.has_edge(____, ____):
# Increment recommended
____[(____, ____)] += 1
# Identify the top 10 pairs of users
all_counts = sorted(recommended.values())
top10_pairs = [pair for pair, count in ____ if ____ > ____]
print(top10_pairs)