-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.cpp
1128 lines (928 loc) · 28.2 KB
/
train.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
/*
* =====================================================================================
*
* Filename: train.cpp
*
* Description:
*
* Version: 1.0
* Created: 2013-02-15 16:40:41
* Revision: none
* Compiler: gcc
*
* Author: Didzis Gosko (dg), [email protected]
* Organization:
*
* =====================================================================================
*/
#include <iostream>
#include <iomanip>
#include <set>
#include <sstream>
// #include <boost/filesystem.hpp>
#include "train.hpp"
#include "utils.hpp"
// #include "MurmurHash3.h"
using namespace std;
// using namespace boost::filesystem;
//
// Funkcija, kas ielasa kokus no CoLL faila
//
void readFile(IndexMap& idMap, Trees& trees, const string& path, bool useGeneralTags)
{
cout << path << " ... ";
if(trees.readCoNLL(idMap, path, useGeneralTags))
cout << "ok" << endl;
else
cout << "fail" << endl;
}
//
// Funkcija, kas var ielasīt visus conll failus no direktorijas
//
// Prasības: boost/filesystem.hpp
//
// Pašlaik netiek izmantota
//
// void readDirectory(Trees& trees, const string& path)
// {
// for(directory_iterator it(path), end; it!=end; it++)
// {
// if(it->path().extension() == ".conll")
// {
// readFile(trees, (const string&)it->path());
// }
// }
// }
// #define ANSI
//
// Trenēšanas funkcija
//
void TrainCase::train(FeatureVector& featureVector)
{
int start = arguments.trainStart;
int stop = arguments.trainStop;
Trees& trainTrees = arguments.trainTrees;
int limit = arguments.trainLimit;
int T = arguments.iterations;
bool allowNonProjective = arguments.allowTrainNonProjective;
bool permutate = arguments.permutate;
// // rezervē iezīmju vektoram atmiņu, būtiski optimālai ātrdarbībai
// cout << "Allocate memory for feature vector ... ";
// cout.flush();
// featureVector.reserve(arguments.featureVectorSize);
// cout << "ok" << endl;
// izgūst visu iezīmju precedentus treniņu kokos
cout << "Extracting initial features ... ";
cout.flush();
trainTrees.extractFeatures(featureVector);
cout << "ok" << endl;
// IndexMap index;
// trainTrees.index(index);
/* cout << "size = " << index.size() << endl; */
// cout << "Testing feature vector ... ";
// cout.flush();
// struct HHH {
// uint64_t b1;
// uint64_t b2;
// bool operator <(const struct HHH& f) const {
// return f.b1 < b1 && f.b2 < b2;
// }
// };
// map<struct HHH, string> testMap;
// int c = 0;
// for(const Feature& feature : featureVector.features())
// {
// struct HHH hash;
// MurmurHash3_x64_128(feature.key().c_str(), feature.key().size(), 0, (void*)&hash);
// if(testMap.find(hash) != testMap.end() && testMap[hash] != feature.key())
// c++;
// else
// testMap[hash] = feature.key();
// }
// if(c > 0)
// cout << c << " collisions" << endl;
// else
// cout << "ok" << endl;
#if USE_MAP != STD_MAP
cout << "Feature vector size: " << featureVector.size() << endl;
cout << "Feature vector bucket count: " << featureVector.bucket_count() << endl;
cout << "Initial feature vector collisions: " << featureVector.collisions() << endl;
#endif
// limits tiek norādīts derīgajos tokenus: +1 ir dēļ root tokena "*"
if(limit > 0)
limit++;
// // ja nav norādīts apstāšanās koks, tad līdz pēdējam
// if(stop <= 0)
// stop = trainTrees.size();
// w = 0
featureVector.zero();
// summārais svaru vektors v = 0
vector<FeatureVector::Value> v(featureVector.size(), 0);
// randomizācijas sēkla
srand(arguments.seed);
// koku indeksu saraksti (darbojas kā kartes): linērais un permutētais
vector<int> permutated; // permutated map
vector<int> ascending;
int count = 0; // koku parsējumu kopskaits
int countPerIteration = 0; // koku (parsējumu) skaits uz iterāciju
cout << "Allocate memory for helper feature vectors ... ";
// kāds ir aptuvenais iezīmju skaits noparsētā kokā ?
FeatureVector treeFV(1000);
FeatureVector goldenFV(1000);
// FeatureVector treeFV(1572869);
// FeatureVector goldenFV(1572869);
cout << "ok" << endl;
cout << "Training: " << endl;
for(int t=0; t<T; t++)
{
// iterācijas info uz ekrāna
if(t) cout << endl;
cout << endl;
cout << "# [" << t+1 << " / " << T << "] : ";
// aizpilda lineāro sarakstu
if(t == 0 || permutate)
{
ascending.clear();
for(int i=start; i<stop; i++)
ascending.push_back(i);
}
// aizpilda permutēto sarakstu
if(permutate)
{
permutated.clear();
while(ascending.size() > 0)
{
int index = rand() % ascending.size();
permutated.push_back(ascending[index]);
ascending.erase(ascending.begin()+index);
}
}
// permutētais saraksts, vai sakārtotais-augošais
vector<int>& list = permutate ? permutated : ascending;
countPerIteration = 0; // izmantoto koku skaits uz vienu iterāciju
int sz = list.size();
int n = 0;
int parts = 20;
int part = 0;
int nextgoal = sz / parts;
for(int j : list)
{
n++;
// zelta standarts
const Tokens& golden = trainTrees[j];
// neprojektīvs
if(!allowNonProjective && !golden.projective())
{
cout << "N";
continue;
}
// izmērs pārāk liels
if(limit > 0 && golden.size() > limit)
{
cout << "!" << golden.size()-1;
continue;
}
// kopija
Tokens tree(golden);
#ifdef ANSI
// buferis, kas standarta ANSI terminālī kursoram ļauj pakāpties uz atpakaļu
RollbackOutput output;
// info strings pie progresa izvades
string postfix;
{
stringstream ss;
ss << " #" << j << ", size: " << golden.size() << " ]";
postfix = ss.str();
}
output = " [ ";
// parsēšanas mēģinājums
double duration = parse(tree, featureVector, true, postfix);
output.rollback();
#else
// parsēšanas mēģinājums
Timing timing;
timing.start();
parse(tree, featureVector, arguments.ner);
timing.stop();
double duration = timing;
#endif
cout << "."; // progresa indikātors
cout.flush();
// ja koki atšķiras
if(tree != golden)
{
// FeatureVector treeFV(1572869);
// FeatureVector goldenFV(1572869);
treeFV.clear();
goldenFV.clear();
tree.extractFeatures(treeFV);
golden.extractFeatures(goldenFV);
// pieskaita iezīmes no golden
{
const FeatureVector::Features& features = goldenFV.features();
const FeatureVector::Weights& weights = goldenFV.weights();
for(int i=0, size = features.size(); i<size; i++)
featureVector[features[i]] += weights[i];
}
// atņem iezīmes no parses mēģinājuma
{
const FeatureVector::Features& features = treeFV.features();
const FeatureVector::Weights& weights = treeFV.weights();
for(int i=0, size = features.size(); i<size; i++)
featureVector[features[i]] -= weights[i];
}
}
// ja ir notikušas izmēru izmaiņas starp w un v
if(featureVector.size() > v.size())
for(int k=0, size=featureVector.size()-v.size(); k<size; k++)
v.push_back(0);
// v += w
for(int k=0, size=featureVector.size(); k<size; k++)
v[k] += featureVector[k];
count++;
countPerIteration++;
if(n >= nextgoal)
{
part++;
cout << " (" << (int)(100*part/parts) << "%) "; // [5%]
nextgoal = (sz*(part+1))/parts;
}
}
}
// vidējošana: w = v / T*n
// double koef = 1.0/(double)count;
// for(int k=0, size=featureVector.size(); k<size; k++)
// featureVector[k] = v[k] * koef;
for(int k=0, size=featureVector.size(); k<size; k++)
featureVector[k] = v[k];
trainTreeCount = countPerIteration;
cout << " done" << endl;
}
//
// Pārbaudes funkcija
//
void TrainCase::check(const FeatureVector& featureVector)
{
const Trees& checkTrees = arguments.checkTrees;
int limit = arguments.checkLimit;
int start = arguments.checkStart;
int stop = arguments.checkStop;
bool allowNonProjective = arguments.allowCheckNonProjective;
// limits tiek norādīts derīgajos tokenus: +1 ir dēļ root tokena "*"
if(limit > 0)
limit++;
// // ja nav norādīts apstāšanās koks, tad līdz pēdējam
// if(stop <= 0)
// stop = checkTrees.size();
checkUASTotalCount = 0;
checkUASTotalMatches = 0;
int count = 0; // pārbaudīto koku skaits
cout << "Verification:" << endl;
// reproducēšanas mēģinājums
for(int j=start; j<stop; j++)
{
// zelta standarts
const Tokens& golden = checkTrees[j];
// informācija terminālī par tekošo koku
cout << setw(5) << j << " / [" << start << "," << stop << ")";
cout << setw(8) << golden.size()-1 << " # ";
bool projective = golden.projective();
if(projective)
cout << "P ";
else
cout << "NP ";
// neprojektīvs
// if(!allowNonProjective && !golden.projective())
if(!allowNonProjective && !projective)
{
cout << "Non-Projective" << endl;
continue;
}
// izmērs pārāk liels
if(limit > 0 && golden.size() > limit)
{
cout << "Too Large" << endl;
continue;
}
// neliela atstarpe
cout << " ";
cout.flush();
// kopija
Tokens tree(golden);
#ifdef ANSI
// parsēšanas mēģinājums
double duration = parse(tree, featureVector, arguments.ner);
#else
// double duration = parse(tree, featureVector, false);
Timing timing;
timing.start();
parse(tree, featureVector, arguments.ner);
timing.stop();
double duration = timing;
#endif
// TODO: remove this, for analysis only
// tree.examine(featureVector, golden);
// double similarity = tree.compare(golden);
int matches = tree.compare(golden);
checkUASTotalCount += tree.size()-1;
checkUASTotalMatches += matches;
double similarity = (double)matches/(double)(tree.size()-1);
cout << setw(8) << setprecision(4) << /* defaultfloat << */ similarity * 100 << " % ";
outputDuration(duration);
cout << endl;
checkResults.emplace_back(j, matches, tree.size()-1, duration);
count++;
}
checkTreeCount = count;
// gala rezultāta izvade terminālī
cout << "Total score: " << setprecision(4) << 100 * (double)checkUASTotalMatches/(double)checkUASTotalCount << " %" << endl;
}
//
// Treniņš + pārbaude
//
void TrainCase::run()
{
// ievadparametri: iterācijas, treniņa tokenu limits, pārbaudes tokenu limits, treniņkoku skaits, pārbaudes koku skaits
// iezīmju vektora bucket skaits
bool verify = arguments.checkTrees.valid();
bool quiet = arguments.quiet();
Trees& trainTrees = arguments.trainTrees;
Trees dummy;
// Diemžēl šo atslēgt nav iespējams, var vienīgi norādīt uz trainTrees, bet tad ir avots jaunām, iespējams, grūti nosakāmām kļūdām.
// Tad jau drīzāk uz tukšu kopu!
Trees& checkTrees = verify ? arguments.checkTrees() : dummy;
if(trainTrees.size() == 0 || (verify && checkTrees.size() == 0))
{
if(!quiet)
{
if(trainTrees.size() == 0)
cout << "Error: empty training set!" << endl;
if(verify && checkTrees.size() == 0)
cout << "Error: empty verification set!" << endl;
}
return;
}
// pārbauda start, stop vērtības
if(arguments.trainStop == 0 || arguments.trainStop > trainTrees.size())
arguments.trainStop = trainTrees.size();
else if(arguments.trainStop < 0)
arguments.trainStop = trainTrees.size() + arguments.trainStop;
if(verify)
{
if(arguments.checkStop == 0 || arguments.checkStop > checkTrees.size())
arguments.checkStop = checkTrees.size();
else if(arguments.checkStop < 0)
arguments.checkStop = checkTrees.size() + arguments.checkStop;
}
if(arguments.trainStart < 0)
arguments.trainStart = trainTrees.size() + arguments.trainStart;
if(arguments.trainStart > arguments.trainStop)
arguments.trainStart = arguments.trainStop;
if(verify)
{
if(arguments.checkStart < 0)
arguments.checkStart = checkTrees.size() + arguments.checkStart;
if(arguments.checkStart > arguments.checkStop)
arguments.checkStart = arguments.checkStop;
}
if(!quiet)
{
if(!arguments.trainCoNLL().empty())
cout << "Training tree set from " << arguments.trainCoNLL() << endl;
if(verify && !arguments.checkCoNLL().empty())
cout << "Verification tree set from " << arguments.checkCoNLL() << endl;
cout << "Will perform " << arguments.iterations << " iterations " << (arguments.permutate ? "with" : "without") << " permutations";
if(arguments.permutate)
cout << " using seed " << arguments.seed;
if(arguments.useGeneralTags)
cout << " with general tags";
cout << endl;
cout << "Training set non-projective trees " << (arguments.allowTrainNonProjective ? "included" : "excluded") << endl;
if(verify)
cout << "Verification set non-projective trees " << (arguments.allowCheckNonProjective ? "included" : "excluded") << endl;
if(arguments.trainLimit > 0)
cout << "Will limit to " << arguments.trainLimit();
else
cout << "Unlimited";
cout << " training tokens per tree" << endl;
if(verify)
{
if(arguments.checkLimit > 0)
cout << "Will limit to " << arguments.checkLimit();
else
cout << "Unlimited";
cout << " verification tokens per tree" << endl;
}
// cout << "Feature vector bucket count: " << arguments.featureVectorSize() << endl;
cout << "Training trees: [" << arguments.trainStart() << "," << arguments.trainStop() << ") of " << trainTrees.size() << " trees" << endl;
if(verify)
cout << "Verification trees: [" << arguments.checkStart() << "," << arguments.checkStop() << ") of "
<< checkTrees.size() << " trees" << endl;
}
// rezervē iezīmju vektoram atmiņu, būtiski optimālai ātrdarbībai
if(!quiet)
{
cout << "Allocate memory for feature vector ... ";
cout.flush();
}
// FeatureVector featureVector;
// FeatureVector featureVector(arguments.featureVectorSize); // TODO: vajag pieselektēt tuvāko pirmskaitli
// FeatureVector featureVector; // NOTE: lai būtu pirmskaitlis (noklusētais)
// featureVector.reserve(arguments.featureVectorSize);
// FeatureVector featureVector(arguments.featureVectorSize);
featureVector.reserve(arguments.featureVectorSize);
if(!quiet)
{
cout << "ok" << endl;
#if USE_MAP != STD_MAP
cout << "Feature vector initial bucket count: " << featureVector.bucket_count() << endl;
#endif
cout << "Identificator map size: " << arguments.getIDMap().size() << endl;
}
Timing timing;
timing.start();
train(featureVector);
timing.stop();
trainTime = timing;
timing.start();
if(verify)
check(featureVector);
timing.stop();
if(verify)
checkTime = timing;
else
checkTime = 0;
collisions = featureVector.collisions();
if(!quiet)
{
cout << "Trained with " << arguments.iterations() << " iterations " << (arguments.permutate ? "with" : "without") << " permutations";
if(arguments.permutate)
cout << " using seed " << arguments.seed;
if(arguments.useGeneralTags)
cout << " with general tags";
cout << endl;
if(arguments.trainLimit > 0)
cout << "Training set limited to " << arguments.trainLimit() << " tokens per tree" << endl;
else if(arguments.trainLimit == 0)
cout << "Training set with unlimited token count per tree" << endl;
if(verify && arguments.checkLimit > 0)
cout << "Verification set limited to " << arguments.checkLimit() << " tokens per tree" << endl;
else if(verify && arguments.checkLimit == 0)
cout << "Verification set with unlimited token count per tree" << endl;
cout << "Trained on " << trainTreeCount << " trees" << endl;
if(verify)
cout << "Verified on " << checkTreeCount << " trees" << endl;
cout << "Final feature vector size: " << featureVector.size() << endl;
#if USE_MAP != STD_MAP
cout << "Feature vector bucket count: " << featureVector.capacity() << endl;
cout << "Final feature vector collision count: " << featureVector.collisions() << endl;
#endif
cout << "Identificator map size: " << arguments.getIDMap().size() << endl;
cout << "Training time: ";
outputDuration(trainTime);
cout << endl;
if(verify)
{
cout << "Verification time: ";
outputDuration(checkTime);
cout << endl;
}
cout << "Total time: ";
outputDuration(trainTime + checkTime);
cout << endl;
}
}
//
// Rezumējums
//
void TrainCases::summary()
{
set<int> iterations;
set<int> trainLimits;
set<int> checkLimits;
set<bool> trainNonProjective;
set<bool> checkNonProjective;
int totalTokens = 0;
int totalMatchedTokens = 0;
double totalTrainTime = 0;
double totalCheckTime = 0;
int totalCheckCount = 0;
for(const TrainCase& trainCase : trainCases)
{
iterations.insert(trainCase.arguments.iterations);
trainLimits.insert(trainCase.arguments.trainLimit);
checkLimits.insert(trainCase.arguments.checkLimit);
trainNonProjective.insert(trainCase.arguments.allowTrainNonProjective);
checkNonProjective.insert(trainCase.arguments.allowCheckNonProjective);
totalCheckCount += trainCase.checkTreeCount;
totalTokens += trainCase.checkUASTotalCount;
totalMatchedTokens += trainCase.checkUASTotalMatches;
totalTrainTime += trainCase.trainTime;
totalCheckTime += trainCase.checkTime;
}
bool first;
cout << "--- SUMMARY ---" << endl;
cout << "Training set count: " << trainCases.size() << endl;
cout << "Iterations: ";
first = true;
for(int i : iterations)
{
if(!first)
cout << ", ";
cout << i;
first = true;
}
cout << endl;
cout << "Training limit: ";
first = true;
for(int limit : trainLimits)
{
if(!first)
cout << ", ";
if(limit == 0)
cout << "unlimited";
else
cout << limit;
first = true;
}
cout << endl;
cout << "Verification limit: ";
first = true;
for(int limit : checkLimits)
{
if(!first)
cout << ", ";
if(limit == 0)
cout << "unlimited";
else
cout << limit;
first = true;
}
cout << endl;
cout << "Trained on non-projective trees: ";
first = true;
for(bool allow : trainNonProjective)
{
if(!first)
cout << " and ";
cout << (allow ? "yes" : "no");
first = true;
}
cout << endl;
cout << "Verified on non-projective trees: ";
first = true;
for(bool allow : checkNonProjective)
{
if(!first)
cout << " and ";
cout << (allow ? "yes" : "no");
first = true;
}
cout << endl;
cout << "Total tree verification parses made: " << totalCheckCount << endl;
cout << "Average verification time per tree: ";
outputDuration(totalCheckTime / (double)totalCheckCount);
cout << endl;
cout << "Total parsed token count: " << totalTokens << endl;
cout << "Total matched token count: " << totalMatchedTokens << endl;
cout << "Total UAS: " << setprecision(4) << /* defaultfloat << */ 100.0*(double)totalMatchedTokens/(double)totalTokens << " %" << endl;
cout << "Total training time: ";
outputDuration(totalTrainTime);
cout << endl;
cout << "Total verification time: ";
outputDuration(totalCheckTime);
cout << endl;
cout << "Total time: ";
outputDuration(totalTrainTime + totalCheckTime);
cout << endl;
}
bool train(TrainCase::Arguments& arguments, FeatureVector& featureVector, IndexMap& idMap, streams& istreams)
{
Trees trees(idMap);
// vispirms ielasa no visām straumēm
while(streams::stream& stream = istreams.next())
{
while(stream)
stream >> trees;
}
// pēc tam var sākt treniņus
int start = 0;
int stop = trees.size();
int limit = arguments.trainLimit;
int T = arguments.iterations;
bool allowNonProjective = arguments.allowTrainNonProjective;
bool permutate = arguments.permutate;
bool quiet = arguments.quiet;
// // rezervē iezīmju vektoram atmiņu, būtiski optimālai ātrdarbībai
// cout << "Allocate memory for feature vector ... ";
// cout.flush();
// featureVector.reserve(arguments.featureVectorSize);
// cout << "ok" << endl;
// izgūst visu iezīmju precedentus treniņu kokos
if(!quiet)
{
cout << "Extracting initial features ... ";
cout.flush();
}
trees.extractFeatures(featureVector);
if(!quiet)
cout << "ok" << endl;
#if USE_MAP != STD_MAP
if(!quiet)
{
cout << "Feature vector size: " << featureVector.size() << endl;
cout << "Feature vector bucket count: " << featureVector.bucket_count() << endl;
cout << "Initial feature vector collisions: " << featureVector.collisions() << endl;
}
#endif
// limits tiek norādīts derīgajos tokenus: +1 ir dēļ root tokena "*"
if(limit > 0)
limit++;
// // ja nav norādīts apstāšanās koks, tad līdz pēdējam
// if(stop <= 0)
// stop = trainTrees.size();
// w = 0
featureVector.zero();
// summārais svaru vektors v = 0
vector<FeatureVector::Value> v(featureVector.size(), 0);
// randomizācijas sēkla
srand(arguments.seed);
// koku indeksu saraksti (darbojas kā kartes): linērais un permutētais
vector<int> permutated; // permutated map
vector<int> ascending;
int count = 0; // koku parsējumu kopskaits
int countPerIteration = 0; // koku (parsējumu) skaits uz iterāciju
if(!quiet)
cout << "Allocate memory for helper feature vectors ... ";
// kāds ir aptuvenais iezīmju skaits noparsētā kokā ?
FeatureVector treeFV(1000);
FeatureVector goldenFV(1000);
// FeatureVector treeFV(1572869);
// FeatureVector goldenFV(1572869);
if(!quiet)
{
cout << "ok" << endl;
cout << "Training: " << endl;
}
for(int t=0; t<T; t++)
{
if(!quiet)
{
// iterācijas info uz ekrāna
if(t) cout << endl;
cout << endl;
cout << "# [" << t+1 << " / " << T << "] : ";
}
// aizpilda lineāro sarakstu
if(t == 0 || permutate)
{
ascending.clear();
for(int i=start; i<stop; i++)
ascending.push_back(i);
}
// aizpilda permutēto sarakstu
if(permutate)
{
permutated.clear();
while(ascending.size() > 0)
{
int index = rand() % ascending.size();
permutated.push_back(ascending[index]);
ascending.erase(ascending.begin()+index);
}
}
// permutētais saraksts, vai sakārtotais-augošais
vector<int>& list = permutate ? permutated : ascending;
countPerIteration = 0; // izmantoto koku skaits uz vienu iterāciju
int sz = list.size();
int n = 0;
int parts = 20;
int part = 0;
int nextgoal = sz / parts;
for(int j : list)
{
n++;
// zelta standarts
const Tokens& golden = trees[j];
// neprojektīvs
if(!allowNonProjective && !golden.projective())
{
if(!quiet)
cout << "N";
continue;
}
// izmērs pārāk liels
if(limit > 0 && golden.size() > limit)
{
if(!quiet)
cout << "!" << golden.size()-1;
continue;
}
// kopija
Tokens tree(golden);
// parsēšanas mēģinājums
Timing timing;
timing.start();
parse(tree, featureVector, arguments.ner);
timing.stop();
double duration = timing;
if(!quiet)
{
cout << "."; // progresa indikātors
cout.flush();
}
// ja koki atšķiras
if(tree != golden)
{
// FeatureVector treeFV(1572869);
// FeatureVector goldenFV(1572869);
treeFV.clear();
goldenFV.clear();
tree.extractFeatures(treeFV);
golden.extractFeatures(goldenFV);
// pieskaita iezīmes no golden
{
const FeatureVector::Features& features = goldenFV.features();
const FeatureVector::Weights& weights = goldenFV.weights();
for(int i=0, size = features.size(); i<size; i++)
featureVector[features[i]] += weights[i];
}
// atņem iezīmes no parses mēģinājuma
{
const FeatureVector::Features& features = treeFV.features();
const FeatureVector::Weights& weights = treeFV.weights();
for(int i=0, size = features.size(); i<size; i++)
featureVector[features[i]] -= weights[i];
}
}
// ja ir notikušas izmēru izmaiņas starp w un v
if(featureVector.size() > v.size())
for(int k=0, size=featureVector.size()-v.size(); k<size; k++)
v.push_back(0);
// v += w
for(int k=0, size=featureVector.size(); k<size; k++)
v[k] += featureVector[k];
count++;
countPerIteration++;
if(n >= nextgoal)
{
part++;
if(!quiet)
cout << " (" << (int)(100*part/parts) << "%) "; // [5%]
nextgoal = (sz*(part+1))/parts;
}
}
}
// vidējošana: w = v / T*n
// double koef = 1.0/(double)count;
// for(int k=0, size=featureVector.size(); k<size; k++)
// featureVector[k] = v[k] * koef;
for(int k=0, size=featureVector.size(); k<size; k++)
featureVector[k] = v[k];
featureVector.save("fvnew");
// trainTreeCount = countPerIteration;
if(!quiet)
cout << " done" << endl;
return true;
}
bool verify(TrainCase::Arguments& arguments, const FeatureVector& featureVector, const IndexMap& idMap_, streams& istreams)
{
int limit = arguments.checkLimit;
int start = arguments.checkStart;
int stop = arguments.checkStop;
bool allowNonProjective = arguments.allowCheckNonProjective;
// limits tiek norādīts derīgajos tokenus: +1 ir dēļ root tokena "*"
if(limit > 0)
limit++;
int checkUASTotalMatches;
int checkUASTotalCount;
checkUASTotalCount = 0;
checkUASTotalMatches = 0;
int count = 0; // pārbaudīto koku skaits
int j = 0;
cout << "Verification:" << endl;
// pa vienam kokam no ievadstraumes, parsē, rezultāts izvadstraumē
while(streams::stream& stream = istreams.next())
{
while(stream)
{
// index apakškarte, kuru var pārvietot arī uz parent scope, ja tas palielina ātrdarbību
// doma ir tāda, ka katrs ievadkoks ir neatkarīgs no otra, tāpēc kad viens ir pabeigts,
// tad nav vajadzīgs uzglabāt nākamā koka identifikātoru informāciju, rezultātā
// identifikātoru skaits nepalielinās un nav risks potenciālam overflow
IndexMap idMap(idMap_);
Tokens golden(idMap);
try
{
stream >> golden;
if(!golden)
continue;
// parse(tree, featureVector);
// zelta standarts
// const Tokens& golden = checkTrees[j];
// informācija terminālī par tekošo koku
cout << setw(5) << j << " / [" << start << "," << stop << ")";
cout << setw(8) << golden.size()-1 << " # ";
bool projective = golden.projective();