-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
SVMLight.cpp
2569 lines (2248 loc) · 72.7 KB
/
SVMLight.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***********************************************************************/
/* */
/* SVMLight.cpp */
/* */
/* Author: Thorsten Joachims */
/* Date: 19.07.99 */
/* */
/* Copyright (c) 1999 Universitaet Dortmund - All rights reserved */
/* */
/* This software is available for non-commercial use only. It must */
/* not be modified and distributed without prior permission of the */
/* author. The author is not responsible for implications from the */
/* use of this software. */
/* */
/* THIS INCLUDES THE FOLLOWING ADDITIONS */
/* Generic Kernel Interfacing: Soeren Sonnenburg */
/* Parallizations: Soeren Sonnenburg */
/* Multiple Kernel Learning: Gunnar Raetsch, Soeren Sonnenburg, */
/* Alexander Zien, Marius Kloft, Chen Guohua */
/* Linadd Speedup: Gunnar Raetsch, Soeren Sonnenburg */
/* */
/***********************************************************************/
#include <shogun/lib/config.h>
#ifdef USE_SVMLIGHT
#include <shogun/io/SGIO.h>
#include <shogun/lib/Signal.h>
#include <shogun/mathematics/Math.h>
#include <shogun/lib/Time.h>
#include <shogun/mathematics/lapack.h>
#include <shogun/classifier/svm/SVMLight.h>
#include <shogun/lib/external/pr_loqo.h>
#include <shogun/kernel/Kernel.h>
#include <shogun/machine/KernelMachine.h>
#include <shogun/kernel/CombinedKernel.h>
#ifndef _WIN32
#include <unistd.h>
#endif
#include <shogun/base/Parallel.h>
#include <shogun/labels/BinaryLabels.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#ifdef HAVE_PTHREAD
#include <pthread.h>
#endif
using namespace shogun;
#ifndef DOXYGEN_SHOULD_SKIP_THIS
struct S_THREAD_PARAM_REACTIVATE_LINADD
{
CKernel* kernel;
float64_t* lin;
float64_t* last_lin;
int32_t* active;
int32_t* docs;
int32_t start;
int32_t end;
};
struct S_THREAD_PARAM_SVMLIGHT
{
float64_t * lin ;
float64_t* W;
int32_t start, end;
int32_t * active2dnum ;
int32_t * docs ;
CKernel* kernel ;
};
struct S_THREAD_PARAM_REACTIVATE_VANILLA
{
CKernel* kernel;
float64_t* lin;
float64_t* aicache;
float64_t* a;
float64_t* a_old;
int32_t* changed2dnum;
int32_t* inactive2dnum;
int32_t* label;
int32_t start;
int32_t end;
};
struct S_THREAD_PARAM_KERNEL
{
float64_t *Kval ;
int32_t *KI, *KJ ;
int32_t start, end;
CSVMLight* svmlight;
};
#endif // DOXYGEN_SHOULD_SKIP_THIS
void* CSVMLight::update_linear_component_linadd_helper(void* p)
{
S_THREAD_PARAM_SVMLIGHT* params = (S_THREAD_PARAM_SVMLIGHT*) p;
int32_t jj=0, j=0 ;
for (jj=params->start;(jj<params->end) && (j=params->active2dnum[jj])>=0;jj++)
params->lin[j]+=params->kernel->compute_optimized(params->docs[j]);
return NULL ;
}
void* CSVMLight::compute_kernel_helper(void* p)
{
S_THREAD_PARAM_KERNEL* params = (S_THREAD_PARAM_KERNEL*) p;
int32_t jj=0 ;
for (jj=params->start;jj<params->end;jj++)
params->Kval[jj]=params->svmlight->compute_kernel(params->KI[jj], params->KJ[jj]) ;
return NULL ;
}
CSVMLight::CSVMLight()
: CSVM()
{
init();
set_kernel(NULL);
}
CSVMLight::CSVMLight(float64_t C, CKernel* k, CLabels* lab)
: CSVM(C, k, lab)
{
init();
}
void CSVMLight::init()
{
//optimizer settings
primal=NULL;
dual=NULL;
init_margin=0.15;
init_iter=500;
precision_violations=0;
model_b=0;
verbosity=1;
opt_precision=DEF_PRECISION;
// svm variables
W=NULL;
model=SG_MALLOC(MODEL, 1);
learn_parm=SG_MALLOC(LEARN_PARM, 1);
model->supvec=NULL;
model->alpha=NULL;
model->index=NULL;
// MKL stuff
mymaxdiff=1 ;
mkl_converged=false;
}
CSVMLight::~CSVMLight()
{
SG_FREE(model->supvec);
SG_FREE(model->alpha);
SG_FREE(model->index);
SG_FREE(model);
SG_FREE(learn_parm);
// MKL stuff
SG_FREE(W);
// optimizer variables
SG_FREE(dual);
SG_FREE(primal);
}
bool CSVMLight::train_machine(CFeatures* data)
{
//certain setup params
mkl_converged=false;
verbosity=1 ;
init_margin=0.15;
init_iter=500;
precision_violations=0;
opt_precision=DEF_PRECISION;
strcpy (learn_parm->predfile, "");
learn_parm->biased_hyperplane= get_bias_enabled() ? 1 : 0;
learn_parm->sharedslack=0;
learn_parm->remove_inconsistent=0;
learn_parm->skip_final_opt_check=0;
learn_parm->svm_maxqpsize=get_qpsize();
learn_parm->svm_newvarsinqp=learn_parm->svm_maxqpsize-1;
learn_parm->maxiter=100000;
learn_parm->svm_iter_to_shrink=100;
learn_parm->svm_c=C1;
learn_parm->transduction_posratio=0.33;
learn_parm->svm_costratio=C2/C1;
learn_parm->svm_costratio_unlab=1.0;
learn_parm->svm_unlabbound=1E-5;
learn_parm->epsilon_crit=epsilon; // GU: better decrease it ... ??
learn_parm->epsilon_a=1E-15;
learn_parm->compute_loo=0;
learn_parm->rho=1.0;
learn_parm->xa_depth=0;
if (!kernel)
SG_ERROR("SVM_light can not proceed without kernel!\n")
if (data)
{
if (m_labels->get_num_labels() != data->get_num_vectors())
{
SG_ERROR("%s::train_machine(): Number of training vectors (%d) does"
" not match number of labels (%d)\n", get_name(),
data->get_num_vectors(), m_labels->get_num_labels());
}
kernel->init(data, data);
}
if (!kernel->has_features())
SG_ERROR("SVM_light can not proceed without initialized kernel!\n")
ASSERT(m_labels && m_labels->get_num_labels())
ASSERT(m_labels->get_label_type() == LT_BINARY)
ASSERT(kernel->get_num_vec_lhs()==m_labels->get_num_labels())
// in case of LINADD enabled kernels cleanup!
if (kernel->has_property(KP_LINADD) && get_linadd_enabled())
kernel->clear_normal() ;
// output some info
SG_DEBUG("threads = %i\n", parallel->get_num_threads())
SG_DEBUG("qpsize = %i\n", learn_parm->svm_maxqpsize)
SG_DEBUG("epsilon = %1.1e\n", learn_parm->epsilon_crit)
SG_DEBUG("kernel->has_property(KP_LINADD) = %i\n", kernel->has_property(KP_LINADD))
SG_DEBUG("kernel->has_property(KP_KERNCOMBINATION) = %i\n", kernel->has_property(KP_KERNCOMBINATION))
SG_DEBUG("kernel->has_property(KP_BATCHEVALUATION) = %i\n", kernel->has_property(KP_BATCHEVALUATION))
SG_DEBUG("kernel->get_optimization_type() = %s\n", kernel->get_optimization_type()==FASTBUTMEMHUNGRY ? "FASTBUTMEMHUNGRY" : "SLOWBUTMEMEFFICIENT" )
SG_DEBUG("get_solver_type() = %i\n", get_solver_type())
SG_DEBUG("get_linadd_enabled() = %i\n", get_linadd_enabled())
SG_DEBUG("get_batch_computation_enabled() = %i\n", get_batch_computation_enabled())
SG_DEBUG("kernel->get_num_subkernels() = %i\n", kernel->get_num_subkernels())
use_kernel_cache = !((kernel->get_kernel_type() == K_CUSTOM) ||
(get_linadd_enabled() && kernel->has_property(KP_LINADD)));
SG_DEBUG("use_kernel_cache = %i\n", use_kernel_cache)
if (kernel->get_kernel_type() == K_COMBINED)
{
for (index_t k_idx=0; k_idx<((CCombinedKernel*) kernel)->get_num_kernels(); k_idx++)
{
CKernel* kn = ((CCombinedKernel*) kernel)->get_kernel(k_idx);
// allocate kernel cache but clean up beforehand
kn->resize_kernel_cache(kn->get_cache_size());
SG_UNREF(kn);
}
}
kernel->resize_kernel_cache(kernel->get_cache_size());
// train the svm
svm_learn();
// brain damaged svm light work around
create_new_model(model->sv_num-1);
set_bias(-model->b);
for (int32_t i=0; i<model->sv_num-1; i++)
{
set_alpha(i, model->alpha[i+1]);
set_support_vector(i, model->supvec[i+1]);
}
// in case of LINADD enabled kernels cleanup!
if (kernel->has_property(KP_LINADD) && get_linadd_enabled())
{
kernel->clear_normal() ;
kernel->delete_optimization() ;
}
if (use_kernel_cache)
kernel->kernel_cache_cleanup();
return true ;
}
int32_t CSVMLight::get_runtime()
{
clock_t start;
start = clock();
return((int32_t)((float64_t)start*100.0/(float64_t)CLOCKS_PER_SEC));
}
void CSVMLight::svm_learn()
{
int32_t *inconsistent, i;
int32_t misclassified,upsupvecnum;
float64_t maxdiff, *lin, *c, *a;
int32_t iterations;
int32_t trainpos=0, trainneg=0 ;
ASSERT(m_labels)
SGVector<int32_t> lab=((CBinaryLabels*) m_labels)->get_int_labels();
int32_t totdoc=lab.vlen;
ASSERT(lab.vector && lab.vlen)
int32_t* label=SGVector<int32_t>::clone_vector(lab.vector, lab.vlen);
int32_t* docs=SG_MALLOC(int32_t, totdoc);
SG_FREE(W);
W=NULL;
count = 0 ;
if (kernel->has_property(KP_KERNCOMBINATION) && callback)
{
W = SG_MALLOC(float64_t, totdoc*kernel->get_num_subkernels());
for (i=0; i<totdoc*kernel->get_num_subkernels(); i++)
W[i]=0;
}
for (i=0; i<totdoc; i++)
docs[i]=i;
float64_t *xi_fullset; /* buffer for storing xi on full sample in loo */
float64_t *a_fullset; /* buffer for storing alpha on full sample in loo */
TIMING timing_profile;
SHRINK_STATE shrink_state;
timing_profile.time_kernel=0;
timing_profile.time_opti=0;
timing_profile.time_shrink=0;
timing_profile.time_update=0;
timing_profile.time_model=0;
timing_profile.time_check=0;
timing_profile.time_select=0;
/* make sure -n value is reasonable */
if((learn_parm->svm_newvarsinqp < 2)
|| (learn_parm->svm_newvarsinqp > learn_parm->svm_maxqpsize)) {
learn_parm->svm_newvarsinqp=learn_parm->svm_maxqpsize;
}
init_shrink_state(&shrink_state,totdoc,(int32_t)MAXSHRINK);
inconsistent = SG_MALLOC(int32_t, totdoc);
c = SG_MALLOC(float64_t, totdoc);
a = SG_MALLOC(float64_t, totdoc);
a_fullset = SG_MALLOC(float64_t, totdoc);
xi_fullset = SG_MALLOC(float64_t, totdoc);
lin = SG_MALLOC(float64_t, totdoc);
if (m_linear_term.vlen>0)
learn_parm->eps=get_linear_term_array();
else
{
learn_parm->eps=SG_MALLOC(float64_t, totdoc); /* equivalent regression epsilon for classification */
SGVector<float64_t>::fill_vector(learn_parm->eps, totdoc, -1.0);
}
learn_parm->svm_cost = SG_MALLOC(float64_t, totdoc);
SG_FREE(model->supvec);
SG_FREE(model->alpha);
SG_FREE(model->index);
model->supvec = SG_MALLOC(int32_t, totdoc+2);
model->alpha = SG_MALLOC(float64_t, totdoc+2);
model->index = SG_MALLOC(int32_t, totdoc+2);
model->at_upper_bound=0;
model->b=0;
model->supvec[0]=0; /* element 0 reserved and empty for now */
model->alpha[0]=0;
model->totdoc=totdoc;
model->kernel=kernel;
model->sv_num=1;
model->loo_error=-1;
model->loo_recall=-1;
model->loo_precision=-1;
model->xa_error=-1;
model->xa_recall=-1;
model->xa_precision=-1;
for (i=0;i<totdoc;i++) { /* various inits */
inconsistent[i]=0;
c[i]=0;
a[i]=0;
lin[i]=0;
if(label[i] > 0) {
learn_parm->svm_cost[i]=learn_parm->svm_c*learn_parm->svm_costratio*
fabs((float64_t)label[i]);
label[i]=1;
trainpos++;
}
else if(label[i] < 0) {
learn_parm->svm_cost[i]=learn_parm->svm_c*fabs((float64_t)label[i]);
label[i]=-1;
trainneg++;
}
else {
learn_parm->svm_cost[i]=0;
}
}
/* compute starting state for initial alpha values */
SG_DEBUG("alpha:%d num_sv:%d\n", m_alpha.vector, get_num_support_vectors())
if(m_alpha.vector && get_num_support_vectors()) {
if(verbosity>=1) {
SG_INFO("Computing starting state...")
}
float64_t* alpha = SG_MALLOC(float64_t, totdoc);
for (i=0; i<totdoc; i++)
alpha[i]=0;
for (i=0; i<get_num_support_vectors(); i++)
alpha[get_support_vector(i)]=get_alpha(i);
int32_t* index = SG_MALLOC(int32_t, totdoc);
int32_t* index2dnum = SG_MALLOC(int32_t, totdoc+11);
float64_t* aicache = SG_MALLOC(float64_t, totdoc);
for (i=0;i<totdoc;i++) { /* create full index and clip alphas */
index[i]=1;
alpha[i]=fabs(alpha[i]);
if(alpha[i]<0) alpha[i]=0;
if(alpha[i]>learn_parm->svm_cost[i]) alpha[i]=learn_parm->svm_cost[i];
}
if (use_kernel_cache)
{
if (callback &&
(!((CCombinedKernel*) kernel)->get_append_subkernel_weights())
)
{
CCombinedKernel* k = (CCombinedKernel*) kernel;
for (index_t k_idx=0; k_idx<k->get_num_kernels(); k_idx++)
{
CKernel* kn = k->get_kernel(k_idx);
for (i=0;i<totdoc;i++) // fill kernel cache with unbounded SV
if((alpha[i]>0) && (alpha[i]<learn_parm->svm_cost[i])
&& (kn->kernel_cache_space_available()))
kn->cache_kernel_row(i);
for (i=0;i<totdoc;i++) // fill rest of kernel cache with bounded SV
if((alpha[i]==learn_parm->svm_cost[i])
&& (kn->kernel_cache_space_available()))
kn->cache_kernel_row(i);
SG_UNREF(kn);
}
}
else
{
for (i=0;i<totdoc;i++) /* fill kernel cache with unbounded SV */
if((alpha[i]>0) && (alpha[i]<learn_parm->svm_cost[i])
&& (kernel->kernel_cache_space_available()))
kernel->cache_kernel_row(i);
for (i=0;i<totdoc;i++) /* fill rest of kernel cache with bounded SV */
if((alpha[i]==learn_parm->svm_cost[i])
&& (kernel->kernel_cache_space_available()))
kernel->cache_kernel_row(i);
}
}
compute_index(index,totdoc,index2dnum);
update_linear_component(docs,label,index2dnum,alpha,a,index2dnum,totdoc,
lin,aicache,NULL);
calculate_svm_model(docs,label,lin,alpha,a,c,
index2dnum,index2dnum);
for (i=0;i<totdoc;i++) { /* copy initial alphas */
a[i]=alpha[i];
}
SG_FREE(index);
SG_FREE(index2dnum);
SG_FREE(aicache);
SG_FREE(alpha);
if(verbosity>=1)
SG_DONE()
}
SG_DEBUG("%d totdoc %d pos %d neg\n", totdoc, trainpos, trainneg)
SG_DEBUG("Optimizing...\n")
/* train the svm */
iterations=optimize_to_convergence(docs,label,totdoc,
&shrink_state,inconsistent,a,lin,
c,&timing_profile,
&maxdiff,(int32_t)-1,
(int32_t)1);
if(verbosity>=1) {
if(verbosity==1)
{
SG_DONE()
SG_DEBUG("(%ld iterations)", iterations)
}
misclassified=0;
for (i=0;(i<totdoc);i++) { /* get final statistic */
if((lin[i]-model->b)*(float64_t)label[i] <= 0.0)
misclassified++;
}
SG_INFO("Optimization finished (%ld misclassified, maxdiff=%.8f).\n",
misclassified,maxdiff);
SG_INFO("obj = %.16f, rho = %.16f\n",get_objective(),model->b)
if (maxdiff>epsilon)
SG_WARNING("maximum violation (%f) exceeds svm_epsilon (%f) due to numerical difficulties\n", maxdiff, epsilon)
upsupvecnum=0;
for (i=1;i<model->sv_num;i++)
{
if(fabs(model->alpha[i]) >=
(learn_parm->svm_cost[model->supvec[i]]-
learn_parm->epsilon_a))
upsupvecnum++;
}
SG_INFO("Number of SV: %d (including %d at upper bound)\n",
model->sv_num-1,upsupvecnum);
}
shrink_state_cleanup(&shrink_state);
SG_FREE(label);
SG_FREE(inconsistent);
SG_FREE(c);
SG_FREE(a);
SG_FREE(a_fullset);
SG_FREE(xi_fullset);
SG_FREE(lin);
SG_FREE(learn_parm->eps);
SG_FREE(learn_parm->svm_cost);
SG_FREE(docs);
}
int32_t CSVMLight::optimize_to_convergence(int32_t* docs, int32_t* label, int32_t totdoc,
SHRINK_STATE *shrink_state,
int32_t *inconsistent,
float64_t *a, float64_t *lin, float64_t *c,
TIMING *timing_profile, float64_t *maxdiff,
int32_t heldout, int32_t retrain)
/* docs: Training vectors (x-part) */
/* label: Training labels/value (y-part, zero if test example for
transduction) */
/* totdoc: Number of examples in docs/label */
/* laern_parm: Learning paramenters */
/* kernel_parm: Kernel paramenters */
/* kernel_cache: Initialized/partly filled Cache, if using a kernel.
NULL if linear. */
/* shrink_state: State of active variables */
/* inconsistent: examples thrown out as inconstistent */
/* a: alphas */
/* lin: linear component of gradient */
/* c: right hand side of inequalities (margin) */
/* maxdiff: returns maximum violation of KT-conditions */
/* heldout: marks held-out example for leave-one-out (or -1) */
/* retrain: selects training mode (1=regular / 2=holdout) */
{
int32_t *chosen,*key,i,j,jj,*last_suboptimal_at,noshrink;
int32_t inconsistentnum,choosenum,already_chosen=0,iteration;
int32_t misclassified,supvecnum=0,*active2dnum,inactivenum;
int32_t *working2dnum,*selexam;
int32_t activenum;
float64_t criterion, eq;
float64_t *a_old;
int32_t t0=0,t1=0,t2=0,t3=0,t4=0,t5=0,t6=0; /* timing */
float64_t epsilon_crit_org;
float64_t bestmaxdiff;
float64_t worstmaxdiff;
int32_t bestmaxdiffiter,terminate;
bool reactivated=false;
float64_t *selcrit; /* buffer for sorting */
float64_t *aicache; /* buffer to keep one row of hessian */
QP qp; /* buffer for one quadratic program */
epsilon_crit_org=learn_parm->epsilon_crit; /* save org */
if(kernel->has_property(KP_LINADD) && get_linadd_enabled()) {
learn_parm->epsilon_crit=2.0;
/* caching makes no sense for linear kernel */
}
learn_parm->epsilon_shrink=2;
(*maxdiff)=1;
SG_DEBUG("totdoc:%d\n",totdoc)
chosen = SG_MALLOC(int32_t, totdoc);
last_suboptimal_at =SG_MALLOC(int32_t, totdoc);
key =SG_MALLOC(int32_t, totdoc+11);
selcrit =SG_MALLOC(float64_t, totdoc);
selexam =SG_MALLOC(int32_t, totdoc);
a_old =SG_MALLOC(float64_t, totdoc);
aicache =SG_MALLOC(float64_t, totdoc);
working2dnum =SG_MALLOC(int32_t, totdoc+11);
active2dnum =SG_MALLOC(int32_t, totdoc+11);
qp.opt_ce =SG_MALLOC(float64_t, learn_parm->svm_maxqpsize);
qp.opt_ce0 =SG_MALLOC(float64_t, 1);
qp.opt_g =SG_MALLOC(float64_t, learn_parm->svm_maxqpsize*learn_parm->svm_maxqpsize);
qp.opt_g0 =SG_MALLOC(float64_t, learn_parm->svm_maxqpsize);
qp.opt_xinit =SG_MALLOC(float64_t, learn_parm->svm_maxqpsize);
qp.opt_low=SG_MALLOC(float64_t, learn_parm->svm_maxqpsize);
qp.opt_up=SG_MALLOC(float64_t, learn_parm->svm_maxqpsize);
choosenum=0;
inconsistentnum=0;
if(!retrain) retrain=1;
iteration=1;
bestmaxdiffiter=1;
bestmaxdiff=999999999;
worstmaxdiff=1e-10;
terminate=0;
kernel->set_time(iteration); /* for lru cache */
for (i=0;i<totdoc;i++) { /* various inits */
chosen[i]=0;
a_old[i]=a[i];
last_suboptimal_at[i]=1;
if(inconsistent[i])
inconsistentnum++;
}
activenum=compute_index(shrink_state->active,totdoc,active2dnum);
inactivenum=totdoc-activenum;
clear_index(working2dnum);
/* repeat this loop until we have convergence */
CTime start_time;
mkl_converged=false;
#ifdef CYGWIN
for (;((iteration<100 || (!mkl_converged && callback) ) || (retrain && (!terminate))); iteration++){
#else
CSignal::clear_cancel();
for (;((!CSignal::cancel_computations()) && ((iteration<3 || (!mkl_converged && callback) ) || (retrain && (!terminate)))); iteration++){
#endif
if(use_kernel_cache)
kernel->set_time(iteration); /* for lru cache */
if(verbosity>=2) t0=get_runtime();
if(verbosity>=3) {
SG_DEBUG("\nSelecting working set... ")
}
if(learn_parm->svm_newvarsinqp>learn_parm->svm_maxqpsize)
learn_parm->svm_newvarsinqp=learn_parm->svm_maxqpsize;
i=0;
for (jj=0;(j=working2dnum[jj])>=0;jj++) { /* clear working set */
if((chosen[j]>=(learn_parm->svm_maxqpsize/
CMath::min(learn_parm->svm_maxqpsize,
learn_parm->svm_newvarsinqp)))
|| (inconsistent[j])
|| (j == heldout)) {
chosen[j]=0;
choosenum--;
}
else {
chosen[j]++;
working2dnum[i++]=j;
}
}
working2dnum[i]=-1;
if(retrain == 2) {
choosenum=0;
for (jj=0;(j=working2dnum[jj])>=0;jj++) { /* fully clear working set */
chosen[j]=0;
}
clear_index(working2dnum);
for (i=0;i<totdoc;i++) { /* set inconsistent examples to zero (-i 1) */
if((inconsistent[i] || (heldout==i)) && (a[i] != 0.0)) {
chosen[i]=99999;
choosenum++;
a[i]=0;
}
}
if(learn_parm->biased_hyperplane) {
eq=0;
for (i=0;i<totdoc;i++) { /* make sure we fulfill equality constraint */
eq+=a[i]*label[i];
}
for (i=0;(i<totdoc) && (fabs(eq) > learn_parm->epsilon_a);i++) {
if((eq*label[i] > 0) && (a[i] > 0)) {
chosen[i]=88888;
choosenum++;
if((eq*label[i]) > a[i]) {
eq-=(a[i]*label[i]);
a[i]=0;
}
else {
a[i]-=(eq*label[i]);
eq=0;
}
}
}
}
compute_index(chosen,totdoc,working2dnum);
}
else
{ /* select working set according to steepest gradient */
if(iteration % 101)
{
already_chosen=0;
if(CMath::min(learn_parm->svm_newvarsinqp, learn_parm->svm_maxqpsize-choosenum)>=4 &&
(!(kernel->has_property(KP_LINADD) && get_linadd_enabled())))
{
/* select part of the working set from cache */
already_chosen=select_next_qp_subproblem_grad(
label,a,lin,c,totdoc,
(int32_t)(CMath::min(learn_parm->svm_maxqpsize-choosenum,
learn_parm->svm_newvarsinqp)/2),
inconsistent,active2dnum,
working2dnum,selcrit,selexam,1,
key,chosen);
choosenum+=already_chosen;
}
choosenum+=select_next_qp_subproblem_grad(
label,a,lin,c,totdoc,
CMath::min(learn_parm->svm_maxqpsize-choosenum,
learn_parm->svm_newvarsinqp-already_chosen),
inconsistent,active2dnum,
working2dnum,selcrit,selexam,0,key,
chosen);
}
else { /* once in a while, select a somewhat random working set
to get unlocked of infinite loops due to numerical
inaccuracies in the core qp-solver */
choosenum+=select_next_qp_subproblem_rand(
label,a,lin,c,totdoc,
CMath::min(learn_parm->svm_maxqpsize-choosenum,
learn_parm->svm_newvarsinqp),
inconsistent,active2dnum,
working2dnum,selcrit,selexam,key,
chosen,iteration);
}
}
if(verbosity>=2) {
SG_INFO(" %ld vectors chosen\n",choosenum)
}
if(verbosity>=2) t1=get_runtime();
if (use_kernel_cache)
{
// in case of MKL w/o linadd cache each kernel independently
// else if linadd is disabled cache single kernel
if ( callback &&
(!((CCombinedKernel*) kernel)->get_append_subkernel_weights())
)
{
CCombinedKernel* k = (CCombinedKernel*) kernel;
for (index_t k_idx=0; k_idx<k->get_num_kernels(); k_idx++)
{
CKernel* kn = k->get_kernel(k_idx);
kn->cache_multiple_kernel_rows(working2dnum, choosenum);
SG_UNREF(kn);
}
}
else
kernel->cache_multiple_kernel_rows(working2dnum, choosenum);
}
if(verbosity>=2) t2=get_runtime();
if(retrain != 2) {
optimize_svm(docs,label,inconsistent,0.0,chosen,active2dnum,
totdoc,working2dnum,choosenum,a,lin,c,
aicache,&qp,&epsilon_crit_org);
}
if(verbosity>=2) t3=get_runtime();
update_linear_component(docs,label,active2dnum,a,a_old,working2dnum,totdoc,
lin,aicache,c);
if(verbosity>=2) t4=get_runtime();
supvecnum=calculate_svm_model(docs,label,lin,a,a_old,c,working2dnum,active2dnum);
if(verbosity>=2) t5=get_runtime();
for (jj=0;(i=working2dnum[jj])>=0;jj++) {
a_old[i]=a[i];
}
retrain=check_optimality(label,a,lin,c,totdoc,
maxdiff,epsilon_crit_org,&misclassified,
inconsistent,active2dnum,last_suboptimal_at,
iteration);
if(verbosity>=2) {
t6=get_runtime();
timing_profile->time_select+=t1-t0;
timing_profile->time_kernel+=t2-t1;
timing_profile->time_opti+=t3-t2;
timing_profile->time_update+=t4-t3;
timing_profile->time_model+=t5-t4;
timing_profile->time_check+=t6-t5;
}
/* checking whether optimizer got stuck */
if((*maxdiff) < bestmaxdiff) {
bestmaxdiff=(*maxdiff);
bestmaxdiffiter=iteration;
}
if(iteration > (bestmaxdiffiter+learn_parm->maxiter)) {
/* int32_t time no progress? */
terminate=1;
retrain=0;
SG_WARNING("Relaxing KT-Conditions due to slow progress! Terminating!\n")
SG_DEBUG("(iteration :%d, bestmaxdiffiter: %d, lean_param->maxiter: %d)\n", iteration, bestmaxdiffiter, learn_parm->maxiter )
}
noshrink= (get_shrinking_enabled()) ? 0 : 1;
if ((!callback) && (!retrain) && (inactivenum>0) &&
((!learn_parm->skip_final_opt_check) || (kernel->has_property(KP_LINADD) && get_linadd_enabled())))
{
t1=get_runtime();
SG_DEBUG("reactivating inactive examples\n")
reactivate_inactive_examples(label,a,shrink_state,lin,c,totdoc,
iteration,inconsistent,
docs,aicache,
maxdiff);
reactivated=true;
SG_DEBUG("done reactivating inactive examples (maxdiff:%8f eps_crit:%8f orig_eps:%8f)\n", *maxdiff, learn_parm->epsilon_crit, epsilon_crit_org)
/* Update to new active variables. */
activenum=compute_index(shrink_state->active,totdoc,active2dnum);
inactivenum=totdoc-activenum;
/* reset watchdog */
bestmaxdiff=(*maxdiff);
bestmaxdiffiter=iteration;
/* termination criterion */
noshrink=1;
retrain=0;
if((*maxdiff) > learn_parm->epsilon_crit)
{
SG_INFO("restarting optimization as we are - due to shrinking - deviating too much (maxdiff(%f) > eps(%f))\n", *maxdiff, learn_parm->epsilon_crit)
retrain=1;
}
timing_profile->time_shrink+=get_runtime()-t1;
if (((verbosity>=1) && (!(kernel->has_property(KP_LINADD) && get_linadd_enabled())))
|| (verbosity>=2)) {
SG_DONE()
SG_DEBUG("Number of inactive variables = %ld\n", inactivenum)
}
}
if((!retrain) && (learn_parm->epsilon_crit>(*maxdiff)))
learn_parm->epsilon_crit=(*maxdiff);
if((!retrain) && (learn_parm->epsilon_crit>epsilon_crit_org)) {
learn_parm->epsilon_crit/=4.0;
retrain=1;
noshrink=1;
}
if(learn_parm->epsilon_crit<epsilon_crit_org)
learn_parm->epsilon_crit=epsilon_crit_org;
if(verbosity>=2) {
SG_INFO(" => (%ld SV (incl. %ld SV at u-bound), max violation=%.5f)\n",
supvecnum,model->at_upper_bound,(*maxdiff));
}
mymaxdiff=*maxdiff ;
//don't shrink w/ mkl
if (((iteration % 10) == 0) && (!noshrink) && !callback)
{
activenum=shrink_problem(shrink_state,active2dnum,last_suboptimal_at,iteration,totdoc,
CMath::max((int32_t)(activenum/10),
CMath::max((int32_t)(totdoc/500),(int32_t) 100)),
a,inconsistent, c, lin, label);
inactivenum=totdoc-activenum;
if (use_kernel_cache && (supvecnum>kernel->get_max_elems_cache())
&& ((kernel->get_activenum_cache()-activenum)>CMath::max((int32_t)(activenum/10),(int32_t) 500))) {
kernel->kernel_cache_shrink(totdoc, CMath::min((int32_t) (kernel->get_activenum_cache()-activenum),
(int32_t) (kernel->get_activenum_cache()-supvecnum)),
shrink_state->active);
}
}
if (bestmaxdiff>worstmaxdiff)
worstmaxdiff=bestmaxdiff;
SG_ABS_PROGRESS(bestmaxdiff, -CMath::log10(bestmaxdiff), -CMath::log10(worstmaxdiff), -CMath::log10(epsilon), 6)
/* Terminate loop */
if (m_max_train_time > 0 && start_time.cur_time_diff() > m_max_train_time) {
terminate = 1;
retrain = 0;
}
} /* end of loop */
SG_DEBUG("inactive:%d\n", inactivenum)
if (inactivenum && !reactivated && !callback)
{
SG_DEBUG("reactivating inactive examples\n")
reactivate_inactive_examples(label,a,shrink_state,lin,c,totdoc,
iteration,inconsistent,
docs,aicache,
maxdiff);
SG_DEBUG("done reactivating inactive examples\n")
/* Update to new active variables. */
activenum=compute_index(shrink_state->active,totdoc,active2dnum);
inactivenum=totdoc-activenum;
/* reset watchdog */
bestmaxdiff=(*maxdiff);
bestmaxdiffiter=iteration;
}
//use this for our purposes!
criterion=compute_objective_function(a,lin,c,learn_parm->eps,label,totdoc);
CSVM::set_objective(criterion);
SG_FREE(chosen);
SG_FREE(last_suboptimal_at);
SG_FREE(key);
SG_FREE(selcrit);
SG_FREE(selexam);
SG_FREE(a_old);
SG_FREE(aicache);
SG_FREE(working2dnum);
SG_FREE(active2dnum);
SG_FREE(qp.opt_ce);
SG_FREE(qp.opt_ce0);
SG_FREE(qp.opt_g);
SG_FREE(qp.opt_g0);
SG_FREE(qp.opt_xinit);
SG_FREE(qp.opt_low);
SG_FREE(qp.opt_up);
learn_parm->epsilon_crit=epsilon_crit_org; /* restore org */
return(iteration);
}
float64_t CSVMLight::compute_objective_function(
float64_t *a, float64_t *lin, float64_t *c, float64_t* eps, int32_t *label,
int32_t totdoc)
/* Return value of objective function. */
/* Works only relative to the active variables! */
{
/* calculate value of objective function */
float64_t criterion=0;
for (int32_t i=0;i<totdoc;i++)
criterion=criterion+(eps[i]-(float64_t)label[i]*c[i])*a[i]+0.5*a[i]*label[i]*lin[i];
return(criterion);
}
void CSVMLight::clear_index(int32_t *index)
/* initializes and empties index */
{
index[0]=-1;
}
void CSVMLight::add_to_index(int32_t *index, int32_t elem)
/* initializes and empties index */
{
register int32_t i;
for (i=0;index[i] != -1;i++);
index[i]=elem;
index[i+1]=-1;
}
int32_t CSVMLight::compute_index(
int32_t *binfeature, int32_t range, int32_t *index)
/* create an inverted index of binfeature */
{
register int32_t i,ii;
ii=0;
for (i=0;i<range;i++) {
if(binfeature[i]) {
index[ii]=i;
ii++;
}