00001
00006
00007
00008
00009
00010
00011
00012
00161 #ifndef VL_PEGASOS_INSTANTIATING
00162
00163 #include "pegasos.h"
00164 #include "mathop.h"
00165 #include <math.h>
00166
00167 #define FLT VL_TYPE_FLOAT
00168 #define VL_PEGASOS_INSTANTIATING
00169 #include "pegasos.c"
00170
00171 #define FLT VL_TYPE_DOUBLE
00172 #define VL_PEGASOS_INSTANTIATING
00173 #include "pegasos.c"
00174
00175
00176 #else
00177
00178 #include "float.th"
00179
00180 VL_EXPORT void
00181 VL_XCAT(vl_pegasos_train_binary_svm_,SFX)(T * model,
00182 T const * data,
00183 vl_size dimension,
00184 vl_size numSamples,
00185 vl_int8 const * labels,
00186 double regularizer,
00187 double biasMultiplier,
00188 vl_uindex startingIteration,
00189 vl_size numIterations,
00190 VlRand * randomGenerator)
00191 {
00192 vl_uindex iteration ;
00193 vl_uindex i ;
00194 T const * x ;
00195 T acc, eta, y, scale = 1 ;
00196 double lambda = regularizer ;
00197 double sqrtLambda = sqrt(lambda) ;
00198
00199
00200 #if (FLT == VL_TYPE_FLOAT)
00201 VlFloatVectorComparisonFunction dotFn =
00202 #else
00203 VlDoubleVectorComparisonFunction dotFn =
00204 #endif
00205 VL_XCAT(vl_get_vector_comparison_function_,SFX)(VlKernelL2) ;
00206
00207 if (randomGenerator == NULL) randomGenerator = vl_get_rand() ;
00208
00209 assert(startingIteration >= 1) ;
00210
00211
00212
00213
00214
00215
00216 for (iteration = startingIteration ;
00217 iteration < startingIteration + numIterations ;
00218 ++ iteration) {
00219
00220 vl_uindex k = vl_rand_uindex(randomGenerator, numSamples) ;
00221 x = data + dimension * k ;
00222 y = labels[k] ;
00223
00224
00225 acc = dotFn(dimension, x, model) ;
00226 if (biasMultiplier) acc += biasMultiplier * model[dimension] ;
00227 acc *= scale ;
00228
00229
00230 eta = 1.0 / (iteration * lambda) ;
00231
00232 if (y * acc < (T) 1.0) {
00233
00234 T a = scale * (1 - eta * lambda) ;
00235 T b = y * eta ;
00236
00237 acc = 0 ;
00238 for (i = 0 ; i < dimension ; ++i) {
00239 model[i] = a * model[i] + b * x[i] ;
00240 acc += model[i] * model[i] ;
00241 }
00242 if (biasMultiplier) {
00243 model[dimension] = a * model[dimension] + b * biasMultiplier ;
00244 acc += model[dimension] * model[dimension] ;
00245 }
00246 scale = VL_MIN((T)1.0 / (sqrtLambda * sqrt(acc + VL_EPSILON_D)), (T)1.0) ;
00247 } else {
00248
00249 scale *= 1 - eta * lambda ;
00250 }
00251 }
00252
00253
00254 for (i = 0 ; i < dimension + (biasMultiplier ? 1 : 0) ; ++i) {
00255 model[i] *= scale ;
00256 }
00257 }
00258
00259
00260 #undef FLT
00261 #undef VL_PEGAOS_INSTANTIATING
00262 #endif
00263