查找共同成员:转置
您可能已经注意到,当将图转换为稀疏矩阵表示时,会丢失元数据。接下来您将学习如何把这些元数据补回去,从而更好地分析共同成员关系。
上一练习中您计算得到的 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[____.____[____]]))