bllip-parser / first-stage / TRAIN / trainRsUtils.C

  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
/*
 * Copyright 1999, 2005 Brown University, Providence, RI.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.  You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

#include "trainRsUtils.h"
/* for a given history, as specified by a tree, for each feature f_i record
   how often it was used. */
int pass;
int whichInt;
int sentenceCount;
int c_Val;
bool procGSwitch = false;
FeatureTree* tRoot = NULL;
ECString conditionedType;
InputTree* curTree = NULL;
TrData trData[MAXNUMFS][15];
float unsmoothedPs[MAXNUMFS];
float lambdas[MAXNUMFS];
int bucketVals[MAXNUMFS];
bool prune = false;
vector<InputTree*> sentence;
int endPos;
float totForFeat[20];
float prevMeanSq[20];
float curMeanSq[20];
int done[20] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
		0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
StringSet wordSet;

bool
inWordSet(int i)
{
  const ECString& w = Pst::fromInt(i);
  if(wordSet.find(w) == wordSet.end()) return false;
  return true;
}


void
makeSent(InputTree* tree)
{
  sentence.clear();
  endPos = 0;
  wordsFromTree(tree);
  assert(endPos == tree->finish());
}

void
wordsFromTree(InputTree* tree)
{
  if(tree->word() != "")
    {
      sentence.push_back(tree);
      endPos++;
      return;
    }
  InputTreesIter subTreeIter = tree->subTrees().begin();
  for( ; subTreeIter != tree->subTrees().end() ; subTreeIter++ )
    {
      InputTree* subTree = *subTreeIter;
      wordsFromTree(subTree);
    }
}

void
processG(bool getProb, int whichInt, int i, FeatureTree* ginfo[], TreeHist* treeh, int cVal)
{
  ginfo[i] = NULL;
  Feature* feat = Feature::fromInt(i, whichInt); 
  // e.g., g(rtlu) starts from where g(rtl) left off (after tl)
  int searchStartInd = feat->startPos;
  FeatureTree* strt = ginfo[searchStartInd];
  bucketVals[i] = 0;
  lambdas[i] = 0;
  unsmoothedPs[i] = 0;
  if(!strt)
    {
      if(i == 1) cerr << "no start for i = 1\n" << *curTree << endl;
      //if (getProb)unsmoothedPs[i] = unsmoothedPs[i-1]; //???;
      return;
    }
  SubFeature* sf = SubFeature::fromInt(feat->subFeat, whichInt);
  int nfeatV = (*(sf->fun))(treeh);
  //if(procGSwitch) cerr << "pg " << i << ", " << cVal << ", " << nfeatV << endl;
  FeatureTree* histPt = strt->follow(nfeatV, feat->auxCnt); 
  ginfo[i] = histPt;
  if(i == 1)
    {
      unsmoothedPs[0]-0;
      /*
      if (!getProb) unsmoothedPs[0] = 0;
      else unsmoothedPs[0] = 1;
      */
      if (histPt == NULL) {
            // cerr << "histPt was null" << endl;
            unsmoothedPs[1] = .0001;
            return;
      }

      FeatMap::iterator fti1 = histPt->feats.find(cVal);
      float unsmoothedVal1;
      if(fti1 == histPt->feats.end()) unsmoothedVal1 = 0;
      else 
	{
	  /*
	  if (getProb) unsmoothedVal1 = (*fti1).second.g()-1;
	  else unsmoothedVal1 = (*fti1).second.g();
	  */
	  unsmoothedVal1 = (*fti1).second.g();
	}
      unsmoothedPs[1] = unsmoothedVal1;
      lambdas[1] = 1;
      if(unsmoothedPs[1] == 0)
	{
	  
	  /*if(pass == 0)
	    cerr << "Zero at level 1 " << treeh->pos
	    << "\n" << *curTree << endl;*/
	  
	  unsmoothedPs[1] = .0001;
	}
      /*
      if (getProb){
	//cerr <<i<< " " << nfeatV << " " << cVal << " "<< smoothedPs[1] << endl;
	for(int j = 2; j <= Feature::total[whichInt] ; j++)
	  unsmoothedPs[j] = 0;
      }
      */
      return;
    }
  if(!histPt)
    {
      if (getProb){
	unsmoothedPs[i] = unsmoothedPs[i-1]; //???;
      }
      return;
    }
  int b;
  if(Feature::isLM || getProb)
    {
      int sz = histPt->feats.size();
      assert(sz > 0);
      float estm = ((float)histPt->count / (float)sz);
      b = Smoother::bucket(estm,whichInt,i);
    }
  else
    {
      float estm = histPt->count * unsmoothedPs[1]; 
      b = Smoother::bucket(estm);
    }
  FeatMap::iterator fti = histPt->feats.find(cVal);
  float unsmoothedVal;
  if(fti == histPt->feats.end()) unsmoothedVal = 0;
  else unsmoothedVal = (*fti).second.g();
  float lam = Feature::getLambda(whichInt, i, b);
  lambdas[i] = lam;

  if (!getProb){
    unsmoothedPs[i] = unsmoothedVal;
    bucketVals[i] = b;
    //if(procGSwitch)   cerr << i << " " << nfeatV << " " << histPt->featureInt << " "
    // << estm << " " << b << " " << unsmoothedVal << endl;
  }
  else{
  
    float uspathprob = lam*unsmoothedVal;
    float osmoothedVal = unsmoothedPs[i-1]; //???;
    float smpathprob = (1-lam)*osmoothedVal;
    float nsmoothedVal = uspathprob+smpathprob;
    //cerr << i << " " << nfeatV << " " << histPt->featureInt << " "
    //   << estm << " " << b << " " << unsmoothedVal
    //   << " " << nsmoothedVal << endl;
    unsmoothedPs[i] = nsmoothedVal;

  }
    }


