Ejemplo n.º 1
0
bool SVMPredict::load_svm_model(std::string& path){

  this->model = svm_load_model(path.c_str());
  //this->print_model();
  //this->x = (struct svm_node *) malloc(max_nr_attr*sizeof(struct svm_node));
  return (this->model == nullptr)? false :true;
}
Ejemplo n.º 2
0
int pecker_svm_load_model(svm_model_s *svm_m, char *path, char *normal_para_path, uint32_t input_num, 
            void (*generate_feat_vector)(void *, size_t, struct svm_node *, uint32_t))
{
    int ret = PECKER_MCLA_OK;

    if(NULL == svm_m || generate_feat_vector == NULL)
        return PECKER_MCLA_NULL_POINTER;

    pecker_svm_free_model(svm_m);

    svm_m->svm = svm_load_model(path);
    if(svm_m->svm == NULL)
        return PECKER_MCLA_SVM_LOAD_MODEL_FAIL;

    svm_m->generate_feat_vector = generate_feat_vector;
    svm_m->input_num = input_num;

    if(normal_para_path)
    {
        svm_m->normalized = 1;
        ret = svm_load_normalize_para(svm_m, normal_para_path);
        if(ret != PECKER_MCLA_OK)
        {
            pecker_svm_free_model(svm_m);
        }
    }
        
    return ret;
}
Ejemplo n.º 3
0
void svm_train_and_test(const std::vector<feature_t> &feats, const std::vector<int> &labels, const char * model_file, std::ofstream &ofs)
{
	svm_model * model;
	if(_access(model_file, 0) == -1)
	{
		auto param = svm_fill_parameter();
		auto prob = svm_fill_problem(feats, labels);
		model = svm_train(prob, param);
		svm_save_model(model_file, model);
		auto acc = svm_test_acc(prob, model);
		svm_destroy_param(param);
		svm_free_problem(prob);
		std::cout<<model_file<<"  acc: "<<acc*100<<std::endl;
		ofs<<model_file<<"  acc: "<<acc*100<<std::endl;
	}
	else
	{
		model = svm_load_model(model_file);
		auto acc = svm_test_acc(feats, labels, model);
		std::cout<<model_file<<"  acc: "<<acc*100<<std::endl;
		ofs<<model_file<<"  acc: "<<acc*100<<std::endl;
	}
	//free
	svm_free_and_destroy_model(&model);
}
Ejemplo n.º 4
0
int main(int argc, char **argv)
{
	FILE *input;
	int rank;
	int nproc;
	int size;
	double *res, *conclusion;
	double time;
	input = fopen(argv[1],"r");
	if(input == NULL)
	{
		fprintf(stderr,"can't open input file %s\n",argv[1]);
		exit(1);
	}

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

	x = (struct svm_node *) malloc(max_nr_attr*sizeof(struct svm_node));
	
	res = predict(input, size);
	evaluate(res, size);
	svm_free_and_destroy_model(&model);
	free(x);
	free(line);
	fclose(input);
	return 0;
}
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;
}
Ejemplo n.º 6
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.");
  }
}
Ejemplo n.º 7
0
bool One_Class_SVM::load_model( const char * file_name ){

    struct svm_model * temp_model = svm_load_model( file_name );

    // If load_model fails, this temp_model will be a null pointer.
    // If it succeeds and the resulting model's svm_type is not ONE_CLASS,
    // it can't be used as a model for one_class_svm (for obvious reasons)
    // and we should consider it a failure.

    if ( temp_model == NULL )
    {
        return false;
    }
    else if ( temp_model->param.svm_type != ONE_CLASS )
    {
        // Memory was allocated as a result of the successful load_model function,
        // but the svm type is incompatible.  The pointer must be freed before
        // the function returns false.

        free ( temp_model );
        return false;
    }

    // If the method hasn't returned false yet, temp_model is both non-NULL and
    // has svm_type ONE_CLASS.  Set _model to temp_model, set trained to true,
    // and return trained.

    _model = temp_model;
    trained = true;
    _training_samples = _model->l;
    set_parameters( &(_model->param) );

    return trained;
}
Ejemplo n.º 8
0
void* jpcnn_load_predictor(const char* filename) {
  struct svm_model* model = svm_load_model(filename);
  SPredictorInfo* result = (SPredictorInfo*)(malloc(sizeof(SPredictorInfo)));
  result->model = model;
  result->problem = NULL;
  return result;
}
Ejemplo n.º 9
0
static VALUE cModel_class_load(VALUE cls, VALUE filename)
{
  struct svm_model *model;
  char *path;
  path = StringValueCStr(filename);
  model = svm_load_model(path);
  return Data_Wrap_Struct(cModel, 0, model_free, model);
}
Ejemplo n.º 10
0
	SVM( const std::string& libsvm_model_file, const std::string& libsvm_scale_file ):
		libsvm_model_file_(libsvm_scale_file), scale_info_(libsvm_scale_file)
		{
			if( (libsvm_model_ = svm_load_model( libsvm_model_file.c_str() ) ) == 0 ) {
				PRINT_ERROR( "Could not load LIBSVM model from " + libsvm_model_file );
				abort();
			}
		}
