Class: NekonekoGen::LinearClassifier

Inherits:
Classifier show all
Defined in:
lib/nekoneko_gen/linear_classifier.rb

Direct Known Subclasses

Arow, PA

Instance Attribute Summary collapse

Attributes inherited from Classifier

#k

Instance Method Summary collapse

Methods inherited from Classifier

#default_iteration

Instance Attribute Details

#biasObject (readonly)

Returns the value of attribute bias.



7
8
9
# File 'lib/nekoneko_gen/linear_classifier.rb', line 7

def bias
  @bias
end

#wObject (readonly)

Returns the value of attribute w.



7
8
9
# File 'lib/nekoneko_gen/linear_classifier.rb', line 7

def w
  @w
end

Instance Method Details

#classify_method_code(lang) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/nekoneko_gen/linear_classifier.rb', line 65

def classify_method_code(lang)
  lang ||= :ruby
  case lang
  when :ruby
  else
    raise NotImplementedError
  end
  
  <<CODE
  def self.classify(vec)
if (K == 2)
  BIAS[0] + W[0].values_at(*vec).compact.reduce(0.0, :+) > 0.0 ? 0 : 1
else
  W.each_with_index.map {|w, i|
    [BIAS[i] + w.values_at(*vec).compact.reduce(0.0, :+), i]
  }.max.pop
end
  end
CODE
end

#dot(vec, w) ⇒ Object



8
9
10
11
12
13
14
15
16
# File 'lib/nekoneko_gen/linear_classifier.rb', line 8

def dot(vec, w)
  dot = 0.0
  vec.each do |k, v|
    if (a = w[k])
      dot += a * v
    end
  end
  dot
end

#features(i = -1)) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/nekoneko_gen/linear_classifier.rb', line 42

def features(i = -1)
  if (i < 0)
    w.reduce(0){|sum, v| sum + v.size }
  else
    w[i].size
  end
end

#parameter_code(lang, index_converter = lambda{|i| i}) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/nekoneko_gen/linear_classifier.rb', line 49

def parameter_code(lang, index_converter = lambda{|i| i})
  lang ||= :ruby
  case lang
  when :ruby
  else
    raise NotImplementedError
  end
  
  wvec = self.strip!.map {|w|
    w.reduce({}) {|h, kv| h[index_converter.call(kv[0])] = kv[1]; h }
  }
  <<CODE
  BIAS = #{self.bias.inspect}
  W = JSON.load(#{wvec.to_json.inspect})
CODE
end

#strip!Object



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

def strip!
  @w.each {|w|
    w.reject!{|k,v|
      if (v.abs < Float::EPSILON)
        # p v
        true
      else
        false
      end            
    }
  }
  @w
end

#update(vec, label) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/nekoneko_gen/linear_classifier.rb', line 30

def update(vec, label)
  loss = 0.0
  if (@k == 2)
    loss = update_at(0, vec, label)
  else
    s = 1.0 / @k
    @k.times do |i|
      loss += update_at(i, vec, label) * s
    end
  end
  loss
end