공동 소속 찾기: 전치
희소 행렬 표현으로 바꾸면 그래프의 메타데이터가 사라지는 것을 보셨을 거예요. 이번에는 메타데이터를 다시 보완(impute)해서 공동 소속 정보를 더 잘 파악하는 방법을 배웁니다.
이전 연습 문제에서 계산한 user_matrix는 워크스페이스에 미리 로드되어 있습니다.
여기서 np.where() 함수가 유용합니다. 예를 들어 배열 a = [1, 5, 9, 5]가 있을 때 값이 5인 위치의 인덱스를 얻으려면 idxs = np.where(a == 5)처럼 사용할 수 있어요. 이는 (array([1, 3]),) 형태의 튜플을 반환합니다. 해당 인덱스 배열에 접근하려면 idxs[0]처럼 튜플에 인덱싱해야 합니다.
이 연습은 강의의 일부입니다
Python 중급 네트워크 분석
연습 안내
- 가장 많은 동아리에 가입했던 사람들의 이름을 찾으세요.
- 이를 위해 먼저
user_matrix에서.diagonal()메서드를 사용해diag를 계산하세요. - 그런 다음
np.where()를 사용해diag가diag.max()와 같은 위치의 인덱스를 선택하세요. 이 함수는 튜플을 반환하므로,[0]으로 튜플에 인덱싱해 실제 인덱스 배열에 접근해야 합니다. indices를 순회하면서 제공된print()함수를 사용해people_nodes의 각 인덱스i를 출력하세요.
- 이를 위해 먼저
- 대각 성분을 0으로 설정하고 "coordinate matrix format"으로 변환하세요. 이 코드는 정답에 제공되어 있습니다.
- 가장 많은 동아리를 함께한 사용자 쌍을 찾으세요.
np.where()를 사용해users_coo.data가users_coo.data.max()와 같은 위치의 인덱스를 선택하세요.indices2를 순회하며 각 인덱스idx에 대해users_coo.row와users_coo.col의 값을 사용해people_node의 항목을 출력하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
import numpy as np
# Find out the names of people who were members of the most number of clubs
diag = ____
indices = np.where(____ == ____)[0]
print('Number of clubs: {0}'.format(diag.max()))
print('People with the most number of memberships:')
for i in indices:
print('- {0}'.format(____))
# Set the diagonal to zero and convert it to a coordinate matrix format
user_matrix.setdiag(0)
users_coo = user_matrix.tocoo()
# Find pairs of users who shared membership in the most number of clubs
indices2 = np.where(____ == ____)[0]
print('People with most number of shared memberships:')
for idx in indices2:
print('- {0}, {1}'.format(people_nodes[____.____[____]], people_nodes[____.____[____]]))