void
callProcG(TreeHist* treeh)
{
  FeatureTree* ginfo[MAXNUMFS];
  ginfo[0] = FeatureTree::root(); 
  int cVal = (*Feature::conditionedEvent)(treeh);
  if(cVal < 0) return;
  int i;
  for(i = 1 ; i <= Feature::total[Feature::whichInt] ; i++) {
    processG(0, Feature::whichInt, i, ginfo, treeh, cVal);
  }
  double total = 0;
  double postLam[MAXNUMFS];
  double percents[MAXNUMFS];
  double remainingProb = 1.0;
  for(i = Feature::total[Feature::whichInt] ; i > 0 ; i--)
    {
      postLam[i] = unsmoothedPs[i]*(remainingProb*lambdas[i]);
      total += postLam[i];
      remainingProb *= 1-lambdas[i];
    }
  remainingProb = 1.0;
  for(i = Feature::total[Feature::whichInt] ; i > 0 ; i--)
    {
      int b = bucketVals[i];
      if(!procGSwitch)
	{
	  trData[i][b].c++;
	  continue;
	}
      trData[i][b].c +=remainingProb;
      double incr = 0;
      if(total*remainingProb > 0)
	incr = postLam[i]/total*remainingProb;
      assert(incr >= 0);
      trData[i][b].pm += incr;
      remainingProb *= 1-lambdas[i];
      total -= postLam[i];
      if(total < 0)
	{
	  //cerr << "Bad total " << total << endl;
	  total = 0;
	}
    }
}

void
gatherFfCounts(InputTree* tree, int inHpos)
{
  InputTrees& st = tree->subTrees();;
  InputTrees::iterator  subTreeIter= st.begin();
  InputTree  *subTree;
  int hpos = 0;
  if(st.size() != 0) hpos = headPosFromTree(tree);
  //cerr << hpos << *tree << endl;
  int pos = 0;
  for( ; subTreeIter != st.end() ; subTreeIter++ )
    {
      subTree = *subTreeIter;
      gatherFfCounts(subTree, pos==hpos ? 1 : 0);
      pos++;
    }
  //cerr << "g " << *tree << endl;
  curTree = tree;
  TreeHist treeh(tree, 0);
  treeh.pos = pos;
  treeh.hpos = hpos;
  const Term* lhsTerm = Term::get(tree->term());
  if(lhsTerm->terminal_p())
    {
      if(Feature::whichInt == TTCALC) callProcG(&treeh);
      return;
    }
  if(Feature::whichInt == HCALC || Feature::whichInt == UCALC)
    {
      if(!inHpos) callProcG(&treeh);
      return;
    }
  //if(procGSwitch) cerr << "gff " << *tree << endl;
  if(st.size() == 1 && st.front()->term() == tree->term()) return;
  subTreeIter = st.begin();
  int cVal;
  treeh.pos = -1;
  if(Feature::whichInt == LMCALC) callProcG(&treeh);
  if(Feature::whichInt == LCALC) callProcG(&treeh);
  pos = 0;
  for( ; subTreeIter != st.end() ; subTreeIter++)
    {
      treeh.pos = pos;
      if(pos == hpos && Feature::whichInt == MCALC) callProcG(&treeh);
      if(pos < hpos && Feature::whichInt == LCALC) callProcG(&treeh);
      if(pos > hpos && Feature::whichInt == RCALC) callProcG(&treeh);
      if(pos == hpos && Feature::whichInt == RUCALC) callProcG(&treeh);
      if(pos >= hpos && Feature::whichInt == RMCALC) callProcG(&treeh);
      if(pos <= hpos && Feature::whichInt == LMCALC) callProcG(&treeh);
      pos++;
    }
  //cerr << "gg " << *tree << endl;
  treeh.pos = pos;
  if(Feature::whichInt == RCALC) callProcG(&treeh);
  if(Feature::whichInt == RMCALC) callProcG(&treeh);
}

void
printCounts()
{
   int b,f;
   cerr << "\n";
   for(f = 2 ; f <= Feature::total[whichInt] ; f++)
     cerr << "\t" << curMeanSq[f];
   cerr << "\n";
   for(b = 1; b < 15 ; b++)
     {
       cerr << b ;
       for(f = 2; f <= Feature::total[whichInt] ; f++)
	 {
	   cerr << "\t" << trData[f][b].c;
	 }
       cerr << "\n";
     }
}

