-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPosMaxEn.cpp
More file actions
3811 lines (3253 loc) · 83.7 KB
/
PosMaxEn.cpp
File metadata and controls
3811 lines (3253 loc) · 83.7 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
#include "PosMaxEn.h"
//#include "DictAndConvert.h"
#include <fstream>
#include <set>
#include "Verify.h"
#include <time.h>
#include <cstdlib>
#include <cstdio>
#include <ext/numeric>
#include <iomanip>
#include <stdlib.h>
#include <float.h>
#include "mwutool.h"
//#include "lbfgs.h"
using namespace std;
using namespace HitZy;
map<int, int> map_pos_gold;
map<string, vector< int > > test_dict;
int g_debug = 0;
int g_decodingMethod = 0;
int g_context = 0;
int g_combine = 0;
string g_mwu ="mwu";
double g_filter_value = -1.0;
vector<tag_Options> g_all_result;
int g_event_split = 120000000;
//int g_event_split = 250000;
double result_fb_0 = 0;
double result_nb_0 = 0;
double result_fb_1 = 0;
double result_nb_1 = 0;
double result_fb_2 = 0;
double result_nb_2 = 0;
double result_fb_3 = 0;
double result_nb_3 = 0;
double result_fb_4 = 0;
double result_nb_4 = 0;
double threshold_fb_0 = 0;
double threshold_nb_0 = 0;
double threshold_fb_1 = 0;
double threshold_nb_1 = 0;
double threshold_fb_2 = 0;
double threshold_nb_2 = 0;
double threshold_fb_3 = 0;
double threshold_nb_3 = 0;
double threshold_fb_4 = 0;
double threshold_nb_4 = 0;
fstream file_0;
fstream file_1;
fstream file_2;
fstream file_3;
fstream file_4;
CPosMaxEn::CPosMaxEn(void)
{
g_TagIDMapFileName = "model/"+APPLICATION+"/ME_TagIDMap_"+g_mwu;
string title = "model/";
if(g_context == 1)
{
m_fileNameModel = title+APPLICATION+"/MEModel_"+g_mwu+"_Con.bin";
}
else
{
m_fileNameModel = title+APPLICATION+"/MEModel_"+g_mwu+".bin";
}
m_fileNameModelOption = title+APPLICATION+"/MEModelOption.bin";
options_array.resize(5000);
m_BeginSample.word = START_WORD;
m_BeginSample.tag = START_TAG;
m_BeginSample.middle ="<DUMMY_CONTEXT>";
m_EndSample.word = END_WORD;
m_EndSample.tag = END_TAG;
/*m_BeginSample.word = "";
m_BeginSample.tag = "";
m_BeginSample.middle ="<DUMMY_CONTEXT>";
m_EndSample.word = "";
m_EndSample.tag = "";*/
m_Heap = new PriorHeap;
m_NewHeap = new PriorHeap;
//if I set g_Bigram true, I will add START_TAG to the taglist;
//g_Bigram is used mainly in CRF to decide Unigram and Bigram model.
g_Bigram = true;
}
CPosMaxEn::~CPosMaxEn(void)
{
delete m_Heap;
delete m_NewHeap;
}
/**
add sentence boundary, beyond boundary, set it as #B or #E!
*/
void CPosMaxEn::FillInWnd(SAMPLE * pSample[], int index)
{
pSample[WND_INDEX] = &m_vectSamples[index];
for(int i = WND_INDEX-1;i>=0;i--)
{
if(m_vectSamples[index-(2-i)].word == "##")
{
for(int j = i;j>=0;j--)
{
pSample[j] =&m_BeginSample;
}
i = 0;
}
else
{
pSample[i] = &m_vectSamples[index-(2-i)];
}
}
for(int i = WND_INDEX+1;i<WND_SIZE;i++)
{
if(m_vectSamples[index+(i-2)].word == "##")
{
for(int j = i;j<WND_SIZE;j++)
{
pSample[j] =&m_EndSample;
}
i = WND_SIZE;
}
else
{
pSample[i] = &m_vectSamples[index+(i-2)];
}
}
}
template<class T>
bool CPosMaxEn::GetFeatureFromTemplate(T &ft, SAMPLE * wnd[], string & templateStr)
{
vector<string> temp;
String_SeperateToList_WithTrim(templateStr,temp,":");
ft.predType = atoi(temp[0].c_str());
string content = "";
int pos_index,con_index;
for(int i = 1;i<temp.size();i++)
{
AnalysizeTemplateString(temp[i],pos_index,con_index);
if(con_index ==0 && wnd[pos_index+WND_INDEX]->word != "")
{
content+=wnd[pos_index+WND_INDEX]->word;
content +=SPLIT_TAG;
}
else if(con_index ==1 && wnd[pos_index+WND_INDEX]->middle =="")
{
content+=wnd[pos_index+WND_INDEX]->tag;
content +=SPLIT_TAG;
}
else if(con_index ==1 /*&& wnd[WND_INDEX]->middle !=""*/&&wnd[pos_index+WND_INDEX]->middle!="")
{
content+=wnd[pos_index+WND_INDEX]->middle;
content +=SPLIT_TAG;
}
else if(con_index ==2&& wnd[pos_index+WND_INDEX]->tag!="")
{
content+=wnd[pos_index+WND_INDEX]->tag;
content +=SPLIT_TAG;
}
else
{
// for some bigram features [-2,1]:[-1,1], if one component [-1,1] don't exist, the
// whole feature will be empty, you can skip the other loop and jump out.
content = "";
break;
}
}
if(content.length()>0)
{
content.erase(content.length()-1);
ft.predData = content;
return true;
}
return false;
}
void CPosMaxEn::ExtractFeatureFromWnd(SAMPLE * wnd[])
{
FEATURE ft;
ft.outTag = TagToID(wnd[WND_INDEX]->tag);
for(int i = 0;i<m_templateVect.size();i++)
{
ft.predData = "";
if(GetFeatureFromTemplate(ft, wnd,m_templateVect[i]))
{
LookupAndUpdateFeature(ft);
}
}
}
int CPosMaxEn::SaveModel(int AFileIndex)
{
fstream f1;
string mModel_FeatureName = File_FileName_AddIndex(m_fileNameModel, (int)g_sigma);
mModel_FeatureName = File_FileName_AddIndex(mModel_FeatureName, AFileIndex);
f1.open( mModel_FeatureName.c_str(),ios_base::out|ios_base::binary);
VERIFY_FILE(f1);
//////////////////////////////////////////////////
vector<FEATURE>::iterator vIter;
vector<FEATURE>::iterator vIterBegin = m_vectFeatures.begin();
vector<FEATURE>::iterator vIterEnd = m_vectFeatures.end();
for(vIter = vIterBegin;vIter!=vIterEnd;vIter++)
{
f1<<*vIter;
}
/////////////////////////////////////////////////
f1.close();
/* FILE * fp;
string mModel_OptionFileName = File_FileName_AddIndex(m_fileNameModelOption, AFileIndex);
fp = fopen(mModel_OptionFileName.c_str(), "wb");
fwrite(&m_corr, sizeof(m_corr), 1, fp);
fwrite(&m_maxFeatureCount, sizeof(m_maxFeatureCount), 1, fp);
fwrite(&m_minFeatureCount, sizeof(m_minFeatureCount), 1, fp);
fwrite(&m_correctFeatureE, sizeof(m_correctFeatureE), 1, fp);
fwrite(&m_correctFeatureAlfa, sizeof(m_correctFeatureAlfa), 1, fp);
fclose(fp);*/
return 0;
}
int CPosMaxEn::SaveFeatures(string AFeatureName)
{
fstream f1;
f1.open( AFeatureName.c_str(),ios_base::out|ios_base::binary);
VERIFY_FILE(f1);
//////////////////////////////////////////////////
vector<FEATURE>::iterator vIter;
vector<FEATURE>::iterator vIterBegin = m_vectFeatures.begin();
vector<FEATURE>::iterator vIterEnd = m_vectFeatures.end();
for(vIter = vIterBegin;vIter!=vIterEnd;vIter++)
{
f1<<*vIter;
}
/////////////////////////////////////////////////
f1.close();
return 0;
}
void CPosMaxEn::ExtractEventFromWnd(SAMPLE * wnd[])
{
EVENT ev;
ev.outTag = TagToID(wnd[WND_INDEX]->tag);
ev.count = 1;
int numPredicate = 0;
PREDICATE predicate;
int mLoc;
for(int i = 0;i<m_templateVect.size();i++)
{
predicate.predData = "";
if(GetFeatureFromTemplate(predicate, wnd,m_templateVect[i]))
{
mLoc = IndexOfPredicate(predicate);
if (mLoc != -1)
{
ev.vectIndexPredicate.push_back(mLoc);
numPredicate++;
}
}
}
if(numPredicate >0)
{
m_EventList.WriteEvent(ev);
}
else
{
cout<<"delete one event"<<endl;
}
}
double CPosMaxEn::FeatureModelExpecation(double & log_likelihood)
{
double pab[m_numTag];
int corr[m_numTag];
int mPos=0, mNeg=0;
/////////////////////////////////////////////////////////////
EVENT mCurEvent;
m_EventList.OpenEventList(OpenMode_Read);
int sumEvent = 0;
for(int i= 0;i<m_numTag;i++)
{
pab[i] = 0.0f;
corr[i] = m_maxFeatureCount;
}
vector<int> pos_vect;
int bi_array[m_numTag+10][10];
//cout<<"beging to read each event"<<endl;
for(int i= 0;i<m_numTag;i++)
{
pab[i] = 1.0;
corr[i] = m_maxFeatureCount;
}
while (m_EventList.ReadEvent(mCurEvent) == true)
{
pos_vect.clear();
sumEvent++;
if(m_EventList.TotalEventCount()>1000000 && sumEvent% (m_EventList.TotalEventCount()/10) == 0)
{
cout<< "Training event = "<<sumEvent<<endl;
}
for(int i = 0;i<mCurEvent.vectIndexPredicate.size();i++)
{
PREDICATE & mCurPredicate = m_vectPredicates[mCurEvent.vectIndexPredicate[i]]; //找到当前Predicate引用
vector<pair<int,int> >::iterator s1_Iter = mCurPredicate.indexFeature.begin();
while(s1_Iter != mCurPredicate.indexFeature.end())
{
pab[s1_Iter->first]+=m_vectFeatures[s1_Iter->second].alpha;
if(corr[s1_Iter->first]==m_maxFeatureCount)
{
pos_vect.push_back(s1_Iter->first);
pab[s1_Iter->first]-=1.0;
}
bi_array[s1_Iter->first][m_maxFeatureCount-corr[s1_Iter->first]] = s1_Iter->second;
corr[s1_Iter->first]--;
s1_Iter++;
}
//
}
///////////////
double psum = 0.0;
vector<int>::iterator it;
for(it=pos_vect.begin();it!=pos_vect.end();it++)
{
int i = *it;
pab[i] = exp(pab[i]);
psum += pab[i];
}
psum += (m_numTag-pos_vect.size());
log_likelihood -= log(pab[mCurEvent.outTag]/psum);
for(it=pos_vect.begin();it!=pos_vect.end();it++)
{
int k = *it;
for(int j = 0;j<(m_maxFeatureCount-corr[k]);j++)
{
int point = bi_array[k][j];
m_model_expectation[point] +=pab[k]/psum;
}
pab[k] = 1.0;
corr[k] = m_maxFeatureCount;
}
}
m_EventList.CloseEventList();
return (double) 0 ;
}
double CPosMaxEn::GIS(double& likelihood)
{
double log_likelihood;
double prevision = FeatureModelExpecation(likelihood);
////////////////////////////////////////////////////////////////
//update lamda of each feature.
double m_inv_maxFeatureCount = 1.0f / m_maxFeatureCount;
for (int k = 0; k < m_vectFeatures.size(); k ++)
{
FEATURE & mCurFeature = m_vectFeatures[k];
if(m_model_expectation[k]>0.0f)
{
mCurFeature.alpha += m_inv_maxFeatureCount * (m_feature_count_log[k] - log(m_model_expectation[k]));
}
}
fill(m_model_expectation.begin(),m_model_expectation.end(),0.0f);
return prevision;
}
int CPosMaxEn::LoadPreTriggerPair(void)
{
const string mFileName = "PosMaxEnData\\PreTriggerPair.txt";
if (File_Exist(mFileName) == false)
{
cout << "Can not open file :" << mFileName << endl;
return -1;
}
fstream f1;
f1.open( mFileName.c_str(),ios_base::in);
//VERIFY_FILE(f1);
string A;
string B;
string pos;
string key;
while(true)
{
f1>>A;
if(f1.eof())
{
break;
}
f1>>B;
f1>>pos;
key = A+"+"+B+"+"+pos;
m_hashPreTriggers.insert(key);
}
f1.close();
return 0;
}
int CPosMaxEn::LoadSucTriggerPair(void)
{
const string mFileName = "PosMaxEnData\\SucTriggerPair.txt";
if (File_Exist(mFileName) == false)
{
cout << "Can not open file :" << mFileName << endl;
return -1;
}
fstream f1;
f1.open( mFileName.c_str(),ios_base::in);
//VERIFY_FILE(f1);
string A;
string B;
string pos;
string key;
while(true)
{
f1>>A;
if(f1.eof())
{
break;
}
f1>>B;
f1>>pos;
key = A+"+"+B+"+"+pos;
m_hashSucTriggers.insert(key);
}
f1.close();
return 0;
}
bool CPosMaxEn::FindInPreTriggerPairs(string& key)
{
if(m_hashPreTriggers.find(key)!=m_hashPreTriggers.end())
{
return true;
}
return false;
}
bool CPosMaxEn::FindInSucTriggerPairs(string& key)
{
if(m_hashSucTriggers.find(key)!=m_hashSucTriggers.end())
{
return true;
}
return false;
}
void CPosMaxEn::JHeapClear(PriorHeap *AHeap)
{ //
while (AHeap->size() > 0)
{
AHeap->pop();
}
}
int CPosMaxEn::LoadDict(void)
{
FILE* fsample;
string fileName = "model/"+APPLICATION+"/dict";
fsample = fopen(fileName.c_str(), "rt"); //
if (fsample == NULL)
{
cout << "Cannot open sample file:" << endl;
cout << "Cannot continue run...." << endl;
throw ("Cannot open sample file");
return -1;
}
string word = "";
while (! feof(fsample))
{
char line[10000];
fgets(line,10000,fsample);
string sline;
sline.assign(line);
vector<string> vectline;
String_SeperateToList_WithTrim(sline,vectline," ");
word = vectline[0];
int numPos= atoi(vectline[1].c_str());
vector<int> posVector;
for(int i = 0;i<numPos ;i++)
{
string pos = vectline[2+i];
if(m_mapPosID.find(pos) != m_mapPosID.end())
{
posVector.push_back(TagToID(pos));
}
}
pair<string, vector<int> > pairT;
pairT.first = word;
pairT.second = posVector;
test_dict.insert(pairT);
}
////////////////////////////////////////////////
fclose(fsample);
cout << "Read Dict OK" << endl;
return 1;
}
int CPosMaxEn::Continue_TrainModel(string& fileName,int con_num)
{
////////////////////////////////////////////
//the first step;
GetPosList(fileName);
m_numTag = LoadPosTag(g_TagIDMapFileName);
cout<<"the number of tag is "<<m_numTag<<endl;
cout<<"The TagIDMap.txt has been built"<<endl;
//load template file
LoadTemplate(g_templateFileName);
///////////////////////////////////////////////////////
//the second step
LoadModel(con_num);
const string mFilterFeatureName = "model/"+APPLICATION+"/FilterFeature.bin";
SaveFeatures(mFilterFeatureName);
GetPredictsFromFeatures();
cout << "Unload Features ...." ;
m_vectFeatures.clear();
cout << " OK " << endl;
//m_EventList.SetEventOperatorMode(OperatorMode_File);
////////////////////////////////////////////////////////////
//the fourth step
CollectEvents(fileName);
LoadFeatures(mFilterFeatureName, false);
cout << " OK " << endl;
cout << "Begin training ..... " << endl;
// while(true)
double min = 0.0,na,delta;
double b = 0.0;
for(int j=0; j<100; j++)
{
//na = GIS();
cout<<"the "<<j<<" na="<<na<<endl;
delta = na-b;
cout<<"第"<<j<<"迭代"<<" 精度:"<<delta<<endl;
b = na;
if( delta<=min )
{
cout<<"The Model has reached at the precision"<<endl;
cout<<"The times of iteration is: "<<j+1<<endl;
break;
}
if ((j + 1) % 3 == 0) {SaveModel(con_num+j + 1);}
}
cout << "Save Model....." ;
SaveModel(0);
SaveFeaturesToTxt("model/"+APPLICATION+"/LastFeatures.txt");
cout << " OK " << endl;
return 0;
}
int CPosMaxEn::GetTagFromEvents()
{
EVENT mCurEvent;
m_EventList.OpenEventList(OpenMode_Read);
map<int,int> ZyTagMap;
while (m_EventList.ReadEvent(mCurEvent) == true)
{
if(ZyTagMap.find(mCurEvent.outTag) == ZyTagMap.end())
{
ZyTagMap.insert(pair<int,int> (mCurEvent.outTag,1));
}
}
m_EventList.CloseEventList();
return ZyTagMap.size();
}
int CPosMaxEn::TrainModel(string& fileName)
{
cout << "Training......" << endl;
////////////////////////////////////////////
//Get Tag and ID map and load template file
GetPosList(fileName);
m_numTag = LoadPosTag(g_TagIDMapFileName);
cout<<"the number of tag is "<<m_numTag<<endl;
LoadTemplate(g_templateFileName);
// GetDict(fileName);
cout<<"************************************************"<<endl;
///////////////////////////////////////////////////////
//Get and filter all the features from training corpora
ReadSamplesAndCollectFeature(fileName);
FilterFeatures();
const string mFilterFeatureName = "model/"+APPLICATION+"/FilterFeature.bin";
SaveFeatures(mFilterFeatureName);
if(g_context == 1)
SaveFeaturesToTxt("model/"+APPLICATION+"/Features_Con.txt");
SaveFeaturesToTxt("model/"+APPLICATION+"/Features.txt");
//output the text and binary format of features. you can check features in text file manually.
cout<<"The Features.txt has been built"<<endl;
cout<<"************************************************"<<endl;
////////////////////////////////////////////////////////////
//Get predicts from Features
GetPredictsFromFeatures();
cout<<"************************************************"<<endl;
////////////////////////////////////////////////////////////
//Get Event from training corpora
CollectEvents(fileName);
cout<<"Collecting Events is over"<<endl;
cout<<"************************************************"<<endl;
//cout<<"number of tag from event is"<<GetTagFromEvents()<<endl;
////////////////////////////////////////////////
//get the m_maxFeatureCount through loop all events
//GetCorrectionOptions();
///////////////////////////////////////////////////
//selection of training method
if(g_gis)
{
GIS_Estimate();
}
else
{
//LBFGS_Estimate();
LBFGS_Estimate_C();
}
cout << "Save the last model" ;
//SaveModel(0);
SaveFeaturesToTxt("model/"+APPLICATION+"/LastFeatures.txt");
cout << "Training is ok" << endl;
return 0;
}
void CPosMaxEn::LBFGS_Estimate_C(void)
{
cout << "Begin LBFGS training ..... " << endl;
int n = m_vectFeatures.size();
double* g = new double[n];
double* x = new double[n];
for(int j = 0;j<n;j++)
{
x[j] = m_vectFeatures[j].alpha ;
}
int m = 5;
double f;
int correct;
cout<<"num"<<"\t"<<"log-likelihood"<<"\t"<<"accuracy"<<endl;
int flag_LBFGS = 0;
int j = 0;
m_numFeatures = m_vectFeatures.size();
int hessian = 5;
int ws_size = m_numFeatures * (2 * hessian + 1) + 2 * hessian;
double* ws = new double[ws_size];
double* diag = new double[m_numFeatures];
int * iprint = new int[2];
int iflag = 0;
int acc_max = 0;
int acc_file_index = 0;
for(j=0; j<g_iteration; j++)
{
f = 0.0;
correct = 0;
//cout<<"memory has been allocated"<<endl;
double acc = FeatureModelExpecation(f);
cout<<j<<"\t";
cout<<setw(10)<<-1*f<<"\t";
cout<<acc<<endl;
for(int index = 0;index<n;index++)
{
g[index] = m_model_expectation[index] - m_feature_count[index];
}
if(g_sigma>0.0f)
{
for(int index = 0;index<n;index++)
{
double penality = x[index]/g_sigma;
g[index] += penality;
f+=(penality*x[index])/2;
}
}
double xtol = DBL_EPSILON; // machine precision
double eps_for_convergence = 0.00001;
int diagco = 0;
lbfgs(&m_numFeatures, &hessian, x, &f, g, &diagco, diag, iprint, &eps_for_convergence, &xtol, ws, &iflag);
if (iflag < 0) {
cout<<"lbfgs routine stops with an error"<<endl;
flag_LBFGS = 1;
break;
// throw runtime_error("lbfgs routine stops with an error");
} else if (iflag == 0) {
cout<<"Training terminats succesfully i"<<endl;
flag_LBFGS = 2;
break;
}
fill(m_model_expectation.begin(),m_model_expectation.end(),0.0f);
for(int index = 0;index<n;index++)
{
m_vectFeatures[index].alpha = x[index];
}
if ((j + 1) % 20 == 0 && g_syn_flag == 1)
{
cerr<<" iter_num="<<j+1<<" ";
if(g_decodingMethod == 0 ||g_decodingMethod == 1)
{
TagFile(g_testingFileName,j+1);
}
if(g_decodingMethod == 2||g_decodingMethod == 3 ||
g_decodingMethod == 4||g_decodingMethod == 5 )
{
FB_FilterFile(g_testingFileName,j+1);
}
if(g_right>acc_max)
{
acc_max = g_right;
acc_file_index = j+1;
int f_index = int(g_sigma)+1;
string mPosFileName = File_FileName_AddSuffix(g_testingFileName, "_ME");
string oldf = File_FileName_AddIndex(mPosFileName, j+1);
string newf = File_FileName_AddIndex(mPosFileName, f_index);
//rename(oldf.c_str(),newf.c_str());
//SaveModel(f_index);
}
m_numTag = LoadPosTag(g_TagIDMapFileName);
SaveModel(j+1);
}
}
int f_index = int(g_sigma)+1;
string mPosFileName = File_FileName_AddSuffix(g_testingFileName, "_ME");
string oldf = File_FileName_AddIndex(mPosFileName, j+1);
string newf = File_FileName_AddIndex(mPosFileName, f_index);
rename(oldf.c_str(),newf.c_str());
if (flag_LBFGS> 0 && g_syn_flag == 1)
{
cerr<<" iter_num="<<j+1<<" ";
if(g_decodingMethod == 0 ||g_decodingMethod == 1)
{
TagFile(g_testingFileName,j+1);
}
if(g_decodingMethod == 2 || g_decodingMethod == 3 ||
g_decodingMethod == 4 || g_decodingMethod == 5 )
{
FB_FilterFile(g_testingFileName,j+1);
}
}
if(flag_LBFGS == 1)
{
cerr<<"g_templateFileName="<<g_templateFileName;
cerr<<" c="<<g_threshold;
cerr<<" g="<<g_sigma;
cerr<<" iter_num="<<j+1;
cerr<<" "<<-1<<endl;
}
delete [] g;
delete [] ws;
delete [] diag;
delete [] iprint;
}
void CPosMaxEn::GIS_Estimate(void)
{
cout << "Begin GIS training ..... " << endl;
double min = 0.0,acc,likelihood;
cout<<"num"<<"\t"<<"log-likelihood"<<"\t"<<"accuracy"<<endl;
for(int j=0; j<g_iteration; j++)
{
acc = GIS(likelihood);
cout<<j<<"\t";
cout<<setw(10)<<-1*likelihood<<"\t";
cout<<acc<<endl;
if ((j + 1) % 20 == 0 && g_syn_flag == 1)
{
g_right = 0;
g_sum = 0;
TagFile(g_testingFileName,j+1);
m_numTag = LoadPosTag(g_TagIDMapFileName);
cerr<<"g_templateFileName="<<g_templateFileName;
cerr<<" c="<<g_threshold;
cerr<<" g="<<g_sigma;
cerr<<" iter_num="<<j+1;
cerr<<" "<<double(g_right*100)/g_sum<<endl;
}
}
}
int CPosMaxEn::CollectEvents(string& fileName)
{
cout<<"Collect Events .........."<<endl;
SAMPLE* wnd[WND_SIZE];
for (int k = 0; k < WND_SIZE; k ++)
{
wnd[k] = 0;
}
// 6000000 means that the training file is big enough, we can't load all events into the memory. we use file on disk to store all events.
if (g_sumTrainLine > g_event_split) { m_EventList.SetEventOperatorMode(OperatorMode_File); }
m_EventList.OpenEventList(OpenMode_Write);
int mNewEventCount = 0;
fstream fsample;
fsample.open(fileName.c_str(),ios::in);
VERIFY_FILE(fsample);
SAMPLE mSample;
m_vectSamples.clear();
m_vectSamples.push_back(m_BeginSample);
m_vectSamples.push_back(m_BeginSample);
int sumTrainLine = 0;
do
{
sumTrainLine ++;
if(sumTrainLine % 10000 == 0)
{
cout << ".";
cout.flush();
}
if(sumTrainLine % 100000 == 0)
{
cout << sumTrainLine;
cout.flush();
}
char line[1000];
fsample.getline(line,1000);
string sline;
sline.assign(line);
if(sline == ""||sline == "\n")
{
continue;
}
vector<string> vectline;
String_SeperateToList_WithTrim(sline,vectline," ");
mSample.word = vectline[0];
if(mSample.word.substr(0,3) == SEN_SPLIT)
{
m_vectSamples.push_back(m_EndSample);
m_vectSamples.push_back(m_EndSample);
for(int i = 0;i<m_vectSamples.size()-4;i++)
{
wnd[0] = &m_vectSamples[i];
wnd[1] = &m_vectSamples[i+1];
wnd[2] = &m_vectSamples[i+2];
wnd[3] = &m_vectSamples[i+3];
wnd[4] = &m_vectSamples[i+4];
{
ExtractEventFromWnd(wnd);
}
}
m_vectSamples.clear();
m_vectSamples.push_back(m_BeginSample);
m_vectSamples.push_back(m_BeginSample);
}
else
{
if(vectline.size()>2)
{
mSample.middle = vectline[vectline.size()-2];
}
mSample.tag = vectline[vectline.size()-1];
m_vectSamples.push_back(mSample);
}
}while(!fsample.eof());
////////////////////////////////////////////////
fsample.close();
if(m_vectSamples.size()>0)
{
m_vectSamples.push_back(m_EndSample);
m_vectSamples.push_back(m_EndSample);
for(int i = 0;i<m_vectSamples.size()-4;i++)
{
wnd[0] = &m_vectSamples[i];
wnd[1] = &m_vectSamples[i+1];
wnd[2] = &m_vectSamples[i+2];
wnd[3] = &m_vectSamples[i+3];
wnd[4] = &m_vectSamples[i+4];
{
ExtractEventFromWnd(wnd);
}
}
}
m_EventList.CloseEventList();
cout << "Events Count is " << m_EventList.TotalEventCount() << endl;
cout<<"Collect Events is ok"<<endl;