Class: SlopeOne
- Inherits:
-
Object
- Object
- SlopeOne
- Defined in:
- lib/slope_one.rb
Instance Attribute Summary collapse
-
#diffs ⇒ Object
Returns the value of attribute diffs.
-
#freqs ⇒ Object
Returns the value of attribute freqs.
Instance Method Summary collapse
-
#initialize ⇒ SlopeOne
constructor
A new instance of SlopeOne.
- #insert(user_data) ⇒ Object
- #predict(user) ⇒ Object
Constructor Details
#initialize ⇒ SlopeOne
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
#diffs ⇒ Object
Returns the value of attribute diffs.
4 5 6 |
# File 'lib/slope_one.rb', line 4 def diffs @diffs end |
#freqs ⇒ Object
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, | .each do |item1, | self.freqs[item1] ||= {} self.diffs[item1] ||= {} .each do |item2, | self.freqs[item1][item2] ||= 0 self.diffs[item1][item2] ||= 0.0 self.freqs[item1][item2] += 1 self.diffs[item1][item2] += ( - ) end end end self.diffs.each do |item1, | .each do |item2, | [item2] = [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, | self.diffs.each do |diff_item, | next if self.freqs[diff_item].nil? or [item].nil? freq = self.freqs[diff_item][item] preds[diff_item] ||= 0.0 freqs[diff_item] ||= 0 preds[diff_item] += freq * ([item] + ) 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 |