void
printLambdas(ostream& res)
{
   int b,f;
   if(Feature::isLM)
     for(f = 2 ; f <= Feature::total[whichInt] ; f++)
       res << "\t" << Feature::logFacs[Feature::whichInt][f];
   res << "\n";
   for(b = 1; b < 15 ; b++)
     {
       res << b ;
       for(f = 2; f <= Feature::total[whichInt] ; f++)
	 {
	   res << "\t";
	   float val = Feature::getLambda(whichInt, f, b);
	   if(val > .998) val = .998;  //nothing too close to 1; 
	   res << val;
	 }
       res << "\n";
     }
}

void
updateLambdas()
{
   int b,f;
   for(b = 1; b < 15 ; b++)
     {
       for(f = 2; f <= Feature::total[whichInt] ; f++)
	 {
	   float denom = trData[f][b].c;
	   float num = trData[f][b].pm;
	   float ans = num/denom;
	   if(denom == 0) ans = ((float)b/15.0);
	   else if(denom < 5 && trData[f][b+1].pm == 0 &&
		   (b == 0 ||  trData[f][b-1].pm == 0))
	     ans = 0;
	   Feature::setLambda(whichInt,f,b,ans);
	 }
     }
}

int
resetLogBases(int n)
{
  int i,j;
  int stillWorking = 0;
  for(i = 2 ; i <= Feature::total[whichInt] ; i++)
    {
      if(done[i]) continue;
      stillWorking = 1;
      Feature::logFacs[Feature::whichInt][i] += .1;

      curMeanSq[i] = 0;
      totForFeat[i] = 0;
      for(j = 1 ; j < 15 ; j++) totForFeat[i] += trData[i][j].c;
      for(j = 1 ; j < 15 ; j++)
	{
	  curMeanSq[i] += pow((trData[i][j].c - (totForFeat[i]/13.0)),2);
	}
      if((prevMeanSq[i] > 0 && curMeanSq[i] >= prevMeanSq[i])
	 || trData[i][14].c == 0)
	{
	  //cerr << "rlb " << i << " "
	  // << Feature::logFacs[Feature::whichInt][i]-.1 << " " << curMeanSq[i]
	  // << " " << trData[i][14].c << " " << prevMeanSq[i] << endl;
	  done[i] = 1;
	  Feature::logFacs[Feature::whichInt][i] -= 0.1;
	}
      prevMeanSq[i] = curMeanSq[i];
    }
  return stillWorking;
}

void
zeroData()
{
   int b,f;
   for(b = 0; b < 15 ; b++)
     {
       for(f = 1; f <= Feature::total[whichInt] ; f++)
	 {
	   trData[f][b].c = 0.0;
	   trData[f][b].pm = 0.0;
	 }
     }
}

void
pickLogBases(InputTree** trainingData, int sc)
{

  int i;
  for( i = 0 ; i < 20 ; i++)
    {
      Feature::logFacs[Feature::whichInt][i] = (whichInt == HCALC) ? 1.1 : 1.5 ;      
    }
  for(i = 0 ; i < Feature::total[whichInt] ; i++) prevMeanSq[i] = 0;
  for(i = 0 ; ; i++)
    {

 
      goThroughSents(trainingData,sc);
      int contp = resetLogBases(i);
      if(!contp) break;
      zeroData();
    }
      // printCounts();

  zeroData();
}  

void
lamInit()
{
   int b,f;
   float factor = 1.0/15.0;
   int numFs = Feature::total[whichInt];
   for(b = 0; b < 15 ; b++)
     {
       for(f = 1; f <= numFs ; f++)
	 {
	   Feature* feat = Feature::fromInt(f, whichInt); 
	   int strtpos = feat->startPos;
	   /* we are trying b/15 */
	   float num = factor* b;
	   Feature::setLambda(whichInt,f,b,num);
	   trData[f][b].c = 0;
	   trData[f][b].pm = 0.0;
	 }
     }
}


void
goThroughSents(InputTree* trainingData[1301], int sc)
{
  int sentenceCount;
  for(sentenceCount = 0 ; sentenceCount < sc ; sentenceCount++)

    {
      InputTree* par = trainingData[sentenceCount];
      //if(sentenceCount%50 == 1)
      //cerr << sentenceCount << endl;
      makeSent(par);
      gatherFfCounts(par,0);


      if(whichInt == TTCALC)
	{

	  list<InputTree*> dummy2;
	  InputTree stopInputTree(par->finish(),par->finish(),
				  whichInt==TTCALC ? "" : "^^",
				  "STOP","",
				  dummy2,NULL,NULL);
	  stopInputTree.headTree() = &stopInputTree;
	  TreeHist treeh(&stopInputTree,0);
	  treeh.hpos = 0;
	  callProcG(&treeh);
	}
    }
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.