/* call-seq: problem.set_examples(labels, examples_array) Sets the examples and their label for a training set. The indices of the arrays are supposed to correspond. If they don't match in length an ArgumentError is raised. @return [Integer] number of examples in the traning set */ static VALUE cProblem_examples_set(VALUE obj,VALUE labels_ary,VALUE examples_ary) { struct svm_problem *prob; int i; int num = rx_ary_size(labels_ary); if(num != rx_ary_size(examples_ary)) { rb_raise(rb_eArgError, "Number of labels (%i) does not match number of features (%i).", num, rx_ary_size(examples_ary)); } Data_Get_Struct(obj, struct svm_problem, prob); if(prob->l > 0) { free(prob->y); for(i = 0; i < num; ++i) { free(*(prob->x+i)); } free(prob->x); } prob->y = calloc(num,sizeof(double)); if(prob->y == 0) { rb_raise(rb_eNoMemError, "%s:%i", __FILE__,__LINE__); } for(i = 0; i < num; ++i) { *(prob->y+i) = NUM2DBL(rb_ary_entry(labels_ary,i)); } prob->x = examples_ary_to_internal(examples_ary); prob->l = num; return INT2FIX(num); }
static struct svm_node *example_to_internal(VALUE example_ary) { struct svm_node *x, *node_struct; int example_ary_len, j; VALUE node; /* allocate memory for it */ example_ary_len = rx_ary_size(example_ary); x = (struct svm_node *)calloc(example_ary_len+1,sizeof(struct svm_node)); if(x == 0) { rb_raise(rb_eNoMemError, "on Libsvm::Node allocation" " %s:%i", __FILE__,__LINE__); } /* loop it's element nodes */ for(j = 0; j < example_ary_len; ++j) { node = rb_ary_entry(example_ary,j); Data_Get_Struct(node,struct svm_node,node_struct); memcpy(x+j,node_struct,sizeof(struct svm_node)); } /* add terminator */ memcpy(x+example_ary_len,&TERMINATOR,sizeof(struct svm_node)); return x; }