Class: LibSVMLoader

Inherits:
Object
  • Object
show all
Defined in:
lib/libsvmloader.rb,
lib/libsvmloader/version.rb

Overview

module LibSVMLoader

VERSION = "0.1.0"

end

Defined Under Namespace

Modules: VERSION

Class Method Summary collapse

Class Method Details

.dump_libsvm_file(data, labels, filename, zero_based: false) ⇒ Object

Dump the dataset with the libsvm file format.

Parameters:

  • data (NMatrix)

    (n_samples x n_features) matrix consisting of feature vectors.

  • labels (NMatrix)

    (n_samples x 1) matrix consisting of labels or target values.

  • filename (String)

    A path to the output libsvm file.

  • zero_based (Boolean) (defaults to: false)

    Whether the column index starts from 0 (true) or 1 (false).



42
43
44
45
46
47
48
49
50
51
52
# File 'lib/libsvmloader.rb', line 42

def dump_libsvm_file(data, labels, filename, zero_based: false)
  n_samples = [data.rows, labels.rows].min
  label_type = detect_dtype(labels)
  value_type = detect_dtype(data)
  File.open(filename, 'w') do |file|
    n_samples.times do |n|
      file.puts(dump_libsvm_line(labels[n], data.row(n),
                                 label_type, value_type, zero_based))
    end
  end
end

.load_libsvm_file(filename, zero_based: false, stype: :yale, label_dtype: :int32, value_dtype: :float64) ⇒ Array<NMatrix>

Load a dataset with the libsvm file format into NMatrix.

Parameters:

  • filename (String)

    A path to a dataset file.

  • zero_based (Boolean) (defaults to: false)

    Whether the column index starts from 0 (true) or 1 (false).

  • stype (Symbol) (defaults to: :yale)

    The strorage type of the nmatrix consisting of feature vectors.

  • label_dtype (Symbol) (defaults to: :int32)

    The data type of the NMatrix consisting of labels or target values.

  • value_dtype (Symbol) (defaults to: :float64)

    The data type of the NMatrix consisting of feature vectors.

Returns:

  • (Array<NMatrix>)

    Returns array containing the (n_samples x n_features) matrix for feature vectors and (n_samples x 1) matrix for labels or target values.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/libsvmloader.rb', line 19

def load_libsvm_file(filename, zero_based: false, stype: :yale,
                     label_dtype: :int32, value_dtype: :float64)
  ftvecs = []
  labels = []
  n_features = 0
  File.open(filename, 'r') do |file|
    file.each_line do |line|
      label, ftvec, max_idx = parse_libsvm_line(line, zero_based)
      labels.push(label)
      ftvecs.push(ftvec)
      n_features = [n_features, max_idx].max
    end
  end
  [convert_to_nmatrix(ftvecs, n_features, value_dtype, stype),
   NMatrix.new([labels.size, 1], labels, dtype: label_dtype)]
end