Class: NLPBackpack::Classifier::NaiveBayes
- Defined in:
- lib/nlp_backpack/classifier/naive_bayes.rb
Instance Attribute Summary
Attributes inherited from Base
Instance Method Summary collapse
-
#classify(*features) ⇒ Object
P(Class | Item) = P(Item | Class) * P(Class).
-
#initialize(*klasses) ⇒ NaiveBayes
constructor
A new instance of NaiveBayes.
- #train(klass, *features) ⇒ Object
Methods inherited from Base
Constructor Details
#initialize(*klasses) ⇒ NaiveBayes
Returns a new instance of NaiveBayes.
20 21 22 23 24 25 26 27 28 29 |
# File 'lib/nlp_backpack/classifier/naive_bayes.rb', line 20 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 Method Details
#classify(*features) ⇒ Object
P(Class | Item) = P(Item | Class) * P(Class)
39 40 41 42 43 44 45 |
# File 'lib/nlp_backpack/classifier/naive_bayes.rb', line 39 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 |
#train(klass, *features) ⇒ Object
31 32 33 34 35 36 |
# File 'lib/nlp_backpack/classifier/naive_bayes.rb', line 31 def train(klass, *features) features.uniq.each do |feature| @features_count[klass][feature] += 1 end @klass_count[klass] += 1 end |