Class: SlopeOne

Inherits:
Object
  • Object
show all
Defined in:
lib/slope_one.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeSlopeOne

Returns a new instance of SlopeOne.



6
7
8
9
# File 'lib/slope_one.rb', line 6

def initialize
  self.diffs = {}
  self.freqs = {}
end

Instance Attribute Details

#diffsObject

Returns the value of attribute diffs.



4
5
6
# File 'lib/slope_one.rb', line 4

def diffs
  @diffs
end

#freqsObject

Returns the value of attribute freqs.



4
5
6
# File 'lib/slope_one.rb', line 4

def freqs
  @freqs
end

Instance Method Details

#insert(user_data) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/slope_one.rb', line 11

def insert(user_data)
  user_data.each do |name, ratings|
    ratings.each do |item1, rating1|
      self.freqs[item1] ||= {}
      self.diffs[item1] ||= {}
      ratings.each do |item2, rating2|
        self.freqs[item1][item2] ||= 0
        self.diffs[item1][item2] ||= 0.0
        self.freqs[item1][item2] += 1
        self.diffs[item1][item2] += (rating1 - rating2)
      end
    end
  end
  
  self.diffs.each do |item1, ratings|
    ratings.each do |item2, rating2|
      ratings[item2] = ratings[item2] / self.freqs[item1][item2]
    end
  end
end

#predict(user) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/slope_one.rb', line 32

def predict(user)
  preds, freqs = {}, {}

  user.each do |item, rating|
    self.diffs.each do |diff_item, diff_ratings|
      next if self.freqs[diff_item].nil? or diff_ratings[item].nil?
      freq = self.freqs[diff_item][item]
      preds[diff_item] ||= 0.0
      freqs[diff_item] ||= 0
      preds[diff_item] += freq * (diff_ratings[item] + rating)
      freqs[diff_item] += freq
    end
  end
  
  results = {}
  preds.each do |item, value|
    results[item] = sprintf('%.3f', (value / freqs[item])).to_f unless user.include?(item) && freqs[item] > 0
  end
  return results
end