Class: XLearn::DMatrix

Inherits:
Object
  • Object
show all
Includes:
Utils
Defined in:
lib/xlearn/dmatrix.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, label: nil) ⇒ DMatrix

Returns a new instance of DMatrix.



5
6
7
8
9
10
11
12
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
39
40
# File 'lib/xlearn/dmatrix.rb', line 5

def initialize(data, label: nil)
  @handle = ::FFI::MemoryPointer.new(:pointer)

  if matrix?(data)
    nrow = data.row_count
    ncol = data.column_count
    flat_data = data.to_a.flatten
  elsif daru?(data)
    nrow, ncol = data.shape
    flat_data = data.map_rows(&:to_a).flatten
  elsif narray?(data)
    nrow, ncol = data.shape
    # TODO convert to SFloat and pass pointer
    # for better performance
    flat_data = data.flatten.to_a
  else
    nrow = data.count
    ncol = data.first.count
    flat_data = data.flatten
  end

  c_data = ::FFI::MemoryPointer.new(:float, flat_data.size)
  c_data.put_array_of_float(0, flat_data)

  if label
    label = label.to_a
    c_label = ::FFI::MemoryPointer.new(:float, label.size)
    c_label.put_array_of_float(0, label)
  end

  # TODO support this
  field_map = nil

  check_call FFI.XlearnCreateDataFromMat(c_data, nrow, ncol, c_label, field_map, @handle)
  ObjectSpace.define_finalizer(self, self.class.finalize(@handle))
end

Class Method Details

.finalize(pointer) ⇒ Object



46
47
48
49
# File 'lib/xlearn/dmatrix.rb', line 46

def self.finalize(pointer)
  # must use proc instead of stabby lambda
  proc { FFI.XlearnDataFree(pointer) }
end

Instance Method Details

#to_ptrObject



42
43
44
# File 'lib/xlearn/dmatrix.rb', line 42

def to_ptr
  @handle
end