Open Detection  1.0
svmlight.h
1 /*
2 Copyright (c) 2015, Kripasindhu Sarkar
3 All rights reserved.
4 
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions are met:
7  * Redistributions of source code must retain the above copyright
8  notice, this list of conditions and the following disclaimer.
9  * Redistributions in binary form must reproduce the above copyright
10  notice, this list of conditions and the following disclaimer in the
11  documentation and/or other materials provided with the distribution.
12  * Neither the name of the copyright holder(s) nor the
13  names of its contributors may be used to endorse or promote products
14  derived from this software without specific prior written permission.
15 
16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
17 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER BE LIABLE FOR ANY
20 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 
27 
28  Original code under the following Apache License 2.0:
29  Changes - None
30 
31  ----------
32  This software is licensed under the Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html) Please find the Apache license 2.0 statement in the respective file alongside this software.
33 
34 Copyright 2015 Jan Hendriks
35 
36 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
37 
38  http://www.apache.org/licenses/LICENSE-2.0
39 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
40  ----------
41  */
42 
43 /**
44  * @file: svmlight.h
45  * @author: Jan Hendriks (dahoc3150 [at] gmail.com)
46  * @date: Created on 11. Mai 2011
47  * @brief: Wrapper interface for SVMlight,
48  * @see http://www.cs.cornell.edu/people/tj/svm_light/ for SVMlight details and terms of use
49  *
50  */
51 
52 #ifndef SVMLIGHT_H
53 #define SVMLIGHT_H
54 
55 #include <stdio.h>
56 #include <vector>
57 // svmlight related
58 // namespace required for avoiding collisions of declarations (e.g. LINEAR being declared in flann, svmlight and libsvm)
59 namespace svmlight {
60  extern "C" {
61  #include "3rdparty/svmlight/svm_common.h"
62  #include "3rdparty/svmlight/svm_learn.h"
63  }
64 }
65 
66 using namespace svmlight;
67 
68 class SVMlight {
69 private:
70  DOC** docs; // training examples
71  long totwords, totdoc, i; // support vector stuff
72  double* target;
73  double* alpha_in;
74  KERNEL_CACHE* kernel_cache;
75  MODEL* model; // SVM model
76 
77  SVMlight() {
78  // Init variables
79  alpha_in = NULL;
80  kernel_cache = NULL; // Cache not needed with linear kernel
81  model = (MODEL *) my_malloc(sizeof (MODEL));
82  learn_parm = new LEARN_PARM;
83  kernel_parm = new KERNEL_PARM;
84  // Init parameters
85  verbosity = 1; // Show some messages -v 1
86  learn_parm->alphafile[0] = ' '; // NULL; // Important, otherwise files with strange/invalid names appear in the working directory
87  // learn_parm->alphafile = NULL; // Important, otherwise files with strange/invalid names appear in the working directory
88  learn_parm->biased_hyperplane = 1;
89  learn_parm->sharedslack = 0; // 1
90  learn_parm->skip_final_opt_check = 0;
91  learn_parm->svm_maxqpsize = 10;
92  learn_parm->svm_newvarsinqp = 0;
93  learn_parm->svm_iter_to_shrink = 2; // 2 is for linear;
94  learn_parm->kernel_cache_size = 40;
95  learn_parm->maxiter = 100000;
96  learn_parm->svm_costratio = 1.0;
97  learn_parm->svm_costratio_unlab = 1.0;
98  learn_parm->svm_unlabbound = 1E-5;
99  learn_parm->eps = 0.1;
100  learn_parm->transduction_posratio = -1.0;
101  learn_parm->epsilon_crit = 0.001;
102  learn_parm->epsilon_a = 1E-15;
103  learn_parm->compute_loo = 0;
104  learn_parm->rho = 1.0;
105  learn_parm->xa_depth = 0;
106  // The HOG paper uses a soft classifier (C = 0.01), set to 0.0 to get the default calculation
107  learn_parm->svm_c = 0.01; // -c 0.01
108  learn_parm->type = REGRESSION;
109  learn_parm->remove_inconsistent = 0; // -i 0 - Important
110  kernel_parm->rbf_gamma = 1.0;
111  kernel_parm->coef_lin = 1;
112  kernel_parm->coef_const = 1;
113  kernel_parm->kernel_type = LINEAR; // -t 0
114  kernel_parm->poly_degree = 3;
115  }
116 
117  virtual ~SVMlight() {
118  // Cleanup area
119  // Free the memory used for the cache
120  if (kernel_cache)
121  kernel_cache_cleanup(kernel_cache);
122  free(alpha_in);
123  free_model(model, 0);
124  for (i = 0; i < totdoc; i++)
125  free_example(docs[i], 1);
126  free(docs);
127  free(target);
128  }
129 
130 public:
131  LEARN_PARM* learn_parm;
132  KERNEL_PARM* kernel_parm;
133 
134  static SVMlight* getInstance();
135 
136  inline void saveModelToFile(const std::string _modelFileName) {
137  write_model(const_cast<char*>(_modelFileName.c_str()), model);
138  }
139 
140  void loadModelFromFile(const std::string _modelFileName) {
141  this->model = read_model(const_cast<char*>(_modelFileName.c_str()));
142  }
143 
144  // read in a problem (in svmlight format)
145  void read_problem(char* filename) {
146  // Reads and parses the specified file
147  read_documents(filename, &docs, &target, &totwords, &totdoc);
148  }
149 
150  // Calls the actual machine learning algorithm
151  void train() {
152  svm_learn_regression(docs, target, totdoc, totwords, learn_parm, kernel_parm, &kernel_cache, model);
153  }
154 
155  /**
156  * Generates a single detecting feature vector (vec1) from the trained support vectors, for use e.g. with the HOG algorithm
157  * vec1 = sum_1_n (alpha_y*x_i). (vec1 is a 1 x n column vector. n = feature vector length)
158  * @param singleDetectorVector resulting single detector vector for use in openCV HOG
159  * @param singleDetectorVectorIndices dummy vector for this implementation
160  */
161  void getSingleDetectingVector(std::vector<float>& singleDetectorVector, std::vector<unsigned int>& singleDetectorVectorIndices) {
162  // Now we use the trained svm to retrieve the single detector vector
163  DOC** supveclist = model->supvec;
164  printf("Calculating single descriptor vector out of support vectors (may take some time)\n");
165  // Retrieve single detecting vector (v1) from returned ones by calculating vec1 = sum_1_n (alpha_y*x_i). (vec1 is a n x1 column vector. n = feature vector length)
166  singleDetectorVector.clear();
167  singleDetectorVector.resize(model->totwords, 0.);
168  printf("Resulting vector size %lu\n", singleDetectorVector.size());
169 
170  // Walk over every support vector
171  for (long ssv = 1; ssv < model->sv_num; ++ssv) { // Don't know what's inside model->supvec[0] ?!
172  // Get a single support vector
173  DOC* singleSupportVector = supveclist[ssv]; // Get next support vector
174  SVECTOR* singleSupportVectorValues = singleSupportVector->fvec;
175  WORD singleSupportVectorComponent;
176  // Walk through components of the support vector and populate our detector vector
177  for (unsigned long singleFeature = 0; singleFeature < model->totwords; ++singleFeature) {
178  singleSupportVectorComponent = singleSupportVectorValues->words[singleFeature];
179  singleDetectorVector.at(singleSupportVectorComponent.wnum-1) += (singleSupportVectorComponent.weight * model->alpha[ssv]);
180  }
181  }
182  }
183 
184  /**
185  * Return model detection threshold / bias
186  * @return detection threshold / bias
187  */
188  float getThreshold() const {
189  return model->b;
190  }
191 
192  const char* getSVMName() const {
193  return "SVMlight";
194  }
195 
196 };
197 
198 /// Singleton
200  static SVMlight theInstance;
201  return &theInstance;
202 }
203 
204 #endif /* SVMLIGHT_H */
const char * getSVMName() const
Definition: svmlight.h:192
void loadModelFromFile(const std::string _modelFileName)
Definition: svmlight.h:140
void read_problem(char *filename)
Definition: svmlight.h:145
KERNEL_PARM * kernel_parm
Definition: svmlight.h:132
static SVMlight * getInstance()
Singleton.
Definition: svmlight.h:199
void saveModelToFile(const std::string _modelFileName)
Definition: svmlight.h:136
LEARN_PARM * learn_parm
Definition: svmlight.h:131
void train()
Definition: svmlight.h:151
void getSingleDetectingVector(std::vector< float > &singleDetectorVector, std::vector< unsigned int > &singleDetectorVectorIndices)
Generates a single detecting feature vector (vec1) from the trained support vectors, for use e.g.
Definition: svmlight.h:161
float getThreshold() const
Return model detection threshold / bias.
Definition: svmlight.h:188