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

Returns a new instance of 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, probabilities: false) ⇒ 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
55
56
57
58
59
60
61
# File 'lib/eps/evaluators/lightgbm.rb', line 14

def predict(data, probabilities: false)
  raise "Probabilities not supported" if probabilities && @objective == "regression"

  rows = data.map(&:to_h)

  # sparse matrix
  @text_features.each do |k, v|
    encoder = TextEncoder.new(**v)
    counts = encoder.transform(data.columns[k])

    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"
    prob = sum_trees(rows, @trees).map { |s| sigmoid(s) }
    if probabilities
      prob.map { |v| @labels.zip([1 - v, v]).to_h }
    else
      prob.map { |v| @labels[v > 0.5 ? 1 : 0] }
    end
  else
    tree_scores = []
    num_trees = @trees.size / @labels.size
    @trees.each_slice(num_trees).each do |trees|
      tree_scores << sum_trees(rows, trees)
    end
    rows.size.times.map do |i|
      v = tree_scores.map { |s| s[i] }
      if probabilities
        exp = v.map { |vi| Math.exp(vi) }
        sum = exp.sum
        @labels.zip(exp.map { |e| e / sum }).to_h
      else
        idx = v.map.with_index.max_by { |v2, _| v2 }.last
        @labels[idx]
      end
    end
  end
end