Class: Classify::NB

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeNB

Returns a new instance of NB.



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

def initialize
  @labels = {}
  @features = Set.new
  @nF = 0.0
  @nL = 0.0
  @c = 0.5
end

Class Method Details

.from_json(json) ⇒ Object



37
38
39
40
41
42
43
44
45
# File 'lib/lite/classifier.rb', line 37

def self.from_json json
  parsed = JSON.parse json
  c = self.new
  c.instance_variable_set("@labels", parsed["labels"])
  c.instance_variable_set("@features", Set.new( parsed["F"] ) )
  c.instance_variable_set("@nF", parsed["nf"])
  c.instance_variable_set("@nL",  parsed["nl"])
  c
end

Instance Method Details

#classify(fvect) ⇒ Object



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

def classify fvect
  @labels.keys.inject({}) do |aux,y|
    sx = fvect.keys.inject(0.0){|z, fi| z += fvect[fi] * Math.log( (@labels[y]["xs"][fi]||@c) / (@labels[y]["nX"]+@c*@nF))}
    sy = Math.log( @labels[y]["N"] / @nL ) # here no smoothing
    aux[ y ] = sx + sy 
    aux
  end
end

#to_jsonObject



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

def to_json
  { "id" => "#{rand(10000)}#{Time.now.to_i}", "labels"=>@labels, "F"=>@features.to_a, "nf"=>@nF, "nl"=>@nL,"c"=>@c  }.to_json
end

#update!(fvect, label) ⇒ Object



16
17
18
19
20
21
# File 'lib/lite/classifier.rb', line 16

def update! fvect, label
  @labels[ label ] ||= { "xs" => {}, "N"=>0 }
  fvect.each{|k,v|  @features<<k; @labels[label]["nX"]||=@c ;@labels[ label ]["xs"][k] ||= @c; @labels[ label ]["xs"][k] += v;@labels[label]["nX"]+=v}
  @labels[ label ]["N"]+=1
  wrapup
end

#wrapupObject



48
49
50
51
52
# File 'lib/lite/classifier.rb', line 48

def wrapup
  @nF = @features.size
  @nL = @labels.keys.inject(0.0){|s,k| s += @labels[k]["N"]}
  @labels.keys.each{|k| @labels[k]["sF"] = @labels[k]["N"]+@c*@nF}
end