Class: Bayes::Classifier

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeClassifier

Returns a new instance of Classifier.



5
6
7
# File 'lib/bayes/classifier.rb', line 5

def initialize
  @categories = {}
end

Instance Attribute Details

#categoriesObject (readonly)

Returns the value of attribute categories.



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

def categories
  @categories
end

Instance Method Details

#apply_weighting(category, coeff) ⇒ Object



32
33
34
# File 'lib/bayes/classifier.rb', line 32

def apply_weighting(category, coeff)
  ensure_category(category).apply_weighting(coeff)
end

#classify(string) ⇒ Object



36
37
38
39
40
41
# File 'lib/bayes/classifier.rb', line 36

def classify(string)
  words = string.word_hash.keys
  @categories.each_with_object({}) do |category, hash|
    hash[category[0]] = category[1].score_for(words)
  end.sort_by { |cat| -cat[1] }[0][0]
end

#ensure_category(category) ⇒ Object



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

def ensure_category(category)
  @categories[category] ||= Bayes::Category.new
end

#flushObject



47
48
49
# File 'lib/bayes/classifier.rb', line 47

def flush
  @categories.each{ |name, cat| cat.reset }
end

#flush_allObject



51
52
53
# File 'lib/bayes/classifier.rb', line 51

def flush_all
  @categories = {}
end

#pop_unusedObject



43
44
45
# File 'lib/bayes/classifier.rb', line 43

def pop_unused
  @categories.delete_if{ |name,cat| cat.blank? }
end

#train(category, text) ⇒ Object



9
10
11
# File 'lib/bayes/classifier.rb', line 9

def train(category, text)
  ensure_category(category).train(text)
end

#train_with_array(category, lines) ⇒ Object



17
18
19
# File 'lib/bayes/classifier.rb', line 17

def train_with_array(category, lines)
  lines.each{ |line| train(category, line) }
end

#train_with_csv(filename, separator: "||") ⇒ Object



25
26
27
28
29
30
# File 'lib/bayes/classifier.rb', line 25

def train_with_csv(filename, separator: "||")
  csv = CSV.new File.read(filename), col_sep: separator, quote_char: "§" # hope § won't be used anywhere
  csv.each do |row|
    train row[1], row[0]
  end
end

#train_with_file(category, filename) ⇒ Object



21
22
23
# File 'lib/bayes/classifier.rb', line 21

def train_with_file(category, filename)
  train_with_array category, File.read(filename).split(/\r?\n/)
end