Class: NaiveBayes::Classifier

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ Classifier

Returns a new instance of Classifier.



8
9
10
11
12
13
14
15
# File 'lib/naivebayes/classifier.rb', line 8

def initialize(params = {})
  @frequency_table = Hash.new
  @word_table = Hash.new
  @instance_count_of = Hash.new(0)
  @total_count = 0
  @model = params[:model]
  @smoothing_parameter = params[:smoothing_parameter] || 1
end

Instance Attribute Details

#frequency_tableObject

Returns the value of attribute frequency_table.



6
7
8
# File 'lib/naivebayes/classifier.rb', line 6

def frequency_table
  @frequency_table
end

#instance_count_ofObject

Returns the value of attribute instance_count_of.



6
7
8
# File 'lib/naivebayes/classifier.rb', line 6

def instance_count_of
  @instance_count_of
end

#modelObject

Returns the value of attribute model.



6
7
8
# File 'lib/naivebayes/classifier.rb', line 6

def model
  @model
end

#smoothing_parameterObject

Returns the value of attribute smoothing_parameter.



6
7
8
# File 'lib/naivebayes/classifier.rb', line 6

def smoothing_parameter
  @smoothing_parameter
end

#total_countObject

Returns the value of attribute total_count.



6
7
8
# File 'lib/naivebayes/classifier.rb', line 6

def total_count
  @total_count
end

#word_tableObject

Returns the value of attribute word_table.



6
7
8
# File 'lib/naivebayes/classifier.rb', line 6

def word_table
  @word_table
end

Instance Method Details

#classify(feature) ⇒ Object



33
34
35
# File 'lib/naivebayes/classifier.rb', line 33

def classify(feature)
  @model == "complement" ? cnb(feature) : mnb(feature)
end

#train(label, feature) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/naivebayes/classifier.rb', line 17

def train(label, feature)
  unless @frequency_table.has_key?(label)
    @frequency_table[label] = Hash.new(0)
  end
  feature.each {|word, frequency|
    if @model == "berounoulli"
      @frequency_table[label][word] += 1
    else
      @frequency_table[label][word] += frequency
    end
    @word_table[word] = 1
  }
  @instance_count_of[label] += 1
  @total_count += 1
end