Class: Ankusa::NaiveBayesClassifier

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

Instance Attribute Summary

Attributes included from Classifier

#classnames

Instance Method Summary collapse

Methods included from Classifier

#initialize, #train, #untrain

Instance Method Details

#classifications(text, classnames = nil) ⇒ Object

Classes is an array of classes to look at



20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/ankusa/naive_bayes.rb', line 20

def classifications(text, classnames=nil)
  result = log_likelihoods text, classnames
  result.keys.each { |k|
    result[k] = (result[k] == -INFTY) ? 0 : Math.exp(result[k])
  }

  # normalize to get probs
  sum = result.values.inject{ |x,y| x+y }
  result.keys.each { |k|
    result[k] = result[k] / sum
    } unless sum.zero?
  result
end

#classify(text, classes = nil) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/ankusa/naive_bayes.rb', line 7

def classify(text, classes=nil)
  # return the most probable class

  result = log_likelihoods(text, classes)
  if result.values.uniq.size. === 1
    # unless all classes are equally likely, then return nil
    return nil
  else
    result.sort_by { |c| -c[1] }.first.first
  end
end

#log_likelihoods(text, classnames = nil) ⇒ Object

Classes is an array of classes to look at



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/ankusa/naive_bayes.rb', line 35

def log_likelihoods(text, classnames=nil)
  classnames ||= @classnames
  result = Hash.new 0

  TextHash.new(text).each { |word, count|
    probs = get_word_probs(word, classnames)
    classnames.each { |k|
      # Choose a really small probability if the word has never been seen before in class k
      result[k] += Math.log(probs[k] > 0 ? (probs[k] * count) : Float::EPSILON)
    }
  }

  # add the prior
  doc_counts = doc_count_totals.select { |k,v| classnames.include? k }.map { |k,v| v }

  doc_count_total = (doc_counts.inject(0){ |x,y| x+y } + classnames.length).to_f

  classnames.each { |k|
    result[k] += Math.log((@storage.get_doc_count(k) + 1).to_f / doc_count_total)
  }

  result
end