int svmpredict(double **values, int **indices, int rowNum, int *colNum,
               int isProb, const char *modelFile, int *labels, double **prob_estimates)
{
    if((model=svm_load_model(modelFile))==0)
    {
        LOGD("can't open model file %s\n",modelFile);
        exit(1);
    }

    x = (struct svm_node *) malloc(max_nr_attr*sizeof(struct svm_node));
    if(isProb)
    {
        if(svm_check_probability_model(model)==0)
        {
            LOGD("Model does not support probability estimates\n");
            exit(1);
        }
    }
    else
    {
        if(svm_check_probability_model(model)!=0)
            LOGD("Model supports probability estimates, but disabled in prediction.\n");
    }
    int r = predict(values, indices, rowNum, colNum, labels, prob_estimates, isProb);
    //LOGD("in svmpredict %.2f", prob_estimates[0]);
    svm_free_and_destroy_model(&model);
    free(x);
    free(line);
    return r;
}
Пример #2
0
/**
 * @brief Constructor of SVMPredictorSingle
 */
SVMPredictorSingle::SVMPredictorSingle(std::string path, std::string filename)
{
  if(path.size() == 0)
    path = SVM_MODEL;
  filename = path + filename;
  
  max_nr_attr = 64;
  predict_probability = true;

  if((model = svm_load_model(filename.c_str())) == 0)
    printf("[SVMPredictorSingle::SVMPredictorSingle] Error: Can't open model file: %s\n", filename.c_str());
  
#ifdef DEBUG
  else
    printf("[SVMPredictorSingle] Open model file: %s\n", filename.c_str());
#endif
    
  // allocate memory for model (and nodes)
  node = (struct svm_node *) malloc(max_nr_attr*sizeof(struct svm_node));

  if(predict_probability) {
    if(svm_check_probability_model(model) == 0) {
      printf("[SVMPredictorSingle::SVMPredictorSingle] Error: Model does not support probability estimates.\n");
      return;
    }
  }
  else {
    if(svm_check_probability_model(model) == 0)
      printf("[SVMPredictorSingle::SVMPredictorSingle] Warning: Model supports probability estimates, but disabled in prediction.");
  }
}
// [ref] ${LIBSVM_HOME}/svm-predict.c
void predict_example()
{
	const bool predict_probability = false;

	const std::string test_file_name("./data/machine_learning/svm/heart_scale");
	const std::string output_file_name("./data/machine_learning/svm/heart_scale.output");
	const std::string model_file_name("./data/machine_learning/svm/heart_scale.model");

	FILE *input = fopen(test_file_name.c_str(), "r");
	if(input == NULL)
	{
		std::cout << "can't open input file " << test_file_name << std::endl;
		return;
	}

	FILE *output = fopen(output_file_name.c_str(), "w");
	if(output == NULL)
	{
		std::cout << "can't open output file " << output_file_name << std::endl;
		return;
	}

	struct svm_model *model = svm_load_model(model_file_name.c_str());
	if (NULL == model)
	{
		std::cout << "can't open model file " << model_file_name << std::endl;
		return;
	}

	if (predict_probability)
	{
		if (svm_check_probability_model(model) == 0)
		{
			std::cout << "Model does not support probabiliy estimates" << std::endl;
			return;
		}
	}
	else
	{
		if (svm_check_probability_model(model) != 0)
			std::cout << "Model supports probability estimates, but disabled in prediction." << std::endl;
	}

	int max_nr_attr = 64;
	struct svm_node *x = (struct svm_node *)malloc(max_nr_attr * sizeof(struct svm_node));
	local::predict(input, output, model, predict_probability, max_nr_attr, x);

	free(x);
	fclose(input);
	fclose(output);

	svm_free_and_destroy_model(&model);
}
Пример #4
0
//
// Called to load a svm model file
//
void SVMPredict::loadSVMModel(const v8::FunctionCallbackInfo<v8::Value>& args){
  //v8::Isolate* isolate = v8::Isolate::GetCurrent();
  //v8::HandleScope scope(isolate);
  //bool ok;
  SVMPredict* svmPredict_instance =
  node::ObjectWrap::Unwrap<SVMPredict>(args.Holder());
  if (args.Length() != 1) {
    args.GetIsolate()->ThrowException(
                                      v8::String::NewFromUtf8(args.GetIsolate(),"Bad parameters"));
    return;
    //ThrowError("Wrong number of arguments!");
    //args.GetReturnValue().Set(v8::Undefined());
    //scope.Close(v8::Undefined());
  }
  if (!args[0]->IsString()) {
    args.GetIsolate()->ThrowException(
                                      v8::String::NewFromUtf8(args.GetIsolate(),"Wrong argument type!"));
    return;
    //ThrowError("Wrong arguments!");
    //scope.Close(v8::Undefined());
  }
  v8::String::Utf8Value File(args[0]);
  //std::string modelfile = FromV8<std::string>(args[0],&ok);
  std::string modelfile = *File;
  if ( !svmPredict_instance->load_svm_model(modelfile)){
    ThrowError(("Failed to load the SVM model file!"+modelfile).c_str());
    args.GetReturnValue().Set(false);
  }else{
    svmPredict_instance->isModelLoaded = true;
    svmPredict_instance->predict_probability =
    (svm_check_probability_model(svmPredict_instance->model)==0) ? false: true;
    args.GetReturnValue().Set(true);
  }
};
Пример #5
0
Datum pgm_svm_predict(PG_FUNCTION_ARGS){
    PGM_Matriz_Double *matrix = (PGM_Matriz_Double*) PG_GETARG_POINTER(0);
    PGM_Vetor_Double *vector_label = (PGM_Vetor_Double*) PG_GETARG_POINTER(1);
    struct svm_model *model = (struct svm_model*) PG_GETARG_POINTER(2);
    int predict_probability = PG_GETARG_INT32(3);
    MemoryContext contextoAnterior = MemoryContextSwitchTo( CurTransactionContext );
    PGM_Vetor_Double *predict_vector = pgm_create_PGM_Vetor_Double(vector_label->n_elems);
    MemoryContextSwitchTo( contextoAnterior );
    if(matrix->n_linhas != vector_label->n_elems)
        elog(ERROR,"Numero de labels nao correspondem ao numero de linhas da matrix");

    if(predict_probability){
		if(svm_check_probability_model(model)==0)
			elog(ERROR,"Model does not support probabiliy estimates\n");
	}else
		if(svm_check_probability_model(model)!=0)
			elog(INFO,"Model supports probability estimates, but disabled in prediction.\n");

    predict(matrix,vector_label,model,predict_probability,predict_vector);

    PG_RETURN_POINTER(predict_vector);
}
Пример #6
0
int init_predict(char *model_f_name){

	if((imp_model=svm_load_model(model_f_name))==0)
	{
		fprintf(stderr,"can't open model file %s\n",model_f_name);
		exit(1);
	}

	x = (struct svm_node *) malloc(max_nr_attr*sizeof(struct svm_node));
	if(predict_probability)
	{
		if(svm_check_probability_model(imp_model)==0)
		{
			fprintf(stderr,"Model does not support probabiliy estimates\n");
			exit(1);
		}
	}
	else
	{
		if(svm_check_probability_model(imp_model)!=0)
			printf("Model supports probability estimates, but disabled in prediction.\n");
	}
}
Пример #7
0
void mexFunction( int nlhs, mxArray *plhs[],
		 int nrhs, const mxArray *prhs[] )
{
	int prob_estimate_flag = 0;
	struct svm_model *model;

	if(nrhs > 4 || nrhs < 3)
	{
		exit_with_help();
		fake_answer(plhs);
		return;
	}

	if(!mxIsDouble(prhs[0]) || !mxIsDouble(prhs[1])) {
		mexPrintf("Error: label vector and instance matrix must be double\n");
		fake_answer(plhs);
		return;
	}

	if(mxIsStruct(prhs[2]))
	{
		const char *error_msg;

		// parse options
		if(nrhs==4)
		{
			int i, argc = 1;
			char cmd[CMD_LEN], *argv[CMD_LEN/2];

			// put options in argv[]
			mxGetString(prhs[3], cmd,  mxGetN(prhs[3]) + 1);
			if((argv[argc] = strtok(cmd, " ")) != NULL)
				while((argv[++argc] = strtok(NULL, " ")) != NULL)
					;

			for(i=1;i<argc;i++)
			{
				if(argv[i][0] != '-') break;
				if(++i>=argc)
				{
					exit_with_help();
					fake_answer(plhs);
					return;
				}
				switch(argv[i-1][1])
				{
					case 'b':
						prob_estimate_flag = atoi(argv[i]);
						break;
					default:
						mexPrintf("Unknown option: -%c\n", argv[i-1][1]);
						exit_with_help();
						fake_answer(plhs);
						return;
				}
			}
		}

		model = matlab_matrix_to_model(prhs[2], &error_msg);
		if (model == NULL)
		{
			mexPrintf("Error: can't read model: %s\n", error_msg);
			fake_answer(plhs);
			return;
		}

		if(prob_estimate_flag)
		{
			if(svm_check_probability_model(model)==0)
			{
				mexPrintf("Model does not support probabiliy estimates\n");
				fake_answer(plhs);
				svm_destroy_model(model);
				return;
			}
		}
		else
		{
			if(svm_check_probability_model(model)!=0)
				printf("Model supports probability estimates, but disabled in predicton.\n");
		}

		predict(plhs, prhs, model, prob_estimate_flag);
		// destroy model
		svm_destroy_model(model);
	}
	else
	{
		mexPrintf("model file should be a struct array\n");
		fake_answer(plhs);
	}

	return;
}
Пример #8
0
void svmpredict  (int    *decisionvalues,
		  int    *probability,

		  double *v, int *r, int *c,
		  int    *rowindex,
		  int    *colindex,
		  double *coefs,
		  double *rho,
		  int    *compprob,
		  double *probA,
		  double *probB,
		  int    *nclasses,
		  int    *totnSV,
		  int    *labels,
		  int    *nSV,
		  int    *sparsemodel,

		  int    *svm_type,
		  int    *kernel_type,
		  int    *degree,
		  double *gamma,
		  double *coef0,

		  double *x, int *xr,
		  int    *xrowindex,
		  int    *xcolindex,
		  int    *sparsex,
		  
		  double *ret,
		  double *dec,
		  double *prob)
{
    struct svm_model m;
    struct svm_node ** train;
    int i;
    
    /* set up model */
    m.l        = *totnSV;
    m.nr_class = *nclasses;
    m.sv_coef  = (double **) malloc (m.nr_class * sizeof(double*));
    for (i = 0; i < m.nr_class - 1; i++) {
      m.sv_coef[i] = (double *) malloc (m.l * sizeof (double));
      memcpy (m.sv_coef[i], coefs + i*m.l, m.l * sizeof (double));
    }
    
    if (*sparsemodel > 0)
	m.SV   = transsparse(v, *r, rowindex, colindex);
    else
	m.SV   = sparsify(v, *r, *c);
    
    m.rho      = rho;
    m.probA    = probA;
    m.probB    = probB;
    m.label    = labels;
    m.nSV      = nSV;

    /* set up parameter */
    m.param.svm_type    = *svm_type;
    m.param.kernel_type = *kernel_type;
    m.param.degree      = *degree;
    m.param.gamma       = *gamma;
    m.param.coef0       = *coef0;
    m.param.probability = *compprob;      

    m.free_sv           = 1;

    /* create sparse training matrix */
    if (*sparsex > 0)
	train = transsparse(x, *xr, xrowindex, xcolindex);
    else
	train = sparsify(x, *xr, *c);

    /* call svm-predict-function for each x-row, possibly using probability 
       estimator, if requested */
    if (*probability && svm_check_probability_model(&m)) {
      for (i = 0; i < *xr; i++)
	ret[i] = svm_predict_probability(&m, train[i], prob + i * *nclasses);
    } else {
      for (i = 0; i < *xr; i++)
	ret[i] = svm_predict(&m, train[i]);
    }

    /* optionally, compute decision values */
    if (*decisionvalues)
      for (i = 0; i < *xr; i++)
	svm_predict_values(&m, train[i], dec + i * *nclasses * (*nclasses - 1) / 2);

    /* clean up memory */
    for (i = 0; i < *xr; i++)
	free (train[i]);
    free (train);

    for (i = 0; i < *r; i++)
	free (m.SV[i]);
    free (m.SV);
    
    for (i = 0; i < m.nr_class - 1; i++)
      free(m.sv_coef[i]);
    free(m.sv_coef);
}	     
Пример #9
0
int main(int argc, char **argv)
{
	FILE *input, *output;
	int i;

	// parse options
	for(i=1;i<argc;i++)
	{
		if(argv[i][0] != '-') break;
		++i;
		switch(argv[i-1][1])
		{
			case 'b':
				predict_probability = atoi(argv[i]);
				break;
			default:
				fprintf(stderr,"Unknown option: -%c\n", argv[i-1][1]);
				exit_with_help();
		}
	}
	if(i>=argc-2)
		exit_with_help();
	
	input = fopen(argv[i],"r");
	if(input == NULL)
	{
		fprintf(stderr,"can't open input file %s\n",argv[i]);
		exit(1);
	}

	output = fopen(argv[i+2],"w");
	if(output == NULL)
	{
		fprintf(stderr,"can't open output file %s\n",argv[i+2]);
		exit(1);
	}

	if((model=svm_load_model(argv[i+1]))==0)
	{
		fprintf(stderr,"can't open model file %s\n",argv[i+1]);
		exit(1);
	}

	x = (struct svm_node *) malloc(max_nr_attr*sizeof(struct svm_node));
	if(predict_probability)
	{
		if(svm_check_probability_model(model)==0)
		{
			fprintf(stderr,"Model does not support probabiliy estimates\n");
			exit(1);
		}
	}
	else
	{
		if(svm_check_probability_model(model)!=0)
			printf("Model supports probability estimates, but disabled in prediction.\n");
	}
	predict(input,output);
	svm_free_and_destroy_model(&model);
	free(x);
	free(line);
	fclose(input);
	fclose(output);
	return 0;
}
Пример #10
0
int main(int argc, char **argv)
{
/* Polsarpro Variables */
	char range_file[1024], output_classif[1024],input_envi_file[1024], input_addr_file[1024];
	char output_dist[1024];
	char file_name[1024];
	int Nlig, Ncol, predict_probability;		/* Initial image nb of lines and rows */
	FILE *class_file, *range_restore, *in_file, *in_addr_file,  *output_dist_file, *prob_file;
	long Npolar; /* Number of polarimetrics indicators */

/* Libsvm Variables */
	int i;    

	if (argc >= 10) {
	  predict_probability =  atoi(argv[1]);
	  sprintf(file_name, "%s", argv[2]);
	  if((model=svm_load_model(file_name))==0)
	    {
		fprintf(stderr,"can't open model file %s\n",file_name);
		exit(1);
	    }
	  strcpy(range_file, argv[3]);
	  strcpy(output_classif, argv[4]);
	  strcpy(input_envi_file, argv[5]);
	  strcpy(input_addr_file, argv[6]);
	  Npolar = atoi(argv[7]);
	  Nlig =  atoi(argv[8]);
	  Ncol =  atoi(argv[9]);
	} else {
	fprintf(stderr,"svm-predict  prob svm_model_file range_file output_classif input_envi_file inpu_addr_file number_of_pol_ind num_b1 num_b2 ...\n");
		exit(1);
	}
	printf("\n\n\nfile_name : %s\n",file_name);
	printf("range_file : %s\n",range_file);
	printf("output_classif : %s \n",output_classif);
	printf(" input_envi_file : %s\n",input_envi_file);
	printf(" input_addr_file : %s\n",input_addr_file);
	printf(" Npolar : %ld\n",Npolar);
	printf(" Nlig : %d\n",Nlig);
	printf(" Ncol : %d\n",Ncol);

	//Test INPUT File
	sprintf(file_name, "%s", input_envi_file);
	if ((in_file = fopen(file_name, "rb")) == NULL)
		{
			fprintf(stderr,"Could not open input file : %s\n",file_name);
			exit(1);
		}
		
	//Test MASK File
	sprintf(file_name, "%s", input_addr_file);
	if ((in_addr_file = fopen(file_name, "rb")) == NULL)
		{
			fprintf(stderr,"Could not open addr file : %s\n",file_name);
			exit(1);
		}

	//Test OUTPUT File
	sprintf(file_name, "%s", output_classif);
	if ((class_file = fopen(file_name, "wb")) == NULL)
		{
			fprintf(stderr,"Could not open output file : %s\n",file_name);
			exit(1);
		}
		

	

		
		sprintf(output_dist, "%s_dist", output_classif);
	if ((output_dist_file = fopen(output_dist, "wb")) == NULL)
		{
			fprintf(stderr,"Could not open output file : %s\n",file_name);
			exit(1);
		}
	/*	float zero=0;
	i=0;
	while(i < Ncol * Nlig){
		fwrite(&zero, sizeof(float), 1, class_file);
		i++;
	}
	fclose(class_file);
	class_file = fopen(file_name, "w+");*/

	int num_band_file[Npolar];

//	for(i=9;i<argc;i++){
//		num_band_file[i-9] = atoi(argv[i]);
//	}

	//Test RANGE File
	sprintf(file_name, "%s", range_file);
	range_restore = fopen(file_name, "r");
	restore_scale_param(range_restore,Npolar);
	x = (struct svm_node *) malloc(max_nr_attr*sizeof(struct svm_node));
	if(predict_probability)
	{
		sprintf(file_name, "%s_prob", output_classif);
		if ((prob_file = fopen(file_name, "wb")) == NULL)
		{
			fprintf(stderr,"Could not open prob file : %s\n",file_name);
			exit(1);
		}	
		
		if(svm_check_probability_model(model)==0)
		{
			fprintf(stderr,"Model does not support probabiliy estimates\n");
			exit(1);
		}
	}
	else
	{
		if(svm_check_probability_model(model)!=0)
			printf("Model supports probability estimates, but disabled in prediction.\n");
	}
	printf("\n\nON Y EST!!!\n\n");
	predict(in_file,class_file, output_dist_file,prob_file, predict_probability, in_addr_file,Ncol, Nlig, Npolar);
	svm_destroy_model(model);
	free(x);
	free(line);
	fclose(in_file);
	fclose(in_addr_file);
	fclose(class_file);
	/*fclose(output_dist_file);*/
	/*fclose(prob_file);*/
	return 0;
}
Пример #11
0
JNIEXPORT jint JNICALL Java_LibSVMTest_doClassificationNative
        (JNIEnv *env, jobject obj, jobjectArray valuesArr,
         jobjectArray indicesArr, jint isProb, jintArray labelsArr, jdoubleArray probsArr) {
    int *labels = env->GetIntArrayElements(labelsArr, NULL);
    // initiate the arrays
    int nRow = env->GetArrayLength(valuesArr);
    double **probs = (double **) calloc(nRow, sizeof(double *));
    jfloatArray vrows = (jfloatArray) env->GetObjectArrayElement(valuesArr, 0);
    jintArray irows = (jintArray) env->GetObjectArrayElement(indicesArr, 0);
    jfloat *velement = env->GetFloatArrayElements(vrows, NULL);
    jint *ielement = env->GetIntArrayElements(irows, NULL);
    int colNum = env->GetArrayLength(vrows);
    probs[0] = env->GetDoubleArrayElements(probsArr, NULL);
    
    if(isProb)
    {
        if(svm_check_probability_model(model_F)==0)
        {
            fprintf(stderr, "Model does not support probabiliy estimates\n");
            exit(1);
        }
    }
    else
    {
        if(svm_check_probability_model(model_F)!=0)
            fprintf(stderr, "Model supports probability estimates, but disabled in prediction.\n");
    }

    if(isProb)
    {
        if (svm_type==NU_SVR || svm_type==EPSILON_SVR)
            fprintf(stderr, "Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=%g\n",svm_get_svr_probability(model_F));
        else
        {
            int *labels=(int *) malloc(nr_class*sizeof(int));
            svm_get_labels(model_F,labels);
        }
    }

    double predict_label=0;
    struct svm_node *x = (struct svm_node *) malloc(64*sizeof(struct svm_node));
    x = (struct svm_node *) realloc(x, (colNum+1)*sizeof(struct svm_node));

    for (int j = 0; j < colNum; j++)
    {
        x[j].index = velement[j];
        x[j].value = ielement[j];
    }
    x[colNum].index = -1;


    // Probability prediction
    if (isProb && (svm_type==C_SVC || svm_type==NU_SVC))
    {
        predict_label = svm_predict_probability(model_F,x,*probs);
        labels[0]=predict_label;

    }
    else { labels[0] = svm_predict(model_F,x);}

    env->ReleaseFloatArrayElements(vrows, velement, JNI_ABORT);
    env->ReleaseIntArrayElements(irows, ielement, JNI_ABORT);
    //added for fixing : JNI ERROR (app bug): local reference table overflow (max=512)
    env->DeleteLocalRef(vrows);
    env->DeleteLocalRef(irows);
    // release the one-D arrays and strings
    env->ReleaseIntArrayElements(labelsArr, labels, 0);
    //added for fixing : JNI ERROR (app bug): local reference table overflow (max=512)
    env->DeleteLocalRef(labelsArr);
    free(x);

    return 0;
}
Пример #12
0
int main(int argc, char *argv[]) {

    float labels[4] = {1.0, 1.0, -1.0, -1.0};
    cv::Mat labelsMat(4, 1, CV_32FC1, labels);
    float trainingData[4][2] = {{501, 10}, {255, 10},
                                {501, 255}, {10, 501}};
    cv::Mat trainingDataMat(4, 2, CV_32FC1, trainingData);
    
    svm_parameter param;
    param.svm_type = C_SVC;
    param.kernel_type = LINEAR;
    param.degree = 3;
    param.gamma = 0;
    param.coef0 = 0;
    param.nu = 0.5;
    param.cache_size = 100;
    param.C = 1;
    param.eps = 1e-6;
    param.p = 0.1;
    param.shrinking = 1;
    param.probability = 1;
    param.nr_weight = 0;
    param.weight_label = NULL;
    param.weight = NULL;
    
    svm_problem svm_prob_vector = libSVMWrapper(
       trainingDataMat, labelsMat, param);
    struct svm_model *model = new svm_model;
    if (svm_check_parameter(&svm_prob_vector, &param)) {
       std::cout << "ERROR" << std::endl;
    } else {
       model = svm_train(&svm_prob_vector, &param);
    }

    bool is_compute_probability = true;
    std::string model_file_name = "svm";
    bool save_model = true;
    if (save_model) {
       try {
          svm_save_model(model_file_name.c_str(), model);
          std::cout << "Model file Saved Successfully..." << std::endl;
       } catch(std::exception& e) {
          std::cout << e.what() << std::endl;
       }
    }


    bool is_probability_model = svm_check_probability_model(model);
    int svm_type = svm_get_svm_type(model);
    int nr_class = svm_get_nr_class(model);  // number of classes
    double *prob_estimates = new double[nr_class];

    cv::Vec3b green(0, 255, 0);
    cv::Vec3b blue(255, 0, 0);
    int width = 512, height = 512;
    cv::Mat image = cv::Mat::zeros(height, width, CV_8UC3);
    for (int i = 0; i < image.rows; ++i) {
       for (int j = 0; j < image.cols; ++j) {
          cv::Mat sampleMat = (cv::Mat_<float>(1, 2) << j, i);
              
          int dims = sampleMat.cols;
          svm_node* test_pt = new svm_node[dims];
          for (int k = 0; k < dims; k++) {
             test_pt[k].index = k + 1;
             test_pt[k].value = static_cast<double>(sampleMat.at<float>(0, k));
          }
          test_pt[dims].index = -1;

          float response = 0.0f;
          if (is_probability_model && is_compute_probability) {
             response = svm_predict_probability(model, test_pt, prob_estimates);
          } else {
             response = svm_predict(model, test_pt);
          }
          
          /*
          std::cout << "Predict: " << prob << std::endl;
          for (int y = 0; y < nr_class; y++) {
             std::cout << prob_estimates[y] << "  ";
          }std::cout <<  std::endl;
          */
          
          if (prob_estimates[0] > 0.5 || response == 1) {
             image.at<cv::Vec3b>(i, j)  = green;
          } else if (prob_estimates[1] >= 0.5 || response == -1) {
             image.at<cv::Vec3b>(i, j)  = blue;
          }
       }
    }
    cv::imshow("image", image);
    cv::waitKey(0);
    return 0;
}
Пример #13
0
bool SVMPredict::hasProb(){
  return (svm_check_probability_model(this->model)==0) ? false: true;
}