Class: NaiveBayes

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

Overview

However, when classifying, P(Item) is the same across all calcualtions So we don’t bother to calculate it

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*klasses) ⇒ NaiveBayes

Returns a new instance of NaiveBayes.



30
31
32
33
34
35
36
37
38
39
# File 'lib/naive_bayes.rb', line 30

def initialize(*klasses)
  @features_count = {}
  @klass_count = {}
  @klasses = klasses
  
  klasses.each do |klass|
    @features_count[klass] = Hash.new(0.0)
    @klass_count[klass] = 0.0
  end
end

Instance Attribute Details

#db_filepathObject

Returns the value of attribute db_filepath.



28
29
30
# File 'lib/naive_bayes.rb', line 28

def db_filepath
  @db_filepath
end

Class Method Details

.load(db_path) ⇒ Object



17
18
19
20
21
22
23
24
25
# File 'lib/naive_bayes.rb', line 17

def load(db_path)
  data = ""
  File.open(db_path) do |f|
    while line = f.gets
      data << line
    end
  end
  Marshal.load(data)
end

Instance Method Details

#classify(*features) ⇒ Object

P(Class | Item) = P(Item | Class) * P(Class)



49
50
51
52
53
54
55
# File 'lib/naive_bayes.rb', line 49

def classify(*features)
  scores = {}
  @klasses.each do |klass|
    scores[klass] = (prob_of_item_given_a_class(features, klass) * prob_of_class(klass))
  end
  scores.sort {|a,b| b[1] <=> a[1]}[0]
end

#saveObject



57
58
59
60
61
62
# File 'lib/naive_bayes.rb', line 57

def save
  raise "You haven't set a db_filpath, I dont know where to save" if @db_filepath.nil?
  File.open(@db_filepath, "w+") do |f|
    f.write(Marshal.dump(self))
  end
end

#train(klass, *features) ⇒ Object



41
42
43
44
45
46
# File 'lib/naive_bayes.rb', line 41

def train(klass, *features)
  features.uniq.each do |feature|
    @features_count[klass][feature] += 1
  end
  @klass_count[klass] += 1
end