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

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