为尚未共同编辑的协作者做推荐
最后,您将利用开放三角形的概念,为 GitHub 用户推荐潜在的合作对象!
本练习是课程的一部分
Python 网络分析入门
练习说明
- 汇总一份应互相推荐合作的 GitHub 用户列表。具体步骤:
- 在第一个
for循环中,遍历G中的所有节点,并包含元数据(通过设置data=True)。 - 在第二个
for循环中,遍历所有可能的三角形组合,可使用size为2的combinations()函数来获取。 - 如果
n1和n2之间没有边,则应推荐这两个节点(用户)进行合作。在这种情况下,将recommended字典中(n1), (n2)对应的值加一。您可以使用.has_edge()方法检查n1和n2之间是否存在边。
- 在第一个
- 使用列表推导式,找出最应推荐合作的前 10 对用户。可迭代对象 应为
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)