找出共同成員關係:轉置
你可能已經注意到,當你用稀疏矩陣來表示圖形時,會失去原本的中繼資料。現在你要學的是如何把這些中繼資料補回來,這樣就能更深入了解共同成員關係。
你在上一題計算的 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,並轉換成「座標矩陣格式」。這段程式碼已在解答中提供。
- 找出共同加入社團數量最多的使用者配對。
- 使用
np.where(),存取users_coo.data等於users_coo.data.max()的索引。 - 迭代
indices2,並印出people_node的users_coo.row與users_coo.col中每個索引idx對應的值。
- 使用
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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[____.____[____]]))