Class: Xgboost::Booster

Inherits:
Object
  • Object
show all
Defined in:
lib/xgboost/booster.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBooster

Returns a new instance of Booster.



5
6
7
8
9
# File 'lib/xgboost/booster.rb', line 5

def initialize
  @handle = ::FFI::MemoryPointer.new(:pointer)
  FFI.XGBoosterCreate(nil, 0, @handle)
  ObjectSpace.define_finalizer(self, self.class.finalize(handle_pointer))
end

Class Method Details

.finalize(pointer) ⇒ Object



11
12
13
# File 'lib/xgboost/booster.rb', line 11

def self.finalize(pointer)
  proc { FFI.XGBoosterFree(pointer) }
end

Instance Method Details

#load(path) ⇒ Object



15
16
17
# File 'lib/xgboost/booster.rb', line 15

def load(path)
  FFI.XGBoosterLoadModel(handle_pointer, path)
end

#predict(input, missing: Float::NAN) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/xgboost/booster.rb', line 23

def predict(input, missing: Float::NAN)
  raise TypeError unless input.is_a?(Array)

  unless input_2d = input.first.is_a?(Array)
    input = [input]
  end

  out_len = ::FFI::MemoryPointer.new(:ulong_long)
  out_result = ::FFI::MemoryPointer.new(:pointer)

  data = ::FFI::MemoryPointer.new(:float, input.count * input.first.count)
  data.put_array_of_float(0, input.flatten)

  dmatrix = ::FFI::MemoryPointer.new(:pointer)
  FFI.XGDMatrixCreateFromMat(data, input.count, input.first.count, missing, dmatrix)

  FFI.XGBoosterPredict(handle_pointer, dmatrix.read_pointer, 0, 0, out_len, out_result)

  out = out_result.read_pointer.read_array_of_float(out_len.read_ulong_long)

  input_2d ? out : out.first
ensure
  FFI.XGDMatrixFree(dmatrix.read_pointer) if dmatrix
end

#save(path) ⇒ Object



19
20
21
# File 'lib/xgboost/booster.rb', line 19

def save(path)
  FFI.XGBoosterSaveModel(handle_pointer, path)
end