Class: Chainer::Functions::Evaluation::Accuracy

Inherits:
Chainer::Function show all
Defined in:
lib/chainer/functions/evaluation/accuracy.rb

Instance Attribute Summary

Attributes inherited from Chainer::Function

#inputs, #output_data, #outputs, #rank, #retain_after_backward

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Chainer::Function

#backward, #call, #forward_cpu, #retain_inputs, #retain_outputs

Constructor Details

#initialize(ignore_label: nil) ⇒ Accuracy

Returns a new instance of Accuracy.



9
10
11
# File 'lib/chainer/functions/evaluation/accuracy.rb', line 9

def initialize(ignore_label: nil)
  @ignore_label = ignore_label
end

Class Method Details

.accuracy(y, t, ignore_label: nil) ⇒ Object



5
6
7
# File 'lib/chainer/functions/evaluation/accuracy.rb', line 5

def self.accuracy(y, t, ignore_label: nil)
  self.new(ignore_label: ignore_label).(y, t)
end

Instance Method Details

#forward(inputs) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/chainer/functions/evaluation/accuracy.rb', line 13

def forward(inputs)
  y, t = inputs
  if @ignore_label
    mask = t.eq(@ignore_label)
    ignore_cnt = mask.count

    # this work
    pred = y.max_index(axis: 1).to_a.map.with_index { |val, idx| val - y.shape[1] * idx}
    pred = y.class[*pred].reshape(*t.shape)
    pred[mask] = @ignore_label
    count = pred.eq(t).count - ignore_cnt

    total = t.size - ignore_cnt

    if total == 0
      [y.class.cast(0.0)]
    else
      [y.class.cast(count.to_f / total)]
    end
  else
    pred = y.max_index(axis: 1).to_a.map.with_index { |val, idx| val - y.shape[1] * idx}
    pred = y.class[*pred].reshape(*t.shape)

    [y.class.cast(y.class[pred.eq(t)].mean)]
  end
end