forked from matefh/Trustious-Recommender
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimilarity.rb
executable file
·50 lines (42 loc) · 1.08 KB
/
similarity.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/env ruby
require './linear_algebra.rb'
include LinearAlgebra
module Similarity
def cosine_rule(vec1, vec2)
dot = LinearAlgebra.dot_product(vec1, vec2)
magn = LinearAlgebra.magnitude(vec1) * LinearAlgebra.magnitude(vec2)
if magn > 1e-9
then
return dot / magn
else
return 0
end
end
def pearson_correlation(vec1, vec2)
average1 = 0
average2 = 0
vec1.each {|x| average1 += x}
vec2.each {|x| average2 += x}
if vec1.size != 0
then
average1 /= vec1.size.to_f
end
if vec2.size != 0
then
average2 /= vec2.size.to_f
end
return cosine_rule(vec1.map {|x| x - average1},
vec2.map {|x| x - average2})
end
def compute_expected_rating(rating_list, similarity_list)
weighted_rating = LinearAlgebra.dot_product(rating_list, similarity_list)
total_similarity = 0
similarity_list.each {|similarity| total_similarity += similarity}
if total_similarity.abs > 1e-9
then
return weighted_rating.to_f / total_similarity.to_f
else
return 0
end
end
end