Class: Classiphier::Bayes

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

Instance Method Summary collapse

Constructor Details

#initializeBayes

Returns a new instance of Bayes.



3
4
5
# File 'lib/classiphier/bayes.rb', line 3

def initialize
  @data = Data.new
end

Instance Method Details

#classifications(sentence) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/classiphier/bayes.rb', line 17

def classifications(sentence)
  Hash.new(0).tap do |score|
    @data[:data].each do |category, data|
      sentence.words.each do |word|
        value = data[:data].fetch(word, 0.1).to_f
        score[category] += Math.log(value / data[:words])
      end

      value = @data[:data][category][:count].to_f
      score[category] += Math.log(value / @data[:count])
    end
  end
end

#classify(sentence) ⇒ Object



13
14
15
# File 'lib/classiphier/bayes.rb', line 13

def classify(sentence)
  classifications(sentence).min_by { |a| -a[1] }[0]
end

#train(category, sentence) ⇒ Object



7
8
9
10
11
# File 'lib/classiphier/bayes.rb', line 7

def train(category, sentence)
  @data.perform!
  @data[:data][category] ||= Data.new
  @data[:data][category].train(sentence)
end