用户相似度度量
您已经编写了一个函数来计算两个节点之间共享的节点集合。接下来,请编写一个函数来计算两个用户之间的相似度度量:两个用户共享的项目数,除以另一分区中节点的总数。该度量可用于查找彼此相似的用户。
本练习是课程的一部分
Python 网络分析中级
练习说明
- 完成
user_similarity()函数,计算user1与user2的相似度。- 使用
assert语句检查user1和user2均属于'users'分区。 - 使用上一练习中的
shared_partition_nodes()函数,获取用户user1与user2共享的节点集合。 - 返回在
projects分区中的比例。也就是说,用shared_nodes的数量除以'projects'分区中节点的总数。
- 使用
- 计算用户
'u4560'与'u1880'之间的相似度分数。步骤如下:- 先使用
get_nodes_from_partition()函数获取'projects'分区中的节点。 - 然后使用
user_similarity()函数计算该分数。
- 先使用
交互式实操练习
通过完成这段示例代码来试试这个练习。
def user_similarity(G, user1, user2, proj_nodes):
# Check that the nodes belong to the 'users' partition
____ G.nodes[____]['bipartite'] == '____'
____ G.nodes[____]['bipartite'] == '____'
# Get the set of nodes shared between the two users
shared_nodes = ____
# Return the fraction of nodes in the projects partition
return len(____) / len(____)
# Compute the similarity score between users 'u4560' and 'u1880'
project_nodes = ____
similarity_score = ____
print(similarity_score)