source: trunk/MagicSoft/Mars/mranforest/MRanForest.cc@ 7424

Last change on this file since 7424 was 7424, checked in by tbretz, 19 years ago
*** empty log message ***
File size: 17.4 KB
Line 
1/* ======================================================================== *\
2!
3! *
4! * This file is part of MARS, the MAGIC Analysis and Reconstruction
5! * Software. It is distributed to you in the hope that it can be a useful
6! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
7! * It is distributed WITHOUT ANY WARRANTY.
8! *
9! * Permission to use, copy, modify and distribute this software and its
10! * documentation for any purpose is hereby granted without fee,
11! * provided that the above copyright notice appear in all copies and
12! * that both that copyright notice and this permission notice appear
13! * in supporting documentation. It is provided "as is" without express
14! * or implied warranty.
15! *
16!
17!
18! Author(s): Thomas Hengstebeck 3/2003 <mailto:hengsteb@physik.hu-berlin.de>
19!
20! Copyright: MAGIC Software Development, 2000-2005
21!
22!
23\* ======================================================================== */
24
25/////////////////////////////////////////////////////////////////////////////
26//
27// MRanForest
28//
29// ParameterContainer for Forest structure
30//
31// A random forest can be grown by calling GrowForest.
32// In advance SetupGrow must be called in order to initialize arrays and
33// do some preprocessing.
34// GrowForest() provides the training data for a single tree (bootstrap
35// aggregate procedure)
36//
37// Essentially two random elements serve to provide a "random" forest,
38// namely bootstrap aggregating (which is done in GrowForest()) and random
39// split selection (which is subject to MRanTree::GrowTree())
40//
41/////////////////////////////////////////////////////////////////////////////
42#include "MRanForest.h"
43
44#include <TVector.h>
45#include <TRandom.h>
46
47#include "MHMatrix.h"
48#include "MRanTree.h"
49#include "MData.h"
50#include "MDataArray.h"
51#include "MParList.h"
52
53#include "MLog.h"
54#include "MLogManip.h"
55
56ClassImp(MRanForest);
57
58using namespace std;
59
60// --------------------------------------------------------------------------
61//
62// Default constructor.
63//
64MRanForest::MRanForest(const char *name, const char *title)
65 : fClassify(kTRUE), fNumTrees(100), fNumTry(0), fNdSize(1),
66 fRanTree(NULL), fRules(NULL), fMatrix(NULL), fUserVal(-1)
67{
68 fName = name ? name : "MRanForest";
69 fTitle = title ? title : "Storage container for Random Forest";
70
71 fForest=new TObjArray();
72 fForest->SetOwner(kTRUE);
73}
74
75MRanForest::MRanForest(const MRanForest &rf)
76{
77 // Copy constructor
78 fName = rf.fName;
79 fTitle = rf.fTitle;
80
81 fClassify = rf.fClassify;
82 fNumTrees = rf.fNumTrees;
83 fNumTry = rf.fNumTry;
84 fNdSize = rf.fNdSize;
85 fTreeNo = rf.fTreeNo;
86 fRanTree = NULL;
87
88 fRules=new MDataArray();
89 fRules->Reset();
90
91 MDataArray *newrules=rf.fRules;
92
93 for(Int_t i=0;i<newrules->GetNumEntries();i++)
94 {
95 MData &data=(*newrules)[i];
96 fRules->AddEntry(data.GetRule());
97 }
98
99 // trees
100 fForest=new TObjArray();
101 fForest->SetOwner(kTRUE);
102
103 TObjArray *newforest=rf.fForest;
104 for(Int_t i=0;i<newforest->GetEntries();i++)
105 {
106 MRanTree *rantree=(MRanTree*)newforest->At(i);
107
108 MRanTree *newtree=new MRanTree(*rantree);
109 fForest->Add(newtree);
110 }
111
112 fHadTrue = rf.fHadTrue;
113 fHadEst = rf.fHadEst;
114 fDataSort = rf.fDataSort;
115 fDataRang = rf.fDataRang;
116 fClassPop = rf.fClassPop;
117 fWeight = rf.fWeight;
118 fTreeHad = rf.fTreeHad;
119
120 fNTimesOutBag = rf.fNTimesOutBag;
121
122}
123
124// --------------------------------------------------------------------------
125// Destructor.
126MRanForest::~MRanForest()
127{
128 delete fForest;
129 if (fMatrix)
130 delete fMatrix;
131 if (fRules)
132 delete fRules;
133}
134
135void MRanForest::Print(Option_t *o) const
136{
137 *fLog << inf << GetDescriptor() << ": " << endl;
138 MRanTree *t = GetTree(0);
139 if (t)
140 {
141 *fLog << "Setting up RF for training on target:" << endl;
142 *fLog << " " << t->GetTitle() << endl;
143 }
144 if (fRules)
145 {
146 *fLog << "Following rules are used as input to RF:" << endl;
147 for (Int_t i=0;i<fRules->GetNumEntries();i++)
148 *fLog << " " << i << ") " << (*fRules)[i].GetRule() << endl;
149 }
150 *fLog << "Random forest parameters:" << endl;
151 if (t)
152 {
153 *fLog << " - " << (t->IsClassify()?"classification":"regression") << " tree" << endl;
154 *fLog << " - Number of trys: " << t->GetNumTry() << endl;
155 *fLog << " - Node size: " << t->GetNdSize() << endl;
156 }
157 *fLog << " - Number of trees: " << fNumTrees << endl;
158 *fLog << " - User value: " << fUserVal << endl;
159 *fLog << endl;
160}
161
162void MRanForest::SetNumTrees(Int_t n)
163{
164 //at least 1 tree
165 fNumTrees=TMath::Max(n,1);
166 fTreeHad.Set(fNumTrees);
167 fTreeHad.Reset();
168}
169
170void MRanForest::SetNumTry(Int_t n)
171{
172 fNumTry=TMath::Max(n,0);
173}
174
175void MRanForest::SetNdSize(Int_t n)
176{
177 fNdSize=TMath::Max(n,1);
178}
179
180void MRanForest::SetWeights(const TArrayF &weights)
181{
182 fWeight=weights;
183}
184
185void MRanForest::SetGrid(const TArrayD &grid)
186{
187 const int n=grid.GetSize();
188
189 for(int i=0;i<n-1;i++)
190 if(grid[i]>=grid[i+1])
191 {
192 *fLog<<warn<<"Grid points must be in increasing order! Ignoring grid."<<endl;
193 return;
194 }
195
196 fGrid=grid;
197
198 //*fLog<<inf<<"Following "<<n<<" grid points are used:"<<endl;
199 //for(int i=0;i<n;i++)
200 // *fLog<<inf<<" "<<i<<") "<<fGrid[i]<<endl;
201}
202
203Int_t MRanForest::GetNumDim() const
204{
205 return fMatrix ? fMatrix->GetNcols() : 0;
206}
207
208Int_t MRanForest::GetNumData() const
209{
210 return fMatrix ? fMatrix->GetNrows() : 0;
211}
212
213Int_t MRanForest::GetNclass() const
214{
215 int maxidx = TMath::LocMax(fClass.GetSize(),fClass.GetArray());
216
217 return int(fClass[maxidx])+1;
218}
219
220void MRanForest::PrepareClasses()
221{
222 const int numdata=fHadTrue.GetSize();
223
224 if(fGrid.GetSize()>0)
225 {
226 // classes given by grid
227 const int ngrid=fGrid.GetSize();
228
229 for(int j=0;j<numdata;j++)
230 {
231 // Array is supposed to be sorted prior to this call.
232 // If match is found, function returns position of element.
233 // If no match found, function gives nearest element smaller
234 // than value.
235 int k=TMath::BinarySearch(ngrid, fGrid.GetArray(), fHadTrue[j]);
236
237 fClass[j] = k;
238 }
239
240 int minidx = TMath::LocMin(fClass.GetSize(),fClass.GetArray());
241 int min = fClass[minidx];
242 if(min!=0) for(int j=0;j<numdata;j++)fClass[j]-=min;
243
244 }else{
245 // classes directly given
246 for (Int_t j=0;j<numdata;j++)
247 fClass[j] = int(fHadTrue[j]+0.5);
248 }
249}
250
251Double_t MRanForest::CalcHadroness()
252{
253 TVector event;
254 *fRules >> event;
255
256 return CalcHadroness(event);
257}
258
259Double_t MRanForest::CalcHadroness(const TVector &event)
260{
261 Double_t hadroness=0;
262 Int_t ntree=0;
263
264 TIter Next(fForest);
265
266 MRanTree *tree;
267 while ((tree=(MRanTree*)Next()))
268 hadroness += (fTreeHad[ntree++]=tree->TreeHad(event));
269
270 return hadroness/ntree;
271}
272
273Bool_t MRanForest::AddTree(MRanTree *rantree=NULL)
274{
275 fRanTree = rantree ? rantree : fRanTree;
276
277 if (!fRanTree) return kFALSE;
278
279 MRanTree *newtree=new MRanTree(*fRanTree);
280 fForest->Add(newtree);
281
282 return kTRUE;
283}
284
285Bool_t MRanForest::SetupGrow(MHMatrix *mat,MParList *plist)
286{
287 //-------------------------------------------------------------------
288 // access matrix, copy last column (target) preliminarily
289 // into fHadTrue
290 if (fMatrix)
291 delete fMatrix;
292 fMatrix = new TMatrix(mat->GetM());
293
294 int dim = fMatrix->GetNcols()-1;
295 int numdata = fMatrix->GetNrows();
296
297 fHadTrue.Set(numdata);
298 fHadTrue.Reset(0);
299
300 for (Int_t j=0;j<numdata;j++)
301 fHadTrue[j] = (*fMatrix)(j,dim);
302
303 // remove last col
304 fMatrix->ResizeTo(numdata,dim);
305
306 //-------------------------------------------------------------------
307 // setup labels for classification/regression
308 fClass.Set(numdata);
309 fClass.Reset(0);
310
311 if (fClassify)
312 PrepareClasses();
313
314 //-------------------------------------------------------------------
315 // allocating and initializing arrays
316 fHadEst.Set(numdata);
317 fHadEst.Reset(0);
318
319 fNTimesOutBag.Set(numdata);
320 fNTimesOutBag.Reset(0);
321
322 fDataSort.Set(dim*numdata);
323 fDataSort.Reset(0);
324
325 fDataRang.Set(dim*numdata);
326 fDataRang.Reset(0);
327
328 if(fWeight.GetSize()!=numdata)
329 {
330 fWeight.Set(numdata);
331 fWeight.Reset(1.);
332 *fLog << inf <<"Setting weights to 1 (no weighting)"<< endl;
333 }
334
335 //-------------------------------------------------------------------
336 // setup rules to be used for classification/regression
337 const MDataArray *allrules=(MDataArray*)mat->GetColumns();
338 if(allrules==NULL)
339 {
340 *fLog << err <<"Rules of matrix == null, exiting"<< endl;
341 return kFALSE;
342 }
343
344 if (fRules)
345 delete fRules;
346 fRules = new MDataArray();
347 fRules->Reset();
348
349 const TString target_rule = (*allrules)[dim].GetRule();
350 for (Int_t i=0;i<dim;i++)
351 fRules->AddEntry((*allrules)[i].GetRule());
352
353 *fLog << inf << endl;
354 *fLog << "Setting up RF for training on target:" << endl;
355 *fLog << " " << target_rule.Data() << endl;
356 *fLog << "Following rules are used as input to RF:" << endl;
357 for (Int_t i=0;i<dim;i++)
358 *fLog << " " << i << ") " << (*fRules)[i].GetRule() << endl;
359 *fLog << endl;
360
361 //-------------------------------------------------------------------
362 // prepare (sort) data for fast optimization algorithm
363 if (!CreateDataSort())
364 return kFALSE;
365
366 //-------------------------------------------------------------------
367 // access and init tree container
368 fRanTree = (MRanTree*)plist->FindCreateObj("MRanTree");
369 if(!fRanTree)
370 {
371 *fLog << err << dbginf << "MRanForest, fRanTree not initialized... aborting." << endl;
372 return kFALSE;
373 }
374 fRanTree->SetName(target_rule);
375
376 const Int_t tryest = TMath::Nint(TMath::Sqrt(dim));
377
378 *fLog << inf << endl;
379 *fLog << "Following input for the tree growing are used:"<<endl;
380 *fLog << " Number of Trees : "<<fNumTrees<<endl;
381 *fLog << " Number of Trials: "<<(fNumTry==0?tryest:fNumTry)<<(fNumTry==0?" (auto)":"")<<endl;
382 *fLog << " Final Node size : "<<fNdSize<<endl;
383 *fLog << " Using Grid : "<<(fGrid.GetSize()>0?"Yes":"No")<<endl;
384 *fLog << " Number of Events: "<<numdata<<endl;
385 *fLog << " Number of Params: "<<dim<<endl;
386
387 if(fNumTry==0)
388 {
389 fNumTry=tryest;
390 *fLog << inf << endl;
391 *fLog << "Set no. of trials to the recommended value of round(";
392 *fLog << TMath::Sqrt(dim) << ") = " << fNumTry << endl;
393 }
394
395 fRanTree->SetNumTry(fNumTry);
396 fRanTree->SetClassify(fClassify);
397 fRanTree->SetNdSize(fNdSize);
398
399 fTreeNo=0;
400
401 return kTRUE;
402}
403
404Bool_t MRanForest::GrowForest()
405{
406 if(!gRandom)
407 {
408 *fLog << err << dbginf << "gRandom not initialized... aborting." << endl;
409 return kFALSE;
410 }
411
412 fTreeNo++;
413
414 //-------------------------------------------------------------------
415 // initialize running output
416
417 float minfloat=fHadTrue[TMath::LocMin(fHadTrue.GetSize(),fHadTrue.GetArray())];
418 Bool_t calcResolution=(minfloat>0.001);
419
420 if (fTreeNo==1)
421 {
422 *fLog << inf << endl << underline;
423
424 if(calcResolution)
425 *fLog << "no. of tree no. of nodes resolution in % (from oob-data -> overest. of error)" << endl;
426 else
427 *fLog << "no. of tree no. of nodes rms in % (from oob-data -> overest. of error)" << endl;
428 // 12345678901234567890123456789012345678901234567890
429 }
430
431 const Int_t numdata = GetNumData();
432 const Int_t nclass = GetNclass();
433
434 //-------------------------------------------------------------------
435 // bootstrap aggregating (bagging) -> sampling with replacement:
436
437 TArrayF classpopw(nclass);
438 TArrayI jinbag(numdata); // Initialization includes filling with 0
439 TArrayF winbag(numdata); // Initialization includes filling with 0
440
441 float square=0;
442 float mean=0;
443
444 for (Int_t n=0; n<numdata; n++)
445 {
446 // The integer k is randomly (uniformly) chosen from the set
447 // {0,1,...,numdata-1}, which is the set of the index numbers of
448 // all events in the training sample
449
450 const Int_t k = Int_t(gRandom->Rndm()*numdata);
451
452 if(fClassify)
453 classpopw[fClass[k]]+=fWeight[k];
454 else
455 classpopw[0]+=fWeight[k];
456
457 mean +=fHadTrue[k]*fWeight[k];
458 square+=fHadTrue[k]*fHadTrue[k]*fWeight[k];
459
460 winbag[k]+=fWeight[k];
461 jinbag[k]=1;
462
463 }
464
465 //-------------------------------------------------------------------
466 // modifying sorted-data array for in-bag data:
467
468 // In bagging procedure ca. 2/3 of all elements in the original
469 // training sample are used to build the in-bag data
470 TArrayI datsortinbag=fDataSort;
471 Int_t ninbag=0;
472
473 ModifyDataSort(datsortinbag, ninbag, jinbag);
474
475 fRanTree->GrowTree(fMatrix,fHadTrue,fClass,datsortinbag,fDataRang,classpopw,mean,square,
476 jinbag,winbag,nclass);
477
478 //-------------------------------------------------------------------
479 // error-estimates from out-of-bag data (oob data):
480 //
481 // For a single tree the events not(!) contained in the bootstrap sample of
482 // this tree can be used to obtain estimates for the classification error of
483 // this tree.
484 // If you take a certain event, it is contained in the oob-data of 1/3 of
485 // the trees (see comment to ModifyData). This means that the classification error
486 // determined from oob-data is underestimated, but can still be taken as upper limit.
487
488 for (Int_t ievt=0;ievt<numdata;ievt++)
489 {
490 if (jinbag[ievt]>0)
491 continue;
492
493 fHadEst[ievt] +=fRanTree->TreeHad((*fMatrix), ievt);
494 fNTimesOutBag[ievt]++;
495
496 }
497
498 Int_t n=0;
499 Float_t ferr=0;
500
501 for (Int_t ievt=0;ievt<numdata;ievt++)
502 {
503 if(fNTimesOutBag[ievt]!=0)
504 {
505 float val = fHadEst[ievt]/float(fNTimesOutBag[ievt])-fHadTrue[ievt];
506 if(calcResolution) val/=fHadTrue[ievt];
507
508 ferr += val*val;
509 n++;
510 }
511 }
512 ferr = TMath::Sqrt(ferr/n);
513
514 //-------------------------------------------------------------------
515 // give running output
516 *fLog << setw(5) << fTreeNo;
517 *fLog << setw(18) << fRanTree->GetNumEndNodes();
518 *fLog << Form("%18.2f", ferr*100.);
519 *fLog << endl;
520
521 fRanTree->SetError(ferr);
522
523 // adding tree to forest
524 AddTree();
525
526 return fTreeNo<fNumTrees;
527}
528
529Bool_t MRanForest::CreateDataSort()
530{
531 // fDataSort(m,n) is the event number in which fMatrix(m,n) occurs.
532 // fDataRang(m,n) is the rang of fMatrix(m,n), i.e. if rang = r:
533 // fMatrix(m,n) is the r-th highest value of all fMatrix(m,.).
534 //
535 // There may be more then 1 event with rang r (due to bagging).
536
537 const Int_t numdata = GetNumData();
538 const Int_t dim = GetNumDim();
539
540 TArrayF v(numdata);
541 TArrayI isort(numdata);
542
543
544 for (Int_t mvar=0;mvar<dim;mvar++)
545 {
546
547 for(Int_t n=0;n<numdata;n++)
548 {
549 v[n]=(*fMatrix)(n,mvar);
550 isort[n]=n;
551
552 if(TMath::IsNaN(v[n]))
553 {
554 *fLog << err <<"Event no. "<<n<<", matrix column no. "<<mvar;
555 *fLog << err <<" has the value NaN."<<endl;
556 return kFALSE;
557 }
558 }
559
560 TMath::Sort(numdata,v.GetArray(),isort.GetArray(),kFALSE);
561
562 // this sorts the v[n] in ascending order. isort[n] is the event number
563 // of that v[n], which is the n-th from the lowest (assume the original
564 // event numbers are 0,1,...).
565
566 // control sorting
567 for(int n=1;n<numdata;n++)
568 if(v[isort[n-1]]>v[isort[n]])
569 {
570 *fLog << err <<"Event no. "<<n<<", matrix column no. "<<mvar;
571 *fLog << err <<" not at correct sorting position."<<endl;
572 return kFALSE;
573 }
574
575 for(Int_t n=0;n<numdata-1;n++)
576 {
577 const Int_t n1=isort[n];
578 const Int_t n2=isort[n+1];
579
580 fDataSort[mvar*numdata+n]=n1;
581 if(n==0) fDataRang[mvar*numdata+n1]=0;
582 if(v[n1]<v[n2])
583 {
584 fDataRang[mvar*numdata+n2]=fDataRang[mvar*numdata+n1]+1;
585 }else{
586 fDataRang[mvar*numdata+n2]=fDataRang[mvar*numdata+n1];
587 }
588 }
589 fDataSort[(mvar+1)*numdata-1]=isort[numdata-1];
590 }
591 return kTRUE;
592}
593
594void MRanForest::ModifyDataSort(TArrayI &datsortinbag, Int_t ninbag, const TArrayI &jinbag)
595{
596 const Int_t numdim=GetNumDim();
597 const Int_t numdata=GetNumData();
598
599 ninbag=0;
600 for (Int_t n=0;n<numdata;n++)
601 if(jinbag[n]==1) ninbag++;
602
603 for(Int_t m=0;m<numdim;m++)
604 {
605 Int_t k=0;
606 Int_t nt=0;
607 for(Int_t n=0;n<numdata;n++)
608 {
609 if(jinbag[datsortinbag[m*numdata+k]]==1)
610 {
611 datsortinbag[m*numdata+nt]=datsortinbag[m*numdata+k];
612 k++;
613 }else{
614 for(Int_t j=1;j<numdata-k;j++)
615 {
616 if(jinbag[datsortinbag[m*numdata+k+j]]==1)
617 {
618 datsortinbag[m*numdata+nt]=datsortinbag[m*numdata+k+j];
619 k+=j+1;
620 break;
621 }
622 }
623 }
624 nt++;
625 if(nt>=ninbag) break;
626 }
627 }
628}
629
630Bool_t MRanForest::AsciiWrite(ostream &out) const
631{
632 Int_t n=0;
633 MRanTree *tree;
634 TIter forest(fForest);
635
636 while ((tree=(MRanTree*)forest.Next()))
637 {
638 tree->AsciiWrite(out);
639 n++;
640 }
641
642 return n==fNumTrees;
643}
Note: See TracBrowser for help on using the repository browser.