Class: Eps::Evaluators::LightGBM

Inherits:
Object
  • Object
show all
Defined in:
lib/eps/evaluators/lightgbm.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(trees:, objective:, labels:, features:, text_features:) ⇒ LightGBM


6
7
8
9
10
11
12
# File 'lib/eps/evaluators/lightgbm.rb', line 6

def initialize(trees:, objective:, labels:, features:, text_features:)
  @trees = trees
  @objective = objective
  @labels = labels
  @features = features
  @text_features = text_features
end

Instance Attribute Details

#featuresObject (readonly)

Returns the value of attribute features


4
5
6
# File 'lib/eps/evaluators/lightgbm.rb', line 4

def features
  @features
end

Instance Method Details

#predict(data) ⇒ Object


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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/eps/evaluators/lightgbm.rb', line 14

def predict(data)
  rows = data.map(&:to_h)

  # sparse matrix
  @text_features.each do |k, v|
    encoder = TextEncoder.new(v)

    values = data.columns.delete(k)
    counts = encoder.transform(values)

    encoder.vocabulary.each do |word|
      data.columns[[k, word]] = [0] * values.size
    end

    counts.each_with_index do |xc, i|
      row = rows[i]
      row.delete(k)
      xc.each do |word, count|
        row[[k, word]] = count
      end
    end
  end

  case @objective
  when "regression"
    sum_trees(rows, @trees)
  when "binary"
    sum_trees(rows, @trees).map { |s| @labels[sigmoid(s) > 0.5 ? 1 : 0] }
  else
    tree_scores = []
    num_trees = @trees.size / @labels.size
    @trees.each_slice(num_trees).each do |trees|
      tree_scores << sum_trees(rows, trees)
    end
    data.size.times.map do |i|
      v = tree_scores.map { |s| s[i] }
      idx = v.map.with_index.max_by { |v2, _| v2 }.last
      @labels[idx]
    end
  end
end