Created
June 13, 2010 17:35
-
-
Save koduki/436827 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sim_dist items, user1, user2 | |
keys = items.to_a.map{|x| x[1].keys}.flatten.uniq | |
sum = keys.map{ |item| | |
if items[user1][item] == nil or items[user2][item] == nil | |
0 | |
else | |
Math.sqrt((items[user1][item] - items[user2][item]) ** 2) | |
end | |
}.reduce(0){|r, x| r + x} | |
1 / (sum +1) | |
end | |
def sim_user items, user | |
users = items.to_a.map{|x| x[0]}.find_all{|u| u != user} | |
users.map{|u| [u,sim_dist(items, user, u)]} | |
.sort{|x,y| y[1] - x[1]} | |
.first[0] | |
end | |
def recom_item items, user | |
users = items.to_a.map{|x| x[0]}.find_all{|u| u != user} | |
items2 = users.map{|u| | |
[u, items[u].reject{|x| items[user].map{|x| x[0]}.index(x) } | |
.map{|x| [x[0], x[1] * sim_dist(items, user, u)]}]} | |
table = items2.map{|x| x[1]} | |
.flatten(1) | |
.reduce({}){|r, xs| | |
k = xs[0] | |
v = xs[1] | |
r[k] = (r[k] == nil) ? v : r[k] + v | |
r | |
} | |
table.to_a.sort{|x, y| y[1] - x[1]}.first[0] | |
end | |
items= { | |
:Taro =>{:A=>2.5, :B=>3.5, :C=>2}, | |
:Hanako =>{:A=>2.3, :B=>3.5, :C=>2.1, :D=>4}, | |
:Sanshiro=>{:A=>1.5, :B=>3.5, :C=>2, :E=>1}, | |
:Goro =>{:A=>1.5, :B=>3.5, :C=>2, :E=>4} | |
} | |
sim_dist(items, :Taro, :Sanshiro) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment