Module: Numo::Libsvm

Defined in:
ext/numo/libsvm/libsvmext.c,
lib/numo/libsvm/version.rb,
ext/numo/libsvm/libsvmext.c

Overview

Numo::Libsvm is a binding library for LIBSVM that handles dataset with Numo::NArray.

Defined Under Namespace

Modules: KernelType, SvmType

Constant Summary collapse

VERSION =

The version of Numo::Libsvm you are using.

'0.1.0'
LIBSVM_VERSION =

The version of LIBSVM used in backgroud library.

INT2NUM(LIBSVM_VERSION)

Class Method Summary collapse

Class Method Details

.cv(x, y, param, n_folds) ⇒ Numo::DFloat

Perform cross validation under given parameters. The given samples are separated to n_fols folds. The predicted labels or values in the validation process are returned.

Parameters:

  • x (Numo::DFloat)

    (shape: [n_samples, n_features]) The samples to be used for training the model.

  • y (Numo::DFloat)

    (shape: [n_samples]) The labels or target values for samples.

  • param (Hash)

    The parameters of an SVM model.

  • n_folds (Integer)

    The number of folds.

Returns:

  • (Numo::DFloat)

    (shape: [n_samples]) The predicted class label or value of each sample.



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'ext/numo/libsvm/libsvmext.c', line 100

static
VALUE cross_validation(VALUE self, VALUE x_val, VALUE y_val, VALUE param_hash, VALUE nr_folds)
{
  const int n_folds = NUM2INT(nr_folds);
  struct svm_problem* problem;
  struct svm_parameter* param;
  narray_t* x_nary;
  double* x_pt;
  double* y_pt;
  int i, j;
  int n_samples;
  int n_features;
  size_t t_shape[1];
  VALUE t_val;
  double* t_pt;

  /* Obtain C data structures. */
  if (CLASS_OF(x_val) != numo_cDFloat) {
    x_val = rb_funcall(numo_cDFloat, rb_intern("cast"), 1, x_val);
  }
  if (CLASS_OF(y_val) != numo_cDFloat) {
    y_val = rb_funcall(numo_cDFloat, rb_intern("cast"), 1, y_val);
  }
  if (!RTEST(nary_check_contiguous(x_val))) {
    x_val = nary_dup(x_val);
  }
  if (!RTEST(nary_check_contiguous(y_val))) {
    y_val = nary_dup(y_val);
  }
  GetNArray(x_val, x_nary);
  param = rb_hash_to_svm_parameter(param_hash);

  /* Initialize some variables. */
  n_samples = (int)NA_SHAPE(x_nary)[0];
  n_features = (int)NA_SHAPE(x_nary)[1];
  x_pt = (double*)na_get_pointer_for_read(x_val);
  y_pt = (double*)na_get_pointer_for_read(y_val);

  /* Prepare LIBSVM problem. */
  problem = ALLOC(struct svm_problem);
  problem->l = n_samples;
  problem->x = ALLOC_N(struct svm_node*, n_samples);
  problem->y = ALLOC_N(double, n_samples);
  for (i = 0; i < n_samples; i++) {
    problem->x[i] = ALLOC_N(struct svm_node, n_features + 1);
    for (j = 0; j < n_features; j++) {
      problem->x[i][j].index = j + 1;
      problem->x[i][j].value = x_pt[i * n_features + j];
    }
    problem->x[i][n_features].index = -1;
    problem->x[i][n_features].value = 0.0;
    problem->y[i] = y_pt[i];
  }

  /* Perform cross validation. */
  t_shape[0] = n_samples;
  t_val = rb_narray_new(numo_cDFloat, 1, t_shape);
  t_pt = (double*)na_get_pointer_for_write(t_val);
  svm_set_print_string_function(print_null);
  svm_cross_validation(problem, param, n_folds, t_pt);

  for (i = 0; i < n_samples; xfree(problem->x[i++]));
  xfree(problem->x);
  xfree(problem->y);
  xfree(problem);
  xfree_svm_parameter(param);

  return t_val;
}

.decision_function(x, param, model) ⇒ Numo::DFloat

Calculate decision values for given samples.

Parameters:

  • x (Numo::DFloat)

    (shape: [n_samples, n_features]) The samples to calculate the scores.

  • param (Hash)

    The parameters of the trained SVM model.

  • model (Hash)

    The model obtained from the training procedure.

Returns:

  • (Numo::DFloat)

    (shape: [n_samples, n_classes * (n_classes - 1) / 2]) The decision value of each sample.



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'ext/numo/libsvm/libsvmext.c', line 244

static
VALUE decision_function(VALUE self, VALUE x_val, VALUE param_hash, VALUE model_hash)
{
  struct svm_parameter* param;
  struct svm_model* model;
  struct svm_node* x_nodes;
  narray_t* x_nary;
  double* x_pt;
  size_t y_shape[2];
  VALUE y_val;
  double* y_pt;
  double* dec_values;
  int y_cols;
  int i, j;
  int n_samples;
  int n_features;

  /* Obtain C data structures. */
  if (CLASS_OF(x_val) != numo_cDFloat) {
    x_val = rb_funcall(numo_cDFloat, rb_intern("cast"), 1, x_val);
  }
  if (!RTEST(nary_check_contiguous(x_val))) {
    x_val = nary_dup(x_val);
  }
  GetNArray(x_val, x_nary);
  param = rb_hash_to_svm_parameter(param_hash);
  model = rb_hash_to_svm_model(model_hash);
  model->param = *param;

  /* Initialize some variables. */
  n_samples = (int)NA_SHAPE(x_nary)[0];
  n_features = (int)NA_SHAPE(x_nary)[1];

  if (model->param.svm_type == ONE_CLASS || model->param.svm_type == EPSILON_SVR || model->param.svm_type == NU_SVR) {
    y_shape[0] = n_samples;
    y_shape[1] = 1;
    y_val = rb_narray_new(numo_cDFloat, 1, y_shape);
  } else {
    y_shape[0] = n_samples;
    y_shape[1] = model->nr_class * (model->nr_class - 1) / 2;
    y_val = rb_narray_new(numo_cDFloat, 2, y_shape);
  }

  x_pt = (double*)na_get_pointer_for_read(x_val);
  y_pt = (double*)na_get_pointer_for_write(y_val);

  /* Predict values. */
  if (model->param.svm_type == ONE_CLASS || model->param.svm_type == EPSILON_SVR || model->param.svm_type == NU_SVR) {
    x_nodes = ALLOC_N(struct svm_node, n_features + 1);
    x_nodes[n_features].index = -1;
    x_nodes[n_features].value = 0.0;
    for (i = 0; i < n_samples; i++) {
      for (j = 0; j < n_features; j++) {
        x_nodes[j].index = j + 1;
        x_nodes[j].value = (double)x_pt[i * n_features + j];
      }
      svm_predict_values(model, x_nodes, &y_pt[i]);
    }
    xfree(x_nodes);
  } else {
    y_cols = (int)y_shape[1];
    dec_values = ALLOC_N(double, y_cols);
    x_nodes = ALLOC_N(struct svm_node, n_features + 1);
    x_nodes[n_features].index = -1;
    x_nodes[n_features].value = 0.0;
    for (i = 0; i < n_samples; i++) {
      for (j = 0; j < n_features; j++) {
        x_nodes[j].index = j + 1;
        x_nodes[j].value = (double)x_pt[i * n_features + j];
      }
      svm_predict_values(model, x_nodes, dec_values);
      for (j = 0; j < y_cols; j++) {
        y_pt[i * y_cols + j] = dec_values[j];
      }
    }
    xfree(x_nodes);
    xfree(dec_values);
  }

  xfree_svm_model(model);
  xfree_svm_parameter(param);

  return y_val;
}

.load_svm_model(filename) ⇒ Array

Load the SVM parameters and model from a text file with LIBSVM format.

Parameters:

  • filename (String)

    The path to a file to load.

Returns:

  • (Array)

    Array contains the SVM parameters and model.



410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# File 'ext/numo/libsvm/libsvmext.c', line 410

static
VALUE load_svm_model(VALUE self, VALUE filename)
{
  struct svm_model* model = svm_load_model(StringValuePtr(filename));
  VALUE res = rb_ary_new2(2);
  VALUE param_hash = Qnil;
  VALUE model_hash = Qnil;

  if (model) {
    param_hash = svm_parameter_to_rb_hash(&(model->param));
    model_hash = svm_model_to_rb_hash(model);
    svm_free_and_destroy_model(&model);
  }

  rb_ary_store(res, 0, param_hash);
  rb_ary_store(res, 1, model_hash);

  return res;
}

.predict(x, param, model) ⇒ Numo::DFloat

Predict class labels or values for given samples.

Parameters:

  • x (Numo::DFloat)

    (shape: [n_samples, n_features]) The samples to calculate the scores.

  • param (Hash)

    The parameters of the trained SVM model.

  • model (Hash)

    The model obtained from the training procedure.

Returns:

  • (Numo::DFloat)

    (shape: [n_samples]) The predicted class label or value of each sample.



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'ext/numo/libsvm/libsvmext.c', line 180

static
VALUE predict(VALUE self, VALUE x_val, VALUE param_hash, VALUE model_hash)
{
  struct svm_parameter* param;
  struct svm_model* model;
  struct svm_node* x_nodes;
  narray_t* x_nary;
  double* x_pt;
  size_t y_shape[1];
  VALUE y_val;
  double* y_pt;
  int i, j;
  int n_samples;
  int n_features;

  /* Obtain C data structures. */
  if (CLASS_OF(x_val) != numo_cDFloat) {
    x_val = rb_funcall(numo_cDFloat, rb_intern("cast"), 1, x_val);
  }
  if (!RTEST(nary_check_contiguous(x_val))) {
    x_val = nary_dup(x_val);
  }
  GetNArray(x_val, x_nary);
  param = rb_hash_to_svm_parameter(param_hash);
  model = rb_hash_to_svm_model(model_hash);
  model->param = *param;

  /* Initialize some variables. */
  n_samples = (int)NA_SHAPE(x_nary)[0];
  n_features = (int)NA_SHAPE(x_nary)[1];
  y_shape[0] = n_samples;
  y_val = rb_narray_new(numo_cDFloat, 1, y_shape);
  y_pt = (double*)na_get_pointer_for_write(y_val);
  x_pt = (double*)na_get_pointer_for_read(x_val);

  /* Predict values. */
  x_nodes = ALLOC_N(struct svm_node, n_features + 1);
  x_nodes[n_features].index = -1;
  x_nodes[n_features].value = 0.0;
  for (i = 0; i < n_samples; i++) {
    for (j = 0; j < n_features; j++) {
      x_nodes[j].index = j + 1;
      x_nodes[j].value = (double)x_pt[i * n_features + j];
    }
    y_pt[i] = svm_predict(model, x_nodes);
  }

  xfree(x_nodes);
  xfree_svm_model(model);
  xfree_svm_parameter(param);

  return y_val;
}

.predict_proba(x, param, model) ⇒ Numo::DFloat

Predict class probability for given samples. The model must have probability information calcualted in training procedure. The parameter ‘:probability’ set to 1 in training procedure.

Parameters:

  • x (Numo::DFloat)

    (shape: [n_samples, n_features]) The samples to predict the class probabilities.

  • param (Hash)

    The parameters of the trained SVM model.

  • model (Hash)

    The model obtained from the training procedure.

Returns:

  • (Numo::DFloat)

    (shape: [n_samples, n_classes]) Predicted probablity of each class per sample.



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
# File 'ext/numo/libsvm/libsvmext.c', line 340

static
VALUE predict_proba(VALUE self, VALUE x_val, VALUE param_hash, VALUE model_hash)
{
  struct svm_parameter* param;
  struct svm_model* model;
  struct svm_node* x_nodes;
  narray_t* x_nary;
  double* x_pt;
  size_t y_shape[2];
  VALUE y_val = Qnil;
  double* y_pt;
  double* probs;
  int i, j;
  int n_samples;
  int n_features;

  param = rb_hash_to_svm_parameter(param_hash);
  model = rb_hash_to_svm_model(model_hash);
  model->param = *param;

  if ((model->param.svm_type == C_SVC || model->param.svm_type == NU_SVC) && model->probA != NULL && model->probB != NULL) {
    /* Obtain C data structures. */
    if (CLASS_OF(x_val) != numo_cDFloat) {
      x_val = rb_funcall(numo_cDFloat, rb_intern("cast"), 1, x_val);
    }
    if (!RTEST(nary_check_contiguous(x_val))) {
      x_val = nary_dup(x_val);
    }
    GetNArray(x_val, x_nary);

    /* Initialize some variables. */
    n_samples = (int)NA_SHAPE(x_nary)[0];
    n_features = (int)NA_SHAPE(x_nary)[1];
    y_shape[0] = n_samples;
    y_shape[1] = model->nr_class;
    y_val = rb_narray_new(numo_cDFloat, 2, y_shape);
    x_pt = (double*)na_get_pointer_for_read(x_val);
    y_pt = (double*)na_get_pointer_for_write(y_val);

    /* Predict values. */
    probs = ALLOC_N(double, model->nr_class);
    x_nodes = ALLOC_N(struct svm_node, n_features + 1);
    x_nodes[n_features].index = -1;
    x_nodes[n_features].value = 0.0;
    for (i = 0; i < n_samples; i++) {
      for (j = 0; j < n_features; j++) {
        x_nodes[j].index = j + 1;
        x_nodes[j].value = (double)x_pt[i * n_features + j];
      }
      svm_predict_probability(model, x_nodes, probs);
      for (j = 0; j < model->nr_class; j++) {
        y_pt[i * model->nr_class + j] = probs[j];
      }
    }
    xfree(x_nodes);
    xfree(probs);
  }

  xfree_svm_model(model);
  xfree_svm_parameter(param);

  return y_val;
}

