我的收藏包含:
{ user_id : 1, product_id : 1 },
{ user_id : 1, product_id : 2 },
{ user_id : 1, product_id : 3 },
{ user_id : 2, product_id : 2 },
{ user_id : 2, product_id : 3 },
{ user_id : 3, product_id : 2 },
我的收藏跟踪用户查看的产品,其中 user_id 是用户 ID,product_id 是产品 ID。
我想计算两个用户之间的相似度,例如他们都浏览过的产品数量。
例如,从上面的集合中,用户之间的相似度将是
{ user_id1 : 1, user_id2 : 2, similarity : 2 },
{ user_id1 : 1, user_id2 : 3, similarity : 1 },
{ user_id1 : 2, user_id2 : 3, similarity : 1 },
已编辑
我已经在没有使用map-reduce的情况下完成了
def self.build_similarity_weight
users_id = ProductView.all.distinct(:user_id).to_a
users_id.each do |user_id|
this_user_products = ProductView.all.where(user_id: user_id).distinct(:product_id).to_a
other_users = users_id.map { |e| e }
other_users.delete_if { |x| x == user_id }
other_users.each do |other_uid|
other_user_products = ProductView.all.where(user_id: other_uid).distinct(:product_id).to_a
user_sim = (other_user_products & this_user_products).length
usw = UserSimilarityWeight.new(user_id1: user_id, user_id2: other_uid, weight: user_sim)
usw.save
end
end
end
问题是我的代码效率不高,O(n2),其中n是用户数量。
如何使用 map-reduce 使我的代码更加高效?
问候,
最佳答案
首先,您执行 2 个映射缩减。
- 映射:省略 Product_id 作为键,省略 user_id 作为值
- reduce:在循环内循环迭代值列表(每个产品的用户 ID 列表),并省略用户 ID 的键对(其中最小的用户 ID 是第一个)和值 1
(处理第一次映射缩减的结果)
- map:只需将用户对作为键传递,并将值 1 作为值传递
- reduce:对每对值求和。
其次,你不可能比 O(n2) 更高效,因为你的结果是 O(n2) 的量级。 这意味着,即使以某种神奇的方式,您将获得对和相似度,您仍然需要编写 n^2 个对。
关于mongodb - 使用映射减少用户到用户的相似度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10561797/