-
Notifications
You must be signed in to change notification settings - Fork 2
/
usvm.cpp
2282 lines (1942 loc) · 65.7 KB
/
usvm.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
/***********************************************************************
*
* UNIVERSVM IMPLEMENTATION
* Copyright (C) 2005 Fabian Sinz Max Planck Institute for Biological Cybernetics
*
* Includes parts of LUSH Lisp Universal Shell:
* Copyright (C) 2002 Leon Bottou, Yann Le Cun, AT&T Corp, NECI.
*
* Includes parts of libsvm.
*
*
* This program is free software except for military or military related use;
* If you don't come under the above exception you can redistribute it
* and/or modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA
*
***********************************************************************/
/* Version 1.22 - 04.10.2012 Matteo Roffilli - [email protected] */
/*
04.10.2012 Fix bug on set_alphas_b0 function (thanks to Ferdinand Kaiser <[email protected]>)
For every model trained with CCCP the value of b0 is calculated correctly during training, but later set to 0 in
set_alphas_b0. This problem is fixed by commenting the condition if (optimizer == SVQP)
such that b0 is also updated for CCCP optimizers.
*/
/* Version 1.21 - 08.01.2010 */
/*
16.10.2010 Fix bug for linux building on g++ (tested on version 4.3.2) (thanks to Anindya Halder)
*/
/* Version 1.2 - 16.10.2008 */
/*
16.10.2008 Fix bug (Matteo Roffilli - [email protected]):
enable sorting in split_file_load function
#include <algorithm>
*/
/*
16.10.2008 Fix bug (thanks to Enrico Angelini):
kgamma should be fixed at 1/k as in LIBSVM
kgamma=-1
*/
/*
16.10.2008 Fix bug (thanks to Cash Costello):
The documentation is not matching up with the code.
The documentation says to set -V to 2 and -o to 1 for the ramp loss.
I only see the ramp loss used if -V is set to 0.
if (sample_type(sv->Aperm[ip[i]]) == TRAINSAMP && use_universum == RAMPUNI){
*/
#ifdef _WIN32_
//Portability Update by Matteo Roffilli [email protected]
#define NAN ((float)1e-30) /* Not A Number - Indicate a wrong or non significant value -
Must always be tested, i.e. never assume that it's "close to zero, anyway" !
Could be any value, esp IEEE error or infinity formats. */
#endif
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>
#include "svqp2/svqp2.h"
#include "svqp2/vector.h"
#ifdef _WIN32_
int isnan(double x)
{
if(x<=NAN) return 1;
else return 0;
}
#endif
#ifdef MEX
#include "mex.h"
#endif
// various kernels
#define LINEAR 0
#define POLY 1
#define RBF 2
#define SIGMOID 3
#define CUSTOM 4
// different univserum training algorithms
#define MULTIUNI 1
#define RAMPUNI 2
char *kernel_type_table[] = {"linear","polynomial","rbf","sigmoid","custom"};
char *optimizer_table[] = {"svqp2","cccp"};
#define SVQP 0
#define CCCP 1
#define ONLINE 1
#define ONLINE_WITH_FINISHING 2
#define VERYBIG pow(10.0,100)
#define CCCP_TOL 0.0
#define TRAIN 0
#define TEST 1
#define UNIVERSUM 2
#define UNLABELED 3
#define SV 4
#define TRAINSAMP 0
#define UNIVESAMP 1
#define UNLABSAMP 2
#define EXTRASAMP 4
#define MAX_LOOPS 20 // maximum number of loops for tsvm training, should converge before this value, anyway..
/*********************** Split file storage class ******************/
class ID // class to hold split file indices and labels
{
public:
int x;
int y;
ID() : x(0), y(0) {}
ID(int x1,int y1) : x(x1), y(y1) {}
};
// IDs will be sorted by index, not by label.
bool operator<(const ID& x, const ID& y)
{
return x.x < y.x;
}
/*********************** Little Stopwatch class ******************/
using namespace std;
class stopwatch
{
public:
stopwatch() : start(std::clock()){} //start counting time
~stopwatch();
double get_time(){
clock_t total = clock()-start;;
return double(total)/CLOCKS_PER_SEC;
};
void reset(){
start= clock();
};
private:
std::clock_t start;
};
stopwatch::~stopwatch()
{
// clock_t total = clock()-start; //get elapsed time
//cout<<"total of ticks for this activity: "<<total<<endl;
//cout<<"Time(secs): "<<double(total)/CLOCKS_PER_SEC<<endl;
}
/*******************************************************************/
/********************** Variable Declarations *****************************/
double gap=0.05; // gap for universum
double s_ramp = -1; // parameter for ramp loss
double s_trans = 0; // parameter for transductive SVM
bool s_spec = 0; // did the user specify s?
int verbosity=1; // verbosity level, 0=off
/* Variable to store different parameters of data*/
double un_weight = NAN; // linear coefficient for the special kernel column
int mall; // train+test size
int m=0; // training set size
int m_map[5]; // map to the training set sizes
int max_index; // maximal index of the training/testing vectors
double maxa=0; // largest value of alpha
/* Regularizer variables*/
double C=1; // C, penalty on errors
double C2=1; // C, penalty on universum
double C3=-1.0; // C, penalty on unlabeled
int ker_ridge = 0;
/* Variables for data*/
vector <lasvm_sparsevector_t*> X; // feature vectors
vector <int> Y; // labels
vector < vector <int> > multi_Y; // labels for multiclass
vector <double> kparam; // kernel parameters
vector <double> x_square; // norms of input vectors, used for RBF
vector <int> data_map[5]; // maps to the indices of train/test/... data
vector <double> global_ext_K; // additional kernel column for transduction
vector <int> labels; // all different labels, that occured in the datafiles
/* Variables for the model*/
vector <double> alpha; // alpha_i, SV weights
vector< vector<double> > multi_alpha; // alpha_ij for multiclass
vector<double> multi_b0; // thresholds for multiclass
double b0; // threshold
int use_b0=1; // use threshold via constraint \sum a_i y_i =0
int kernel_type=LINEAR; // specifies the type of the kernel
vector <double> beta; // vector with betas for transduction
vector <double> Yest; // temporary vector to store the prediction
vector < vector<double> > D; // 2D vector to store the function values of the test points
double C_star = VERYBIG; // C, penalty for the alpha of the special kernel column
/* Algorithm parameters*/
double degree=3,kgamma=-1,coef0=0; // kernel params
int cl=2; // number of classes
int optimizer=SVQP; // strategy of optimization
int folds=-1; // if folds=-1 --> no cross validation, else do folds fold CV
int use_ext_K = 0; // use extra kernel column?
int do_multi_class = 0; // do multiclass?
int prob_size = 0; // size of the problem (different to dataset size!)
int fill_level = 0; // temporary variable for setting up the problem
/* Programm behaviour*/
char report_file_name[1024]; // filename for the training report
char split_file_name[1024]="\0"; // filename for the splits
int cache_size=256; // 256Mb cache size as default
double epsgr=1e-3; // tolerance on gradients
long long kcalcs=0; // number of kernel evaluations
int binary_files=0;
int use_universum = 0; // specifies the training algorithm used for universum
vector <ID> splits;
bool justtest = 0; // if justtest, then universvm tests on the specified model
/* Other */
int seed=0;
vector<double> training_time;
///****************************** Functions *************************************/
void exit_with_help()
{
fprintf(stdout,
"\nUSAGE: usvm [options] training_set_file [model_file]\n\n"
"\n"
"Trains a SVM, TSVM or USVM with specified parameters. If a model_file is\n"
"specified after the training_set_file, then the learnt model will be stored\n"
"there. If the model_file is supplied by the switch -F, then UniverSVM will\n"
"test the specified model on the data that is supplied as training data and \n"
"the test data supplied by -T. So\n"
" universvm [options] -T testfile trainfile\n"
"has the same effect as doing\n"
" universvm [options] trainfile model \n"
" universvm [options] -F model testfile\n"
"\n"
"OPTIONS:\n"
"FILE/DATA OPTIONS:\n"
"-T test_set_file: test model on test set\n"
"-U universum_file : use universum (it's also possible to include universum points \n"
" with label -2 in the training file)\n"
"-F model_file : Test the model stored in model_file on training AND test data (specified by -T)\n"
"-u unlabeled_data_file : use unlabeled data (transductive SVM).\n"
" (it's also possible to include unlabeled points\n"
" with label -3 in the training file)\n"
"-B file format : files are stored in the following format:\n"
" 0 -- libsvm ascii format (default)\n"
" 1 -- binary format\n"
" 2 -- split file format\n"
"-f file : output report file to given destination\n"
"-D file : output function values on test set(s) to given destination\n"
"\nOPTIMIZATION OPTIONS:\n"
"-V universum variant:\n"
" 0 -- Standard universum training (default)\n"
" 1 -- Train SVM with universum by making it a 3-class multiclass\n"
" problem and adding the decision rules for {+1,U} vs. -1 and\n"
" {-1,U} vs. +1 (0=off default)\n"
" This switch works only for binary at the moment.\n"
" 2 -- Train universum with ramp loss. This option requires \"-o 1\".\n"
"-o optimizer: set different optimizers\n"
" 0 -- quadratic programm\n"
" 1 -- convex concave procedure (if you choose a transductive SVM,\n"
" this option will be chosen automatically)\n"
"-G gap : set gap parameter for universum (default 0.05) \n"
"-I use_ridge : Add the ridge 1/C to the kernel matrix.\n"
"-r coef0 : set coef0 in kernel function (default 0)\n"
"-c cost : set the parameter C of C-SVC (default 1)\n"
"-C cost : set the parameter C for universum points\n"
"-a cost : set the parameter C for balancing constraint\n"
"-z cost : set the parameter C for unlabeled points (defaul is z = (l/u)*C\n"
" where l is the number of training points and u is the number of\n"
" unlabeled points).\n"
"-m cachesize : set cache memory size in MB (default 256)\n"
"-e epsilon : set tolerance of termination criterion (default 0.001)\n"
"-s s : s parameter for ramp loss (default: -1 )\n"
"-S s : s parameter for transductive SVM loss (default: 0)\n"
"\nMODEL OPTIONS:\n"
"-t kernel_type : set type of kernel function (default 0)\n"
" 0 -- linear: u'*v\n"
" 1 -- polynomial: (gamma*u'*v + coef0)^degree\n"
" 2 -- radial basis function: exp(-gamma*|u-v|^2)\n"
" 3 -- sigmoid: tanh(gamma*u'*v + coef0)\n"
" 4 -- custom: k(x_i,x_j) = X(i,j)\n"
"-d degree : set degree in kernel function (default 3)\n"
"-g gamma : set gamma in kernel function (default 1/k)\n"
"-b bias: use constraint sum alpha_i y_i =0 (default 1=on)\n"
"-w weight: set the coefficient for the \"extra example\" (balacing constraint)\n"
" in the linear part of the optimization problem (default = sum(y_i)) \n"
"-v n : do cross validation with n folds\n"
"-M k : perform a multiclass training on k classes labeled with k different\n"
"\tintegers >= 0 (default: 0)\n"
);
exit(1);
}
// ******************* Parse Functions **************************************
void parse_command_line(int argc, char **argv, char *input_file_name, char *universum_file_name, char *testset_file_name, char *unlabeled_file_name, char *model_file_name, char *fval_file_name)
{
int i;
// parse options
for(i=1;i<argc;i++)
{
if(argv[i][0] != '-') break;
++i;
switch(argv[i-1][1])
{
case 'o':
optimizer = atoi(argv[i]);
break;
case 't':
kernel_type = atoi(argv[i]);
break;
case 's':
s_ramp = atof(argv[i]);
break;
case 'S':
s_trans = atof(argv[i]);
break;
case 'T':
strcpy(testset_file_name, argv[i]);
break;
case 'D':
strcpy(fval_file_name, argv[i]);
break;
case 'f':
strcpy(report_file_name, argv[i]);
break;
case 'P':
strcpy(split_file_name, argv[i]);
break;
case 'u':
strcpy(unlabeled_file_name, argv[i]);
break;
case 'U':
strcpy(universum_file_name, argv[i]);
break;
case 'V':
use_universum = atoi(argv[i]);
break;
case 'B':
binary_files= atoi(argv[i]);
break;
case 'd':
degree = atof(argv[i]);
break;
case 'g':
kgamma = atof(argv[i]);
break;
case 'G':
gap = atof(argv[i]);
break;
case 'I':
ker_ridge = atoi(argv[i]);
break;
case 'r':
coef0 = atof(argv[i]);
break;
case 'm':
cache_size = (int) atof(argv[i]);
break;
case 'M':
do_multi_class = (int) atof(argv[i]);
break;
case 'c':
C = atof(argv[i]);
break;
case 'a':
C_star = atof(argv[i]);
break;
case 'C':
C2 = atof(argv[i]);
break;
case 'z':
C3 = atof(argv[i]);
break;
case 'v':
folds = atoi(argv[i]);
break;
case 'b':
use_b0=atoi(argv[i]);
break;
case 'w':
un_weight = atof(argv[i]);
break;
case 'e':
epsgr = atof(argv[i]);
break;
case 'R':
seed=atoi(argv[i]);
break;
case 'F':
strcpy(model_file_name,argv[i]);
justtest = 1;
break;
default:
fprintf(stderr,"unknown option\n");
exit_with_help();
}
}
// determine filenames
if(i>=argc)
exit_with_help();
strcpy(input_file_name, argv[i]);
if(i<argc-1){
strcpy(model_file_name,argv[i+1]);
}
/*{ TRASH
char *p = strrchr(argv[i],'/');
if(p==NULL)
p = argv[i];
else
++p;
sprintf(model_file_name,"%s.model",p);
} TRASH END */
}
int split_file_load(char *f)
{
int binary_file=0,labs=0,inds=0;
FILE *fp;
fp=fopen(f,"r");
if(fp==NULL) {printf("[couldn't load split file: %s]\n",f); exit(1);}
char dummy[100],dummy2[100];
int i,j=0;
for(i=0;i<(int)strlen(f);i++) if(f[i]=='/') j=i+1;
fscanf(fp,"%s %s",dummy,dummy2);
strcpy(&(f[j]),dummy2);
fscanf(fp,"%s %d",dummy,&binary_file);
fscanf(fp,"%s %d",dummy,&inds);
fscanf(fp,"%s %d",dummy,&labs);
printf("[split file: load:%s binary:%d new_indices:%d new_labels:%d]\n",f,binary_file,inds,labs);
//printf("[split file:%s binary=%d]\n",dummy2,binary_file);
if(!inds) return binary_file;
while(1)
{
int i,j;
int c=fscanf(fp,"%d",&i);
if(labs) c=fscanf(fp,"%d",&j);
if(c==-1) break;
if (labs)
splits.push_back(ID(i-1,j));
else
splits.push_back(ID(i-1,0));
}
sort(splits.begin(),splits.end());
return binary_file;
}
int libsvm_load_data(char *filename)
// loads the same format as LIBSVM
{
int index; double value;
int elements, i;
FILE *fp = fopen(filename,"r");
lasvm_sparsevector_t* v;
if(fp == NULL)
{
fprintf(stderr,"Can't open input file \"%s\"\n",filename);
exit(1);
}
else
printf("loading \"%s\".. \n",filename);
int splitpos=0;
int msz = 0;
elements = 0;
while(1)
{
int c = fgetc(fp);
switch(c)
{
case '\n':
if(splits.size()>0)
{
if(splitpos<(int)splits.size() && splits[splitpos].x==msz)
{
v=lasvm_sparsevector_create();
X.push_back(v); splitpos++;
}
}
else
{
v=lasvm_sparsevector_create();
X.push_back(v);
}
++msz;
//printf("%d\n",m);
elements=0;
break;
case ':':
++elements;
break;
case EOF:
goto out;
default:
;
}
}
out:
rewind(fp);
max_index = 0;splitpos=0;
for(i=0;i<msz;i++)
{
int write=0;
if(splits.size()>0)
{
if(splitpos<(int)splits.size() && splits[splitpos].x==i)
{
write=2;splitpos++;
}
}
else
write=1;
int label;
fscanf(fp,"%d",&label);
// printf("%d %d\n",i,label);
if(write)
{
if(splits.size()>0)
{
if(splits[splitpos-1].y!=0 && splits[splitpos-1].y!=-99)
Y.push_back(splits[splitpos-1].y);
else
Y.push_back(label);
}
else
Y.push_back(label);
}
while(1)
{
int c;
do {
c = getc(fp);
if(c=='\n') goto out2;
} while(isspace(c));
ungetc(c,fp);
fscanf(fp,"%d:%lf",&index,&value);
if (write==1) lasvm_sparsevector_set(X[m+i],index,value);
if (write==2) lasvm_sparsevector_set(X[m+splitpos-1],index,value); // <-- was this the (and the only) bug?
if (index>max_index) max_index=index;
}
out2:
label=1; // dummy
}
fclose(fp);
msz=X.size()-m;
printf("examples: %d features: %d\n",msz,max_index);
return msz;
}
int binary_load_data(char *filename)
{
int msz,i=0,j;
lasvm_sparsevector_t* v;
int nonsparse=0;
ifstream f;
f.open(filename,ios::in|ios::binary);
// read number of examples and number of features
int sz[2];
f.read((char*)sz,2*sizeof(int));
if (!f) { printf("File writing error in line %d of %s.\n",i,filename); exit(1);}
msz=sz[0]; max_index=sz[1];
vector <float> val;
vector <int> ind;
val.resize(max_index);
if(max_index>0) nonsparse=1;
int splitpos=0;
for(i=0;i<msz;i++)
{
int mwrite=0;
if(splits.size()>0)
{
if(splitpos<(int)splits.size() && splits[splitpos].x==i)
{
mwrite=1;splitpos++;
v=lasvm_sparsevector_create(); X.push_back(v);
}
}
else
{
mwrite=1;
v=lasvm_sparsevector_create(); X.push_back(v);
}
if(nonsparse) // non-sparse binary file
{
f.read((char*)sz,1*sizeof(int)); // get label
if(mwrite)
{
if(splits.size()>0 && (splits[splitpos-1].y!=0 && splits[splitpos-1].y!=-99))
Y.push_back(splits[splitpos-1].y);
else
Y.push_back(sz[0]);
}
f.read((char*)(&val[0]),max_index*sizeof(float));
if(mwrite)
for(j=0;j<max_index;j++) // set features for each example
lasvm_sparsevector_set(v,j,val[j]);
}
else // sparse binary file
{
f.read((char*)sz,2*sizeof(int)); // get label & sparsity of example i
if(mwrite)
{
if(splits.size()>0 && (splits[splitpos-1].y!=0 && splits[splitpos-1].y!=-99))
Y.push_back(splits[splitpos-1].y);
else
Y.push_back(sz[0]);
}
val.resize(sz[1]); ind.resize(sz[1]);
f.read((char*)(&ind[0]),sz[1]*sizeof(int));
f.read((char*)(&val[0]),sz[1]*sizeof(float));
if(mwrite)
for(j=0;j<sz[1];j++) // set features for each example
{
lasvm_sparsevector_set(v,ind[j],val[j]);
//printf("%d=%g\n",ind[j],val[j]);
if(ind[j]>max_index) max_index=ind[j];
}
}
}
f.close();
msz=X.size()-m;
printf("examples: %d features: %d\n",msz,max_index);
return msz;
}
void load_data_file(char *filename)
{
int msz,i,ft;
splits.resize(0);
int bin=binary_files;
if(bin==0) // if ascii, check if it isn't a split file..
{
FILE *f=fopen(filename,"r");
if(f == NULL)
{
fprintf(stderr,"Can't open input file \"%s\"\n",filename);
exit(1);
}
char c; fscanf(f,"%c",&c);
if(c=='f') bin=2; // found split file!
}
switch(bin) // load diferent file formats
{
case 0: // libsvm format
msz=libsvm_load_data(filename); break;
case 1:
msz=binary_load_data(filename); break;
case 2:
ft=split_file_load(filename);
if(ft==0)
{msz=libsvm_load_data(filename); break;}
else
{msz=binary_load_data(filename); break;}
default:
fprintf(stderr,"Illegal file type '-B %d'\n",bin);
exit(1);
}
if(kernel_type==RBF)
{
x_square.resize(m+msz);
for(i=0;i<msz;i++){
x_square[i+m]=lasvm_sparsevector_dot_product(X[i+m],X[i+m]);
}
}
if(kgamma==-1)
kgamma=1.0/ ((double) max_index); // same default as LIBSVM
m+=msz;
}
int sample_type(int i){
switch (Y[i]){
case -3:
return UNLABSAMP;
break;
case -2:
return UNIVESAMP;
break;
case -4:
return EXTRASAMP;
break;
default:
return TRAINSAMP;
}
}
void load_data(char* input_file_name,char* universum_file_name,char* testset_file_name,char* unlabeled_file_name){
printf("Loading data...\n\n");
//load training data
int m_old = 0;
printf("Training data: \n");
load_data_file(input_file_name);
printf("Done!\n");
// check, if data contains universum/unlabeled points
for (int i = m_old; i != m;++i){
if (Y[i] >= -1) data_map[TRAIN].push_back(i);
else if (Y[i] == -2) data_map[UNIVERSUM].push_back(i); // universum has -2
else if (Y[i] == -3) data_map[UNLABELED].push_back(i); // unlabeled has -3
}
m_old = m;
printf("\n");
//load universum data
printf("Universum: \n");
if (universum_file_name[0] != '\0'){
load_data_file(universum_file_name);
for(int i=m_old;i!=m;++i){
Y[i]=-2;
data_map[UNIVERSUM].push_back(i);
}
}
else printf("No Universum specified!\n");
m_old = m;
printf("\n");
//load test data
printf("Test Data: \n");
if (testset_file_name[0] != '\0'){
load_data_file(testset_file_name);
printf("Done!\n");
for(int i=m_old;i!=m;++i){
data_map[TEST].push_back(i);
}
}else printf("No test set specified!\n");
m_old = m;
printf("\n");
printf("Unlabeled Data: \n");
if (unlabeled_file_name[0] != '\0'){
load_data_file(unlabeled_file_name);
printf("Done!\n");
for(int i=m_old;i != m;++i){
Y[i] =-3;
data_map[UNLABELED].push_back(i);
}
}else printf("No unlabeled data specified!\n");
// if C for unlabeled = 0, it should not use it
if (C3 == 0.0) data_map[UNLABELED].resize(0); // KEEP?
printf("\n");
printf("\n\nData successfully loaded:\n \tNumber of training examples: %i\n \tNumber of test examples: %i\n",data_map[TRAIN].size(),data_map[TEST].size());
printf("\tNumber of unlabeled examples: %i\n \tNumber of examples in universum: %i\n\n",data_map[UNLABELED].size(),data_map[UNIVERSUM].size()); // uncomment in future version
}
void load_model_param(const char *model_file_name){
FILE *fp = fopen(model_file_name,"rb");
if(fp==NULL){
fprintf(stderr,"Model file does not exist!\n");
exit(1);
}
double alpha0 = 0.0;
int num_sv = 0;
// read parameters
char cmd[81];
while(1)
{
fscanf(fp,"%80s",cmd);
if(strcmp(cmd,"b0")==0){
fscanf(fp,"%lf",&b0);
printf("\tb0: %g\n",b0);
}else if(strcmp(cmd,"kernel_type")==0){
fscanf(fp,"%80s",cmd);
int i = 0;
for(i=0;kernel_type_table[i];++i){
if(strcmp(kernel_type_table[i],cmd)==0){
kernel_type=i;
break;
}
}
if (i == sizeof(kernel_type_table)){
fprintf(stderr,"kernel_type not know\n"); exit(1);
}else{
printf("\tkernel_type: %s\n",kernel_type_table[kernel_type]);
}
}else if(strcmp(cmd,"degree")==0){
fscanf(fp,"%lf",°ree);
printf("\tdegree: %g\n",degree);
}else if(strcmp(cmd,"kgamma")==0){
fscanf(fp,"%lf",&kgamma);
printf("\tkgamma: %g\n",kgamma);
}else if(strcmp(cmd,"coef0")==0){
fscanf(fp,"%lf",&coef0);
printf("\tcoef0: %g\n",coef0);
}else if(strcmp(cmd,"alpha0")==0){
fscanf(fp,"%lf",&alpha0);
printf("\talpha0: %g\n",alpha0);
}else if(strcmp(cmd,"total_sv")==0){
fscanf(fp,"%d",&num_sv);
printf("\tNumber of SVs: %d\n",num_sv);
}else if(strcmp(cmd,"SV")==0){
while(1){
int c = getc(fp);
if(c==EOF || c=='\n') break;
}
break;
}else{
fprintf(stderr,"unknown text in model file\n");
exit(1);
}
}
fclose(fp);
}
int load_model(const char *model_file_name)
{
FILE *fp = fopen(model_file_name,"rb");
if(fp==NULL){
fprintf(stderr,"Model file does not exist!\n");
exit(1);
}
double alpha0 = 0.0;
int num_sv = 0;
// read parameters
char cmd[81];
while(1)
{
fscanf(fp,"%80s",cmd);
if(strcmp(cmd,"b0")==0){
fscanf(fp,"%lf",&b0);
printf("\tb0: %g\n",b0);
}else if(strcmp(cmd,"kernel_type")==0){
fscanf(fp,"%80s",cmd);
int i = 0;
for(i=0;kernel_type_table[i];++i){
if(strcmp(kernel_type_table[i],cmd)==0){
kernel_type=i;
break;
}
}
if (i == sizeof(kernel_type_table)){
fprintf(stderr,"kernel_type not know\n"); exit(1);
}else{
printf("\tkernel_type: %s\n",kernel_type_table[kernel_type]);
}
}else if(strcmp(cmd,"degree")==0){
fscanf(fp,"%lf",°ree);
printf("\tdegree: %g\n",degree);
}else if(strcmp(cmd,"kgamma")==0){
fscanf(fp,"%lf",&kgamma);
printf("\tkgamma: %g\n",kgamma);
}else if(strcmp(cmd,"coef0")==0){
fscanf(fp,"%lf",&coef0);
printf("\tcoef0: %g\n",coef0);
}else if(strcmp(cmd,"alpha0")==0){
fscanf(fp,"%lf",&alpha0);
printf("\talpha0: %g\n",alpha0);
}else if(strcmp(cmd,"total_sv")==0){
fscanf(fp,"%d",&num_sv);
printf("\tNumber of SVs: %d\n",num_sv);
}else if(strcmp(cmd,"SV")==0){
while(1){
int c = getc(fp);
if(c==EOF || c=='\n') break;
}
break;
}else{
fprintf(stderr,"unknown text in model file\n");
exit(1);
}
}
// read sv_coef and SV
int index; double value;
int elements = 0;
int msz = 0; int i =0;
long pos = ftell(fp);
lasvm_sparsevector_t* v;
elements = 0;
while(1){
int c = fgetc(fp);
switch(c){
case '\n':
v=lasvm_sparsevector_create();
X.push_back(v);
++msz;
elements=0;
break;
case ':':
++elements;
break;
case EOF:
goto out;
default:
;
}
}
out:
fseek(fp,pos,SEEK_SET);
max_index = 0;
for(i=0;i<msz;i++){
double tmp_alpha;
fscanf(fp,"%lf",&tmp_alpha);
alpha.push_back(tmp_alpha);
while(1){
int c;
do {
c = getc(fp);
if(c=='\n') goto out2;
} while(isspace(c));
ungetc(c,fp);
fscanf(fp,"%d:%lf",&index,&value);
lasvm_sparsevector_set(X[m+i],index,value);
if (index>max_index) max_index=index;
}
out2:
if (tmp_alpha != 0)
data_map[SV].push_back(m+i);
else
data_map[UNLABELED].push_back(m+i);