void ImgProcessing::init(string path) {
	if (model == 0) {
		cout << "load model" << endl;
		model = svm_load_model(path.c_str());
	} else {
		cout << "Error while loading model, abort process" << endl;
		exit(-1);
	}
}
Ejemplo n.º 12
0
struct svm_model *Clasificador::crea_svm(const char *f_svm, const char *f_med_desv, float *media, float *desv)
{
	svm_model  *svm;

	svm = svm_load_model(f_svm);
	le_media_desv(f_med_desv, media, desv);

	return(svm);
}
Ejemplo n.º 13
0
gcm::gcm(void)
{
	//Initial
	feature_ori = new double *[maxFrameNum];
	for (int i=0; i<maxFrameNum; i++)
	{
		feature_ori[i] = new double[featureDim];
	}

	gcm_subspace = new double*[featureDim];
	for (int i=0; i<featureDim; i++)
	{
		gcm_subspace[i] = new double[subspaceDim];
	}

	myModel = svm_load_model("..\\model\\model_UI4_noHandSeg_noPSVM");         //SVM model
	myModel_candi = svm_load_model("..\\model\\model_UI4_noHandSeg_PSVM");         //SVM model

	subFeaAll_model = newMatrix(featureDim, NClass*subSpaceDim*NTrainSample);  //Training Matrix
	fstream infile("..\\model\\subFeaAll_UI4_noHandSeg_noPSVM.dat",ios::in|ios::binary);
	for (int i=0; i<featureDim; i++)
	{
		for(int j=0;j<NClass*subSpaceDim*NTrainSample;j++)
		{
			infile.read((char*)&subFeaAll_model[i][j],sizeof(subFeaAll_model[i][j]));
		}
	}
	infile.close( );

	x = new svm_node[NClass*NTrainSample+1+1];                 //To release
	votewhj = new int[NClass*NTrainSample];               //To release

	nFrames = 0;
	nDimension = featureDim;

	prob_estimates = new double[NClass];

	subFea1 = newMatrix(featureDim, subSpaceDim);

	imgShow = cvCreateImage(cvSize(640, 480), 8,3);

	handSegmentVideo.init();
}
Ejemplo n.º 14
0
int cLibsvmLiveSink::myFinaliseInstance()
{
  int ap=0;

  int ret = cDataSink::myFinaliseInstance();
  if (ret==0) return 0;
  
  // TODO: binary model files...
  // load model
  SMILE_MSG(2,"loading LibSVM model for instance '%s' ...",getInstName()); 
  if((model=svm_load_model(modelfile))==0) {
    COMP_ERR("can't open libSVM model file '%s'",modelfile);
  }

  nClasses = svm_get_nr_class(model);
  svmType = svm_get_svm_type(model);

  if(predictProbability) {
    if ((svmType==NU_SVR) || (svmType==EPSILON_SVR)) {
      nClasses = 0;
      SMILE_MSG(2,"LibSVM prob. model (regression) for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=%g",svm_get_svr_probability(model));
    } else {
      labels=(int *) malloc(nClasses*sizeof(int));
      svm_get_labels(model,labels);

      SMILE_MSG(3,"LibSVM %i labels in model '%s':",nClasses,modelfile);
      int j;
      for(j=0;j<nClasses;j++)
        SMILE_MSG(3,"  Label[%i] : '%d'",j,labels[j]);
	}
  }

  //?? move this in front of above if() block ?
  if ((predictProbability)&&(nClasses>0))
    probEstimates = (double *) malloc(nClasses*sizeof(double));

  // load scale
  if((scale=svm_load_scale(scalefile))==0) {
	COMP_ERR("can't open libSVM scale file '%s'",scalefile);
  }

  // load selection
  loadSelection(fselection);

  //TODO: check compatibility of getLevelN() (possibly after selection), number of features in model, and scale
  
  if (nClasses>0) {
    // load class mapping
    loadClasses(classes);
  } else {
    if (classes != NULL) SMILE_IWRN(2,"not loading given class mapping file for regression SVR model (there are no classes...)!");
  }

  return ret;
}
Ejemplo n.º 15
0
bool CmySvmArth::LoadModel(const char* pPath)
{
	if(pPath==NULL)
		return false;
	if((model=svm_load_model(pPath))==0)
	{
		fprintf(stderr,"can't open model file %s\n",pPath);
		return false;
	}
	return true;
}
Ejemplo n.º 16
0
		bool PredictModel::CPredictModel::load(const FilePath& path)
		{
			if (m_model)
			{
				release();
			}

			m_model = svm_load_model(path.narrow().c_str());

			return (m_model != nullptr);
		}