.save_svm_model(filename, param, model) ⇒ Boolean

Save the SVM parameters and model as a text file with LIBSVM format. The saved file can be used with the libsvm tools. Note that the svm_save_model saves only the parameters necessary for estimation with the trained model.

Parameters:

  • filename (String)

    The path to a file to save.

  • param (Hash)

    The parameters of the trained SVM model.

  • model (Hash)

    The model obtained from the training procedure.

Returns:

  • (Boolean)

    true on success, or false if an error occurs.



441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
# File 'ext/numo/libsvm/libsvmext.c', line 441

static
VALUE save_svm_model(VALUE self, VALUE filename, VALUE param_hash, VALUE model_hash)
{
  struct svm_parameter* param = rb_hash_to_svm_parameter(param_hash);
  struct svm_model* model = rb_hash_to_svm_model(model_hash);
  int res;

  model->param = *param;
  res = svm_save_model(StringValuePtr(filename), model);

  xfree_svm_model(model);
  xfree_svm_parameter(param);

  return res < 0 ? Qfalse : Qtrue;
}

.train(x, y, param) ⇒ Hash

Train the SVM model according to the given training data.

Parameters:

  • x (Numo::DFloat)

    (shape: [n_samples, n_features]) The samples to be used for training the model.

  • y (Numo::DFloat)

    (shape: [n_samples]) The labels or target values for samples.

  • param (Hash)

    The parameters of an SVM model.

Returns:

  • (Hash)

    The model obtained from the training procedure.



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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'ext/numo/libsvm/libsvmext.c', line 21

static
VALUE train(VALUE self, VALUE x_val, VALUE y_val, VALUE param_hash)
{
  struct svm_problem* problem;
  struct svm_parameter* param;
  narray_t* x_nary;
  double* x_pt;
  double* y_pt;
  int i, j;
  int n_samples;
  int n_features;
  struct svm_model* model;
  VALUE model_hash;

  /* Obtain C data structures. */
  if (CLASS_OF(x_val) != numo_cDFloat) {
    x_val = rb_funcall(numo_cDFloat, rb_intern("cast"), 1, x_val);
  }
  if (CLASS_OF(y_val) != numo_cDFloat) {
    y_val = rb_funcall(numo_cDFloat, rb_intern("cast"), 1, y_val);
  }
  if (!RTEST(nary_check_contiguous(x_val))) {
    x_val = nary_dup(x_val);
  }
  if (!RTEST(nary_check_contiguous(y_val))) {
    y_val = nary_dup(y_val);
  }
  GetNArray(x_val, x_nary);
  param = rb_hash_to_svm_parameter(param_hash);

  /* Initialize some variables. */
  n_samples = (int)NA_SHAPE(x_nary)[0];
  n_features = (int)NA_SHAPE(x_nary)[1];
  x_pt = (double*)na_get_pointer_for_read(x_val);
  y_pt = (double*)na_get_pointer_for_read(y_val);

  /* Prepare LIBSVM problem. */
  problem = ALLOC(struct svm_problem);
  problem->l = n_samples;
  problem->x = ALLOC_N(struct svm_node*, n_samples);
  problem->y = ALLOC_N(double, n_samples);
  for (i = 0; i < n_samples; i++) {
    problem->x[i] = ALLOC_N(struct svm_node, n_features + 1);
    for (j = 0; j < n_features; j++) {
      problem->x[i][j].index = j + 1;
      problem->x[i][j].value = x_pt[i * n_features + j];
    }
    problem->x[i][n_features].index = -1;
    problem->x[i][n_features].value = 0.0;
    problem->y[i] = y_pt[i];
  }

  /* Perform training. */
  svm_set_print_string_function(print_null);
  model = svm_train(problem, param);
  model_hash = svm_model_to_rb_hash(model);
  svm_free_and_destroy_model(&model);

  for (i = 0; i < n_samples; xfree(problem->x[i++]));
  xfree(problem->x);
  xfree(problem->y);
  xfree(problem);
  xfree_svm_parameter(param);

  return model_hash;
}