forked from leeck10/structural_svm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssvm_train.cpp
More file actions
2125 lines (1855 loc) · 71.4 KB
/
Copy pathssvm_train.cpp
File metadata and controls
2125 lines (1855 loc) · 71.4 KB
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
/*
* vi:ts=4:tw=78:shiftwidth=4:expandtab
* vim600:fdm=marker
*/
/**
@file ssvm_train.cpp
@brief (linear chain) Structural SVMs
@author Changki Lee (leeck@kangwon.ac.kr)
@date 2013/3/1
*/
#ifdef WIN32
#pragma warning(disable: 4786)
#pragma warning(disable: 4996)
#pragma warning(disable: 4267)
#pragma warning(disable: 4244)
#pragma warning(disable: 4018)
#endif
#include <cassert>
#include <stdexcept> //for std::runtime_error
#include <memory> //for std::bad_alloc
#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>
#include <numeric>
#include "ssvm.hpp"
#include "timer.hpp"
#include "pqueue.hpp"
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
/// train
void SSVM::train(string estimate) {
if (domain_adaptation && support_feature) {
cerr << "Error: domain adaptation does not support support_feature mode!" << endl;
exit(1);
}
add_edge();
print_start_status(estimate);
if (estimate == "fsmo") {
train_fsmo();
} else if (estimate == "fsmo_joint") {
train_fsmo_joint(true);
} else if (estimate == "fsmo_joint2") {
train_fsmo_joint(false);
} else if (estimate == "pegasos") {
train_pegasos();
} else if (estimate == "latent_SSVM") {
train_latent_ssvm();
} else if (estimate == "latent_SPL") {
train_latent_ssvm(1);
} else if (estimate == "joint_SSVM") {
train_joint_ssvm();
} else if (estimate == "joint_SPL") {
train_joint_ssvm(1);
} else {
cerr << "!Error: " << estimate << " is not supported." << endl;
exit(1);
}
}
/// fixed-threshold SMO (Sequential Minimum Optimization) + openMP
double SSVM::train_fsmo() {
int n = train_data.size();
int niter = 1, const_num = work_set.size(), old_const_num = work_set.size();
int correct = 0, error = 0, argmax_count = 0;
int i, j;
double max_kkt = 0, obj = 0, diff_obj = 0, additional_value = 0;
double time = 0, time_qp = 0, time_viol = 0, time_psi = 0;
// for domain adaptation
float *prior_theta = NULL;
if (domain_adaptation) {
cerr << "[Domain adaptation mode]" << endl;
prior_theta = new float[n_theta];
for (int i=0; i < n_theta; i++) {
prior_theta[i] = theta[i];
}
}
#ifdef _OPENMP
if (buf < omp_get_max_threads()) omp_set_num_threads(buf);
cerr << "[OpenMP] Number of threads: " << omp_get_max_threads() << endl;
#endif
// comment
if (!use_comment) vector<string>().swap(train_data_comment);
// shirink 초기화
int opti_round = 0;
opti.resize(n, 0);
// work_set_ids 초기화
work_set_ids.clear();
for (i=0; i < train_data.size(); i++) {
vector<int> temp;
work_set_ids.push_back(temp);
}
// sum_alpha 초기화
// shared_slack인 경우만 사용: size=train_data.size()
sum_alpha.resize(train_data.size(), 0);
// slack 초기화
// shared_slack인 경우만 사용: size=train_data.size()
slacks.resize(train_data.size(), 0);
slacks_id.resize(train_data.size(), -1);
// inactive constraint 제거
int opt_count = 0;
if (domain_adaptation) {
printf("iter acc train time |w| |w-w0| primal dual active const SV\n");
printf("========================================================================");
} else {
printf("iter acc train time |w| primal dual active const SV\n");
printf("===================================================================");
}
fflush(stdout);
// C/n
double cost1 = cost / n;
double eps1;
if (owps_format) {
eps1 = 1.28;
} else {
eps1 = 32;
}
int active_num = 0, old_active_num = 0;
int sv_num = 0, old_sv_num = 0;
int newconstraints = 0, new_precision = 1;
int infinite_loop = 0;
do { // increase precision
eps1 = MAX(eps1*0.49999999, eps);
new_precision = 1;
cerr << endl << "# eps = " << eps1 << " ";
opti_round++;
active_num = n;
old_active_num = active_num;
// make M_i matrix
make_M_matrix();
do { // new constatrains
timer t;
old_const_num = const_num;
old_active_num = active_num;
correct = 0;
error = 0;
max_kkt = 0.0;
for (size_t sent_i = 0; sent_i < train_data.size();) {
#pragma omp parallel for
for (int buf_i=0; buf_i < buf; buf_i++) {
int sent_index, skip = 0;
#pragma omp critical (sent_i)
{
sent_index = sent_i;
if (sent_i++ >= train_data.size()) skip = 1;
} // omp
if (skip) continue;
// shrink : 마지막에서는 shrink를 하도록 or 안하도록 수정
if (opti[sent_index] != opti_round || (final_opt_check && eps1 == eps)) {
// find most violated contraint
sent_t& sent = train_data[sent_index];
vector<int> y_seq;
timer t_viol;
#pragma omp atomic
argmax_count++;
// make M_i matrix
vector<double> r_vec;
make_R_matrix(r_vec, sent);
y_seq = find_most_violated_constraint(r_vec, sent);
#pragma omp atomic
time_viol += t_viol.elapsed();
double cur_loss = calculate_loss(sent, y_seq);
timer t_psi;
vect_t max_vect = make_diff_vector(sent, y_seq);
#pragma omp atomic
time_psi += t_psi.elapsed();
if (max_vect.empty()) {
if (opti[sent_index] != opti_round) {
active_num--;
opti[sent_index] = opti_round;
}
continue;
}
double cost_diff = calculate_cost(max_vect);
double H_y = cur_loss - cost_diff;
#pragma omp critical (slack)
{
// slack
double slack = 0;
int sid = -1;
for (i=0; i < sent_ids.size(); i++) {
int id = sent_ids[i];
if (id == sent_index) {
double cur_cost_diff = calculate_cost(work_set[i]);
double cur_H_y = loss[i] - cur_cost_diff;
if (cur_H_y > slack) {
slack = cur_H_y;
sid = i;
}
}
}
slacks[sent_index] = slack;
slacks_id[sent_index] = sid;
max_kkt = MAX(max_kkt, H_y - slack);
if (H_y > slack + eps1) {
//cerr << ".";
// alpha
alpha.push_back(0);
// alpha_history
alpha_history.push_back(opt_count);
// work set
work_set.push_back(max_vect);
// loss
loss.push_back(cur_loss);
// x_norm_vec
x_norm_vec.push_back(kernel(max_vect, max_vect));
// sent_ids
sent_ids.push_back(sent_index);
// work_set_ids
work_set_ids[sent_index].push_back(const_num);
// y_seq
y_seq_vec.push_back(y_seq);
const_num++;
newconstraints++;
} else {
if (opti[sent_index] != opti_round) {
active_num--;
opti[sent_index] = opti_round;
}
}
} // omp
}
} // buf loop
// get new QP solution
if ((newconstraints >= buf)
|| (newconstraints > 0 && sent_i >= n-1)
|| (const_num > 0 && new_precision)) {
cerr << "*";
timer t_qp;
// using SMO if bounded
optimize_dual4fsmo(cost1, eps1);
time_qp += t_qp.elapsed();
// make M_i matrix
make_M_matrix();
new_precision = 0;
newconstraints = 0;
// inactive constraint 제거
// rm_inactive iteration 동안 active된 적이 없는 것
// svm-light는 50
opt_count++;
if (1) {
int remove_count = 0;
for (i=0; i < work_set.size() - remove_count; i++) {
// active constraint
if (alpha[i] > 0) {
alpha_history[i] = opt_count;
}
// rm_inactive번 안에 active 된 적이 없는 constraint
else if (opt_count - alpha_history[i] >= rm_inactive) {
// 맨 뒤의 원소부터 swap한 후, remove_count만큼 맨뒤 원소들을 삭제
int sw_i = work_set.size() - 1 - remove_count;
work_set[i] = work_set[sw_i];
alpha[i] = alpha[sw_i];
alpha_history[i] = alpha_history[sw_i];
loss[i] = loss[sw_i];
x_norm_vec[i] = x_norm_vec[sw_i];
sent_ids[i] = sent_ids[sw_i];
y_seq_vec[i] = y_seq_vec[sw_i];
// 나머지 변수 처리
i--;
//old_const_num--;
const_num--;
remove_count++;
}
}
if (remove_count > 0) {
// 실제 제거
int rm_i = work_set.size() - remove_count;
work_set.erase(work_set.begin() + rm_i, work_set.end());
alpha.erase(alpha.begin() + rm_i, alpha.end());
alpha_history.erase(alpha_history.begin() + rm_i, alpha_history.end());
loss.erase(loss.begin() + rm_i, loss.end());
x_norm_vec.erase(x_norm_vec.begin() + rm_i, x_norm_vec.end());
sent_ids.erase(sent_ids.begin() + rm_i, sent_ids.end());
y_seq_vec.erase(y_seq_vec.begin() + rm_i, y_seq_vec.end());
// work_set_ids 다시 작성
work_set_ids.clear();
for (i=0; i < train_data.size(); i++) {
vector<int> temp;
work_set_ids.push_back(temp);
}
for (i=0; i < sent_ids.size(); i++) {
int id = sent_ids[i];
work_set_ids[id].push_back(i);
}
// test
cerr << "r" << remove_count;
}
}
} // QP
} // example loop
// time
double iter_time = t.elapsed();
time += iter_time;
old_sv_num = sv_num;
sv_num = 0;
double sum = 0, alphasum = 0;
for (i=0; i < alpha.size(); i++) {
if (alpha[i] != 0) {
sum += alpha[i];
alphasum += alpha[i] * loss[i];
sv_num++;
}
}
// 무한 루프 체크
if (active_num == old_active_num && sv_num == old_sv_num && const_num == old_const_num) {
infinite_loop++;
if (infinite_loop >= 2) {
cerr << endl << endl << "Warning: infinite loop (" << infinite_loop << "): ";
cerr << "change rm_inactive or buf!" << endl;
cerr << " changed active_num=0" << endl;
infinite_loop = 0;
active_num = 0;
}
} else {
infinite_loop = 0;
}
// obj --> model length |w|: non-linear인 경우 domain adaption은 아직 고려 안됨
obj = 0.0;
diff_obj = 0;
additional_value = 0;
if (!skip_eval || active_num == 0) {
for (i=0; i < n_theta; i++) {
obj += SQUARE(theta[i]);
if (domain_adaptation && theta[i] != prior_theta[i]) {
diff_obj += SQUARE(theta[i] - prior_theta[i]);
additional_value += prior_theta[i] * (prior_theta[i] - theta[i]);
}
}
obj = sqrt(obj);
diff_obj = sqrt(diff_obj);
}
// continue evaluations
//double acc = 100.0*(correct)/(correct+error);
// test_data 성능
correct = 0;
if (!skip_eval || active_num == 0) {
vector<sent_t>::iterator it = test_data.begin();
// make M_i matrix
make_M_matrix();
#pragma omp parallel for private(j)
for (i = 0; i < test_data.size(); i++) {
sent_t& sent = test_data[i];
double prob;
vector<int> y_seq;
// make M_i matrix
vector<double> r_vec;
make_R_matrix(r_vec, sent);
y_seq = viterbi(r_vec, sent, prob);
for (j=0; j < sent.size(); j++) {
if (sent[j].outcome == y_seq[j]) {
#pragma omp atomic
correct++;
}
}
}
}
double test_acc = test_data.size() > 0 ? 100*double(correct)/double(n_test_event) : 0;
// primal cost 계산: 0.5 * |w|^2 + C/n * L
double primal_cost = 0, dual_cost = 0;
double slack_sum = 0;
for (i=0; i < slacks.size(); i++) {
if (slacks[i] > 0) slack_sum += slacks[i] + eps1;
else slack_sum += eps1;
}
primal_cost += cost1 * slack_sum;
if (obj != 0 || diff_obj != 0) {
if (domain_adaptation) primal_cost = 0.5 * diff_obj * diff_obj + cost1 * slack_sum;
else primal_cost = 0.5 * obj * obj + cost1 * slack_sum;
if (domain_adaptation) dual_cost = alphasum - (0.5 * diff_obj * diff_obj) + additional_value;
else dual_cost = alphasum - (0.5 * obj * obj);
}
if (domain_adaptation) {
printf("\n%3d %5.2f%% %6.1f %5.0f %5.1f %4.1f %9.2e %9.2e %5d %5d %5d ",
niter++ , test_acc, iter_time, time, obj, diff_obj, primal_cost, dual_cost, active_num, const_num, sv_num);
} else {
printf("\n%3d %5.2f%% %6.1f %5.0f %5.1f %9.2e %9.2e %5d %5d %5d ",
niter++ , test_acc, iter_time, time, obj, primal_cost, dual_cost, active_num, const_num, sv_num);
}
if (!skip_eval || active_num == 0) print_status();
fflush(stdout);
} while (active_num > 0);
// eps 마다 저장: 0.5, 0.25, 0.1 -- by leeck
if (period > 0 && eps1 > eps && eps1 < 1)
{
cerr << endl << "model saving to " << model_file << "." << eps1 << " ... ";
char temp[100];
sprintf(temp, "%s.%g", model_file.c_str(), eps1);
if (binary) save_bin(string(temp));
else save(string(temp));
cerr << "done." << endl;
}
} while (eps1 > eps);
try {
cerr << endl;
int const_num = 0, sv_num = 0;
double sum = 0, alphasum = 0;
double max_alpha = 0.0;
const_num = alpha.size();
for (i=0; i < alpha.size(); i++) {
if (alpha[i] > 0) {
sum += alpha[i];
alphasum += alpha[i] * loss[i];
sv_num++;
max_alpha = MAX(max_alpha, alpha[i]);
}
}
// slack
int bounded_sv = 0;
for (i=0; i < work_set_ids.size(); i++) {
double slack = 0;
int sid = -1;
for (j=0; j < work_set_ids[i].size(); j++) {
int id = work_set_ids[i][j];
double cur_cost_diff = calculate_cost(work_set[id]);
double cur_H_y = loss[id] - cur_cost_diff;
if (cur_H_y > slack) {
slack = cur_H_y;
sid = id;
}
// bounded SV
if (sum_alpha[i] >= cost1-precision && alpha[id] > 0) bounded_sv++;
}
slacks[i] = slack;
slacks_id[i] = sid;
}
double slack_sum = 0;
int slack_num = 0;
for (i=0; i < slacks.size(); i++) {
if (slacks[i] > 0) {
slack_sum += slacks[i] + eps1;
slack_num++;
} else {
slack_sum += eps1;
}
}
// primal cost 계산: 0.5 * |w|^2 + C/n * L
// dual object value 계산: sum(Loss*a) - 0.5 * |w|^2
double primal_cost, dual_cost;
if (domain_adaptation) primal_cost = 0.5 * diff_obj * diff_obj + cost1 * slack_sum;
else primal_cost = 0.5 * obj * obj + cost1 * slack_sum;
if (domain_adaptation) dual_cost = alphasum - (0.5 * diff_obj * diff_obj) + additional_value;
else dual_cost = alphasum - (0.5 * obj * obj);
cerr << "Training time= " << time << endl;
cerr << endl << "const=" << const_num << " SV=" << sv_num << " bounded_SV=" << bounded_sv << endl;
cerr << "alphasum=" << alphasum << " sum(a)=" << sum << " max(a)=" << max_alpha << endl;
cerr << "slack_num=" << slack_num << " sum(slack)=" << slack_sum << endl;
cerr << "|w|=" << obj << endl;
cerr << "primal_cost(upper bound)=" << primal_cost << endl;
cerr << "dual object=" << dual_cost << endl;
cerr << "duality gap=" << primal_cost - dual_cost << endl;
cerr << "longest ||Psi(x,y)-Psi(x,ybar)||=" << longest_vector() << endl;
cerr << "Runtime(sec): QP=" << time_qp << " Argmax=" << time_viol << " psi=" << time_psi << endl;
cerr << "Runtime(%): QP=" << 100*time_qp/time << " Argmax=" << 100*time_viol/time;
cerr << " psi=" << 100*time_psi/time << " others=" << 100*(time-time_qp-time_viol-time_psi)/time << endl;
cerr << "Number of calls to 'find_most_violated_constraint': " << argmax_count << endl;
save_slack(eps);
} catch (std::exception& e) {
cerr << endl << "std::exception caught:" << e.what() << endl;
}
// free
if (domain_adaptation) {
delete[] prior_theta;
}
return time;
}
/// fixed threshold SMO + joint constraint (like SVM-Perf)
double SSVM::train_fsmo_joint(bool use_gram) {
int n = train_data.size();
int niter = 1, const_num = work_set.size();
int correct = 0, argmax_count = 0;
double ceps = 0, obj = 0, diff_obj = 0, additional_value = 0;
double time = 0, time_qp = 0, time_viol = 0, time_psi = 0;
// for domain adaptation
float *prior_theta = NULL;
if (domain_adaptation) {
cerr << "[Domain adaptation mode]" << endl;
prior_theta = new float[n_theta];
for (int i=0; i < n_theta; i++) {
prior_theta[i] = theta[i];
}
}
#ifdef _OPENMP
if (buf < omp_get_max_threads()) omp_set_num_threads(buf);
cerr << "[OpenMP] Number of threads: " << omp_get_max_threads() << endl;
#endif
// comment
if (!use_comment) vector<string>().swap(train_data_comment);
// gram 초기화
if (use_gram) {
gram.clear();
for (int i=0; i < gram_size; i++) {
vector<float> gram_i;
for (int j=0; j < gram_size; j++) {
gram_i.push_back(-1);
}
gram.push_back(gram_i);
}
}
// slack 초기화
double slack = 0;
// inactive constraint 제거
int opt_count = 0;
if (domain_adaptation) {
printf("iter accuracy training time |w| |w-w0| primal dual const SV\n");
printf("============================================================================");
} else {
printf("iter accuracy training time |w| primal dual const SV\n");
printf("======================================================================");
}
fflush(stdout);
double cost1 = cost;
double eps1 = 100;
double old_eps = eps1;
// dense vector
vector<float> dense_vect(n_theta, 0);
do { // increase precision
timer t;
correct = 0;
ceps = 0.0;
// a joint vector : linear만 고려
vect_t joint_vect;
single_vect_t s_joint_vect;
double joint_loss = 0, joint_cost_diff = 0;
// dense vector 초기화
for (size_t i=0; i < dense_vect.size(); i++) {
dense_vect[i] = 0;
}
// slack 계산
slack = 0;
#pragma omp parallel for
for (int i=0; i < (int)work_set.size(); i++) {
double cur_cost_diff;
cur_cost_diff = calculate_cost(work_set[i]);
#pragma omp critical (slack)
slack = MAX(slack, loss[i] - cur_cost_diff);
}
if (!owps_format) {
// make M_i matrix
make_M_matrix();
}
// find a violated joint contraint
double sum_viol = 0;
#pragma omp parallel for
for (int sent_index = 0; sent_index < (int)train_data.size(); sent_index++) {
sent_t& sent = train_data[sent_index];
vector<int> y_seq;
// find most violated contraint
timer t_viol;
#pragma omp atomic
argmax_count++;
// for openMP
vector<double> r_vec;
// make M_i matrix
make_R_matrix(r_vec, sent);
y_seq = find_most_violated_constraint(r_vec, sent, 1);
#pragma omp atomic
time_viol += t_viol.elapsed();
// sentence가 맞았는지 검사
bool all_correct = true;
for (size_t i=0; i < sent.size(); i++) {
if (sent[i].outcome == y_seq[i]) correct++;
else all_correct = false;
}
// 다 맞았으면 skip
if (all_correct) continue;
double cur_loss = calculate_loss(sent, y_seq);
// for CPA
timer t_psi;
vect_t vect;
vect = make_diff_vector(sent, y_seq);
#pragma omp critical (dense_vect)
append_diff_vector(dense_vect, vect);
#pragma omp atomic
time_psi += t_psi.elapsed();
// loss 값은 다 더한다
#pragma omp atomic
joint_loss += cur_loss;
} // example loop
joint_loss = joint_loss / double(n);
double norm = 0.0;
size_t non_empty_count = 0;
for (int i=0; i < n_theta; i++) {
if (dense_vect[i] != 0) {
norm += dense_vect[i] * dense_vect[i];
non_empty_count++;
}
}
s_joint_vect.twonorm_sq = norm;
s_joint_vect.factor = 1 / double(n);
// sparse vector로 변경한다
for (int i=0; i < n_theta; i++) {
if (dense_vect[i] != 0) {
s_joint_vect.vect.push_back(make_pair(i,dense_vect[i]));
}
}
joint_vect.push_back(s_joint_vect);
// joint vector의 H_y 계산
joint_cost_diff = calculate_cost(joint_vect);
ceps = MAX(0, joint_loss - joint_cost_diff - slack);
// w*x - b 에서 b 제거
if (verbose || slack > (joint_loss - joint_cost_diff + 1e-12)) {
if (slack > (joint_loss - joint_cost_diff + 1e-12)) {
cerr << endl << "WARNING: Slack of most violated constraint is smaller than slack of working" << endl;
cerr << " set! There is probably a bug in 'find_most_violated_constraint_*'.";
}
cerr << endl << "H(y)=" << joint_loss-joint_cost_diff << " slack=" << slack << " ceps=" << joint_loss-joint_cost_diff-slack << endl;
cerr << "loss=" << joint_loss << " cost=" << joint_cost_diff << endl;
}
// if error, then add a joint constraint
if (ceps > eps) {
//cerr << ".";
// alpha
alpha.push_back(0);
// alpha_history
alpha_history.push_back(opt_count);
// work set
work_set.push_back(joint_vect);
// loss
loss.push_back(joint_loss);
// x_norm_vec
x_norm_vec.push_back(s_joint_vect.factor * s_joint_vect.factor * s_joint_vect.twonorm_sq);
const_num++;
old_eps = eps1;
eps1 = MIN(eps1, MAX(ceps, eps));
if (old_eps != eps1) {
cerr << endl << "# eps = " << eps1 << " ";
}
// get new QP solution
cerr << "*";
timer t_qp;
optimize_dual4fsmo_joint(cost1, eps1, use_gram);
time_qp += t_qp.elapsed();
// inactive constraint 제거
// rm_inactive iteration 동안 active된 적이 없는 것
// svm-light는 50
opt_count++;
int remove_count = 0;
for (int i=0; i < work_set.size() - remove_count; i++) {
// active constraint
if (alpha[i] > 0) {
alpha_history[i] = opt_count;
}
// rm_inactive번 안에 active 된 적이 없는 constraint
else if (opt_count - alpha_history[i] >= rm_inactive) {
// 맨 뒤의 원소부터 swap한 후, remove_count만큼 맨뒤 원소들을 삭제
int sw_i = work_set.size() - 1 - remove_count;
work_set[i] = work_set[sw_i];
alpha[i] = alpha[sw_i];
alpha_history[i] = alpha_history[sw_i];
loss[i] = loss[sw_i];
x_norm_vec[i] = x_norm_vec[sw_i];
// gram matrix
if (use_gram) {
// 1차 배열 수정
gram[i] = gram[sw_i];
// 2차 배열 수정
for (int j=0; j < gram_size; j++) {
gram[j][i] = gram[j][sw_i];
}
// 삭제되는 곳에 -1
for (int j=0; j < gram_size; j++) {
gram[sw_i][j] = -1;
gram[j][sw_i] = -1;
}
}
// cost_diff_vec
if (use_gram) {
cost_diff_vec[i] = cost_diff_vec[sw_i];
}
// 나머지 변수 처리
i--;
const_num--;
remove_count++;
}
}
if (remove_count > 0) {
// 실제 제거
int rm_i = work_set.size() - remove_count;
work_set.erase(work_set.begin() + rm_i, work_set.end());
alpha.erase(alpha.begin() + rm_i, alpha.end());
alpha_history.erase(alpha_history.begin() + rm_i, alpha_history.end());
loss.erase(loss.begin() + rm_i, loss.end());
x_norm_vec.erase(x_norm_vec.begin() + rm_i, x_norm_vec.end());
// cost_diff_vec
if (use_gram) {
cost_diff_vec.erase(cost_diff_vec.begin() + rm_i, cost_diff_vec.end());
}
// test
cerr << "r";
}
}
// time
double iter_time = t.elapsed();
time += iter_time;
// sv number
int sv_num = 0;
double sum = 0, alphasum = 0;
for (size_t i=0; i < alpha.size(); i++) {
if (alpha[i] != 0) {
sum += alpha[i];
alphasum += alpha[i] * loss[i];
sv_num++;
}
}
// obj --> model length |w|
obj = 0;
diff_obj = 0;
additional_value = 0;
if (!skip_eval || ceps < eps ) {
for (int i=0; i < n_theta; i++) {
obj += SQUARE(theta[i]);
if (domain_adaptation && theta[i] != prior_theta[i]) {
diff_obj += SQUARE(theta[i] - prior_theta[i]);
additional_value += prior_theta[i] * (prior_theta[i] - theta[i]);
}
}
obj = sqrt(obj);
diff_obj = sqrt(diff_obj);
}
// continue evaluations
double acc = 100*double(correct)/double(n_event);
// test_data 성능
correct = 0;
if (obj != 0 || diff_obj != 0) {
vector<sent_t>::iterator it = test_data.begin();
// make M_i matrix
make_M_matrix();
for (; it != test_data.end(); it++) {
sent_t& sent = *it;
double prob;
vector<int> y_seq;
// make M_i matrix
vector<double> r_vec; // for openMP
make_R_matrix(r_vec, sent);
y_seq = viterbi(r_vec, sent, prob);
for (size_t i=0; i < sent.size(); i++) {
if (sent[i].outcome == y_seq[i]) correct++;
}
}
}
double test_acc = test_data.size() > 0 ? 100*double(correct)/double(n_test_event) : 0;
// primal cost 계산: 0.5 * |w|^2 + C/n * L
double primal_cost = 0, dual_cost = 0;
if (obj != 0 || diff_obj != 0) {
if (domain_adaptation) primal_cost = 0.5 * diff_obj * diff_obj + cost1 * (slack + ceps);
else primal_cost = 0.5 * obj * obj + cost1 * (slack + ceps);
if (domain_adaptation) dual_cost = alphasum - (0.5 * diff_obj * diff_obj) + additional_value;
else dual_cost = alphasum - (0.5 * obj * obj);
}
if (domain_adaptation) {
printf("\n%3d %5.2f%% %5.2f%% %6.2f %8.2f %6.2f %6.2f %9.2e %9.2e %3d %3d ",
niter++ , acc, test_acc, iter_time, time, obj, diff_obj, primal_cost, dual_cost, const_num, sv_num);
} else {
printf("\n%3d %5.2f%% %5.2f%% %6.2f %8.2f %6.2f %9.2e %9.2e %4d %4d ",
niter++ , acc, test_acc, iter_time, time, obj, primal_cost, dual_cost, const_num, sv_num);
}
if (!skip_eval || eps1 != old_eps || ceps < eps) print_status();
fflush(stdout);
// eps 마다 저장: 0.5, 0.1 -- by leeck
if (period > 0 && eps1 > old_eps && eps1 < 1)
{
cerr << endl << "model saving to " << model_file << "." << eps1 << " ... ";
char temp[100];
sprintf(temp, "%s.%g", model_file.c_str(), eps1);
if (binary) save_bin(string(temp));
else save(string(temp));
cerr << "done." << endl;
}
} while (ceps > eps);
// test
if (domain_adaptation) {
printf("\niter accuracy training time |w| |w-w0| primal dual const SV\n");
} else {
printf("\niter accuracy training time |w| primal dual const SV\n");
}
try {
int const_num = 0, sv_num = 0;
double sum = 0, alphasum = 0;
double max_alpha = 0.0;
const_num = alpha.size();
for (size_t i=0; i < alpha.size(); i++) {
if (alpha[i] != 0) {
sum += alpha[i];
alphasum += alpha[i] * loss[i];
sv_num++;
}
max_alpha = MAX(max_alpha, alpha[i]);
}
slack = 0;
for (size_t i=0; i < work_set.size(); i++) {
slack = MAX(slack, loss[i] - calculate_cost(work_set[i]));
}
// primal cost 계산: 0.5 * |w|^2 + C/n * L
double primal_cost, dual_cost;
if (domain_adaptation) primal_cost = 0.5 * diff_obj * diff_obj + cost1 * (slack + ceps);
else primal_cost = 0.5 * obj * obj + cost1 * (slack + ceps);
if (domain_adaptation) dual_cost = alphasum - (0.5 * diff_obj * diff_obj) + additional_value;
else dual_cost = alphasum - (0.5 * obj * obj);
cerr << "Training time= " << time << endl;
cerr << endl << "Final epsilon on KKT-Conditions: " << ceps << endl;
cerr << "const=" << const_num << " SV=" << sv_num << " alphasum=" << alphasum << " sum(a)=" << sum << " max(a)=" << max_alpha << endl;
cerr << "slack=" << slack << endl;
cerr << "|w|=" << obj << endl;
cerr << "primal_cost(upper bound)=" << primal_cost << endl;
cerr << "dual object=" << dual_cost << endl;
cerr << "duality gap=" << primal_cost - dual_cost << endl;
cerr << "longest ||Psi(x,y)-Psi(x,ybar)||=" << longest_vector() << endl;
cerr << "Runtime(sec): QP=" << time_qp << " Argmax=" << time_viol << " psi=" << time_psi << endl;
cerr << "Runtime(%): QP=" << 100*time_qp/time << " Argmax=" << 100*time_viol/time;
cerr << " psi=" << 100*time_psi/time << " others=" << 100*(time-time_qp-time_viol-time_psi)/time << endl;
cerr << "Number of calls to 'find_most_violated_constraint': " << argmax_count << endl;
} catch (std::exception& e) {
cerr << endl << "std::exception caught:" << e.what() << endl;
}
// free
if (domain_adaptation) {
delete[] prior_theta;
}
return time;
}
/// SVM-struct + primal optimization + Stochastic Gradient Descent
/// f = 0.5 * lambda * |w|^2 + (1/n)sum{L(x,y;w)}
/// hindge loss: g = lambda*w - (1/n)sum{delta(psi(i,y))}
/// domain_adaptation: 0 = no domain adaptation, 1 = domain adaptation
double SSVM::train_pegasos() {
int i, j, k;
int niter = 1, weight_num = 0;
int correct = 0, total = 0, argmax_count = 0;
double time = 0, time_qp = 0, time_viol = 0, time_psi = 0;
// for domain adaptation
float *prior_theta = NULL;
if (domain_adaptation) {
cerr << "[Domain adaptation mode]" << endl;
prior_theta = new float[n_theta];
for (int i=0; i < n_theta; i++) {
prior_theta[i] = theta[i];
// 0 부터 시작인지 w0부터 시작인지?
//theta[i] = 0;
}
}
#ifdef _OPENMP
if (buf < omp_get_max_threads()) omp_set_num_threads(buf);
cerr << "[OpenMP] Number of threads: " << omp_get_max_threads() << endl;
#endif
if (domain_adaptation) {
printf("iter primal_cost |w| |w-w0| d(cost) training acc. training time\n");
printf("=========================================================================");
} else {
printf("iter primal_cost |w| d(cost) training acc. training time\n");
printf("==================================================================");
}
fflush(stdout);
// C/n
double n = (double) train_data.size();
// lambda = 1/C
double lambda = 1.0 / cost;
//double lambda = 1.0 / cost1;
double f = 0.0, old_f = 0.0;
double wscale = 1, old_wscale = 1;
double obj = 0, diff_obj = 0;
double dcost = 1;
double t_i = 0;
double best_acc = 0, test_acc = 0;
int best_iter = 0;
vector<int> train_data_index;
if (1) {
for (i=0; i < train_data.size(); i++)
train_data_index.push_back(i);
}
for (; niter <= iter; niter++) {
timer t;
total = 0;
correct = 0;
old_f = f;
f = 0;
if (1) {
cerr << "r";
random_shuffle(train_data_index.begin(), train_data_index.end());