// [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);
}
Ejemplo n.º 18
0
void InitUserFeelModel(){
      /*
	std::ostringstream ss;
	ss<<"a.model";
	std::string fileName = ss.str();
	svm_model* svmmodel = svm_load_model(fileName.c_str());
	svmModel = svmmodel;
	//*svmModel = svm_load_model(fileName.c_str());
*/
	std::string modelPath = "userFeel.model";
	svmModel_userFeel = svm_load_model(modelPath.c_str());
}
Ejemplo n.º 19
0
double UseSVM_Linear_FastEvaluationStructure(const char* modelfile,const int m,Array2dC<double>& result)
{
    svm_model* model = svm_load_model(modelfile);
    if(model==0)
    {
        std::cout<<"SVM model "<<modelfile<<" can not be loaded."<<std::endl;
        exit(-1);
    }
    double rho = UseSVM_Linear_FastEvaluationStructure(*model,m,result);
    svm_destroy_model(model);
    return rho;
}
void LibsvmSvm::load(std::string file) {
  std::string zipfile;
  if(!Util::unzip(file, zipfile)) {
    printf("Zipped model file doesn't exist.\n");
    throw -1;
  }
  _model = svm_load_model(zipfile.c_str());
  if(!_model) {
    printf("SVM Model file doesn't exist.\n");
    throw -1;
  }
  assert(_model != 0);
  //printf("Loaded %s\n", file.c_str());
}
Ejemplo n.º 21
0
void CSvmModel::Train( const string& strTrainData, const string& strValidData )
{
	Release();

	for( int i=0; i<GetOutputs(); i++ ){
		TransformToSvmData( strTrainData, GetInputs(), GetOutputs(), i, SVM_TRAIN_FILE );
		string strModelFile = CreateUniqueModelName();
		RunSvmTrain( SVM_TRAIN_FILE, /*parameters*/GetOptions(i), strModelFile );
		m_vcModelFiles.push_back( strModelFile );

		SVM_MODEL* model=svm_load_model( strModelFile.c_str() );
		m_vcModels.push_back( model );
	}
}
Ejemplo n.º 22
0
JNIEXPORT jint JNICALL Java_LibSVMTest_modelInitialize
        (JNIEnv *env, jclass cls, jstring modelFiles) {
    const char *modelFile = env->GetStringUTFChars(modelFiles, NULL);
    if ((model_F = svm_load_model(modelFile)) == 0) {
        fprintf(stderr, "can't open model file %s\n", modelFile);
        return -1;
    }
    env->ReleaseStringUTFChars(modelFiles, modelFile);
    env->DeleteLocalRef(modelFiles);

    svm_type=svm_get_svm_type(model_F);
    nr_class=svm_get_nr_class(model_F);
    printf("SVM Model Loaded\n");
    return 0;
}
Ejemplo n.º 23
0
int main(int argc, char *argv[])
{
	if(argc<3||argc>4){
		cerr<<"Usage: "<<argv[0]<<" xk|mail|freshman ImageFilePath "<<" [libsvm_model]"<<endl;
		cerr<<endl;
		cerr<<"Note that if the libsvm model file is not specified, program will use the default model of current working mode under svm model directory."<<endl;
		cerr<<endl;
		return 1;
	}
//	if (string(argv[1])!=s_arg_mode){
//		cerr << "ERROR: Please select working mode with -m" << endl;
//		return 1;
//	}
	if (string(argv[1]) == s_xk){
		trained_model = "model/xk.model";
	}else if (string(argv[1])==s_mail){
		trained_model = "model/mail.model";
	}else if (string(argv[1]) == s_freshman){
		trained_model = "model/freshman.model";
	}else{
		cerr << "ERROR: Unknown mode" << endl;
		return 1;
	}
	Mat src=imread(argv[2],CV_LOAD_IMAGE_UNCHANGED);
	if(src.empty()){
		cerr<<"ERROR: Could not load source file: "<<argv[2]<<endl;
		return 1;
	}
	if (argc == 4)	trained_model = argv[3]; 
	svm_model* model=svm_load_model(trained_model.c_str());
	if(model==0){
		cerr<<"ERROR: Could not load libsvm model: "<<trained_model<<endl;
		return 1;
	}
	if (string(argv[1]) == s_xk){
		SVMCapSolver_XK svmsolver(*model);
		cout << svmsolver.solve(src) << endl;
	}else if (string(argv[1]) == s_mail){
		SVMCapSolver_MAIL svmsolver(*model);
		cout << svmsolver.solve(src) << endl;
	}if (string(argv[1]) == s_freshman){
		SVMCapSolver_FRESHMAN svmsolver(*model);
		cout << svmsolver.solve(src) << endl;
	}

	return 0;
}
Ejemplo n.º 24
0
double SVM::classify(struct svm_node *data, char* filename_model)
{
	double predict_label;
	double *prob_estimates = NULL;
	int svm_type;
	int nr_class;

	// load feature file only once
	if(!this->_bFeatureFileLoaded)
	{
		if((this->_svmModel = svm_load_model(filename_model))==0)
		{
			printf("can't open model file %s\n",filename_model);
			return -99;
		}

		this->_bFeatureFileLoaded = true;
	}

	svm_type = svm_get_svm_type(this->_svmModel);
	nr_class = svm_get_nr_class(this->_svmModel);

	prob_estimates = (double *) malloc(nr_class*sizeof(double));

	if (svm_type==C_SVC || svm_type==NU_SVC)
	{
		predict_label = svm_predict_probability(this->_svmModel,data,prob_estimates);

	//	printf("%g",predict_label);

		//for(int k=0; k < nr_class; k++)
			//printf(" %g",prob_estimates[k]);

		//printf("\n");
	}
	else
	{
		predict_label = svm_predict(this->_svmModel, data);

		printf("%g\n",predict_label);
	}

	free(data);
	free(prob_estimates);

	return predict_label;
}
Ejemplo n.º 25
0
CateTeller::CateTeller() {
	// load Chinese word segment tools
	bool init_res = seg.init("dependency/jieba.dict.utf8");

	// word vector data
	conn = NULL;
	if( SQLITE_OK != sqlite3_open("dependency/new_dictionary.sqlite", &conn) ) {
		printf("can't open the database.");
		exit(-1);
	}

	// svm model
	svmModel = svm_load_model("dependency/trainingSet.txt.model");

	// filter
	filter = termFilter("dependency/symbelTerms.txt");
}
Ejemplo n.º 26
0
void classifyInput(FILE *f, char *modelfile) {
	struct svm_model *model;
	struct svm_node features[NOSAMPS+1];
	int samp[NOSAMPS];
	int rmin[NOSAMPS];
	int rmax[NOSAMPS];
	double *decVals;
	int x, noLabels, noDecVals;
	double r;
	char buff[1024];

	strcpy(buff, modelfile);
	strcat(buff, ".range");
	loadRangeFile(buff, rmin, rmax);

	strcpy(buff, modelfile);
	strcat(buff, ".model");
	model=svm_load_model(buff);
	if (model==NULL) {
		printf("Couldn't load model!\n");
		exit(0);
	}
	noLabels=svm_get_nr_class(model);
	noDecVals=noLabels*(noLabels-1)/2;
	decVals=malloc(sizeof(double)*noDecVals);

	while(1) {
		getSamples(f, samp);
		for (x=0; x<NOSAMPS; x++) {
			features[x].index=x;
			//rescale to [-1, 1]
			r=(samp[x]-rmin[x+1]);
			r=r/(rmax[x+1]-rmin[x+1]);
			r=(r*2)-1;
			features[x+1].value=r;
//			printf("%f ", features[x].value);
		}
//		printf("\n");
		features[x].index=-1;
		r=svm_predict_values(model,features,decVals);
		printf("prediction value: %f\n", r);
//		for (x=0; x<noDecVals; x++) printf("%f ", decVals[x]);
//		printf("\n");
	}
}
Ejemplo n.º 27
0
double UseSVM_Histogram_FastEvaluationStructure(const char* modelfile,const int m,const int upper_bound,Array2dC<double>& eval,svm_model** pmodel,const bool normalize)
// NOTE: If you want exactly the same result as libsvm (and usually better results) when -b 1 is used, set normalize to false
// if probability prediction of LIBSVM is not used (-b 0, which is default), the value of normalize does not have any effect.
// refer to hik-predict.cpp for example usage
{
    svm_model* model = svm_load_model(modelfile);
    if(model==0)
    {
        std::cout<<"SVM model "<<modelfile<<" can not be loaded."<<std::endl;
        exit(-1);
    }
    double rho = UseSVM_Histogram_FastEvaluationStructure(*model,m,upper_bound,eval,normalize);
    if(pmodel==NULL)
        svm_destroy_model(model);
    else
        *pmodel = model;
    return rho;
}
Ejemplo n.º 28
0
int main(){
	auto test_data = read_data("1_3");
	svm_model* model = svm_load_model("1_3_b_model");
	int nr_class = svm_get_nr_class(model);

	for (auto svmData : test_data){
		svm_node* nodes = AssignSVMNode(svmData);
		double* probEstimates = new double[nr_class];
		svm_predict_probability(model, nodes, probEstimates);
		for (int i = 0; i < nr_class; ++i){
			std::cout<<i<<":"<<probEstimates[i]<<"  ";
		}
		std::cout<<std::endl;
	}

	getchar();

	return 0;
}
Ejemplo n.º 29
0
int main () {
	svm_load_model("tu/model_reduced.txt");
	//print_model("model_get.txt");
	// hexagon_sim_init_timer();
	// hexagon_sim_start_timer();
	Real32 result = predict_sample("tu/testcase_200.txt");
	printf("%lf\n", result);
	// hexagon_sim_end_timer();
	// hexagon_sim_show_timer(stdout);


	// printf("test scaling\n");
	// Real32 xxx = 0.5;
	// Word16 a = round_real(xxx);
	// printf("%d\n", a);
	
	// printf("%f\n", min);
	// printf("%f\n", max);
	return 0;
}
HandTranslating::HandTranslating(QObject *parent) :
    QThread(parent)
{
    databaseFolderPath = "../Database/Main";
    modelFile = "databaseMain.model";
    string model_file_name = databaseFolderPath + "/" + modelFile;
    if((model=svm_load_model(model_file_name.c_str()))==0)
    {
        STOP = true;
        cout << "ko mo duoc model\n";
    } else {
        svm_type = svm_get_svm_type(model);
        nr_class = svm_get_nr_class(model);
        labels=(int *) malloc(nr_class*sizeof(int));
        svm_get_labels(model,labels);
        prob_estimates = (double *) malloc(nr_class * sizeof(double));
        STOP = false;
        enableToTranslate = false;
    }
}