54 TMVA::VariablePCATransform::VariablePCATransform( DataSetInfo& dsi )
55 : VariableTransformBase( dsi, Types::
kPCA, "PCA" )
88 if (!IsEnabled() || IsCreated())
return kTRUE;
90 Log() <<
kINFO <<
"Preparing the Principle Component (PCA) transformation..." <<
Endl;
92 UInt_t inputSize = fGet.size();
94 SetNVariables(inputSize);
98 Log() <<
kFATAL <<
"Cannot perform PCA transformation for " << inputSize <<
" variable only" <<
Endl;
102 if (inputSize > 200) {
103 Log() <<
kINFO <<
"----------------------------------------------------------------------------"
106 <<
": More than 200 variables, will not calculate PCA!" <<
Endl;
107 Log() <<
kINFO <<
"----------------------------------------------------------------------------"
112 CalculatePrincipalComponents( events );
124 if (!IsCreated())
return 0;
135 if (cls < 0 || cls >= (
int) fMeanValues.size()) cls = fMeanValues.size()-1;
140 if (fTransformedEvent==0 ) {
141 fTransformedEvent =
new Event();
144 std::vector<Float_t> input;
145 std::vector<Char_t> mask;
146 std::vector<Float_t> principalComponents;
148 Bool_t hasMaskedEntries = GetInput( ev, input, mask );
150 if( hasMaskedEntries ){
153 if( numMasked>0 && numOK>0 ){
154 Log() <<
kFATAL <<
"You mixed variables and targets in the decorrelation transformation. This is not possible." <<
Endl;
156 SetOutput( fTransformedEvent, input, mask, ev );
157 return fTransformedEvent;
160 X2P( principalComponents, input, cls );
161 SetOutput( fTransformedEvent, principalComponents, mask, ev );
163 return fTransformedEvent;
173 if (!IsCreated())
return 0;
175 const UInt_t nCls = GetNClasses();
181 if (cls < 0 ||
UInt_t(cls) > nCls) cls = (fMeanValues.size()==1?0:2);
184 if (fBackTransformedEvent==0 ) fBackTransformedEvent =
new Event();
186 std::vector<Float_t> principalComponents;
187 std::vector<Char_t> mask;
188 std::vector<Float_t>
output;
190 GetInput( ev, principalComponents, mask,
kTRUE );
191 P2X( output, principalComponents, cls );
192 SetOutput( fBackTransformedEvent, output, mask, ev,
kTRUE );
194 return fBackTransformedEvent;
203 UInt_t nvars = 0, ntgts = 0, nspcts = 0;
204 CountVariableTypes( nvars, ntgts, nspcts );
205 if( nvars>0 && ntgts>0 )
206 Log() <<
kFATAL <<
"Variables and targets cannot be mixed in PCA transformation." <<
Endl;
208 const Int_t inputSize = fGet.size();
211 const UInt_t nCls = GetNClasses();
212 const UInt_t maxPCA = (nCls<=1) ? nCls : nCls+1;
215 std::vector<TPrincipal*> pca(maxPCA);
221 Long64_t ievt, entries = events.size();
224 std::vector<Float_t> input;
225 std::vector<Char_t> mask;
226 for (ievt=0; ievt<entries; ievt++) {
227 const Event* ev = events[ievt];
230 Bool_t hasMaskedEntries = GetInput( ev, input, mask );
231 if (hasMaskedEntries){
234 Log() <<
kFATAL <<
"Masked entries found in event read in when calculating the principal components for the PCA transformation." <<
Endl;
238 for( std::vector<Float_t>::iterator itInp = input.begin(), itInpEnd = input.end(); itInp != itInpEnd; ++itInp )
245 pca.at(cls)->AddRow( dvec );
246 if (nCls > 1) pca.at(maxPCA-1)->AddRow( dvec );
250 for (
UInt_t i=0; i<fMeanValues.size(); i++)
if (fMeanValues[i] != 0)
delete fMeanValues[i];
251 for (
UInt_t i=0; i<fEigenVectors.size(); i++)
if (fEigenVectors[i] != 0)
delete fEigenVectors[i];
252 fMeanValues.resize(maxPCA,0);
253 fEigenVectors.resize(maxPCA,0);
255 for (
UInt_t i=0; i<maxPCA; i++ ) {
256 pca.at(i)->MakePrincipals();
259 fMeanValues[i] =
new TVectorD( *(pca.at(i)->GetMeanValues()) );
260 fEigenVectors[i] =
new TMatrixD( *(pca.at(i)->GetEigenVectors()) );
263 for (
UInt_t i=0; i<maxPCA; i++)
delete pca.at(i);
275 const Int_t nInput = x.size();
278 for (
Int_t i = 0; i < nInput; i++) {
280 for (
Int_t j = 0; j < nInput; j++)
281 pv += (((
Double_t)x.at(j)) - (*fMeanValues.at(cls))(j)) * (*fEigenVectors.at(cls))(j,i);
294 const Int_t nInput = pc.size();
297 for (
Int_t i = 0; i < nInput; i++) {
299 for (
Int_t j = 0; j < nInput; j++)
300 xv += (((
Double_t)pc.at(j)) * (*fEigenVectors.at(cls))(i,j) ) + (*fMeanValues.at(cls))(j);
310 for (
Int_t sbType=0; sbType<2; sbType++) {
311 o <<
"# PCA mean values " << std::endl;
312 const TVectorD* means = fMeanValues[sbType];
313 o << (sbType==0 ?
"Signal" :
"Background") <<
" " << means->
GetNrows() << std::endl;
315 o << std::setprecision(12) << std::setw(20) << (*means)[
row];
319 o <<
"##" << std::endl;
322 for (
Int_t sbType=0; sbType<2; sbType++) {
323 o <<
"# PCA eigenvectors " << std::endl;
324 const TMatrixD* mat = fEigenVectors[sbType];
325 o << (sbType==0 ?
"Signal" :
"Background") <<
" " << mat->
GetNrows() <<
" x " << mat->
GetNcols() << std::endl;
328 o << std::setprecision(12) << std::setw(20) << (*mat)[
row][col] <<
" ";
333 o <<
"##" << std::endl;
346 for (
UInt_t sbType=0; sbType<fMeanValues.size(); sbType++) {
348 const TVectorD* means = fMeanValues[sbType];
349 gTools().
AddAttr( meanxml,
"Class", (sbType==0 ?
"Signal" :(sbType==1 ?
"Background":
"Combined")) );
359 for (
UInt_t sbType=0; sbType<fEigenVectors.size(); sbType++) {
361 const TMatrixD* mat = fEigenVectors[sbType];
362 gTools().
AddAttr( evxml,
"Class", (sbType==0 ?
"Signal" :(sbType==1 ?
"Background":
"Combined") ) );
386 void* inpnode =
NULL;
402 if (nodeName ==
"Statistics") {
409 if (fMeanValues.size()<=clsIdx) fMeanValues.resize(clsIdx+1,0);
410 if (fMeanValues[clsIdx]==0) fMeanValues[clsIdx] =
new TVectorD( nrows );
411 fMeanValues[clsIdx]->ResizeTo( nrows );
414 std::stringstream s(
gTools().GetContent(ch));
415 for (
Int_t row = 0; row<nrows; row++) s >> (*fMeanValues[clsIdx])(
row);
417 else if ( nodeName ==
"Eigenvectors" ) {
424 if (fEigenVectors.size()<=clsIdx) fEigenVectors.resize(clsIdx+1,0);
425 if (fEigenVectors[clsIdx]==0) fEigenVectors[clsIdx] =
new TMatrixD( nrows, ncols );
426 fEigenVectors[clsIdx]->ResizeTo( nrows, ncols );
429 std::stringstream s(
gTools().GetContent(ch));
431 for (
Int_t col = 0; col<ncols; col++)
432 s >> (*fEigenVectors[clsIdx])[
row][col];
446 istr.getline(buf,512);
448 Int_t nrows(0), ncols(0);
449 UInt_t classIdx=(classname==
"signal"?0:1);
451 for (
UInt_t i=0; i<fMeanValues.size(); i++) {
452 if (fMeanValues.at(i) != 0)
delete fMeanValues.at(i);
453 if (fEigenVectors.at(i) != 0)
delete fEigenVectors.at(i);
455 fMeanValues.resize(3);
456 fEigenVectors.resize(3);
458 Log() <<
kINFO <<
"VariablePCATransform::ReadTransformationFromStream(): " <<
Endl;
460 while (!(buf[0]==
'#'&& buf[1]==
'#')) {
462 while (*p==
' ' || *p==
'\t') p++;
463 if (*p==
'#' || *p==
'\0') {
464 istr.getline(buf,512);
467 std::stringstream sstr(buf);
469 if (strvar==
"signal" || strvar==
"background") {
472 Int_t sbType = (strvar==
"signal" ? 0 : 1);
474 if (fMeanValues[sbType] == 0) fMeanValues[sbType] =
new TVectorD( nrows );
475 else fMeanValues[sbType]->ResizeTo( nrows );
478 for (
Int_t row = 0; row<nrows; row++) istr >> (*fMeanValues[sbType])(
row);
482 istr.getline(buf,512);
486 istr.getline(buf,512);
487 while (!(buf[0]==
'#'&& buf[1]==
'#')) {
489 while(*p==
' ' || *p==
'\t') p++;
490 if (*p==
'#' || *p==
'\0') {
491 istr.getline(buf,512);
494 std::stringstream sstr(buf);
496 if (strvar==
"signal" || strvar==
"background") {
499 sstr >> nrows >> dummy >> ncols;
500 Int_t sbType = (strvar==
"signal" ? 0 : 1);
502 if (fEigenVectors[sbType] == 0) fEigenVectors[sbType] =
new TMatrixD( nrows, ncols );
503 else fEigenVectors[sbType]->ResizeTo( nrows, ncols );
506 for (
Int_t row = 0;
row<fEigenVectors[sbType]->GetNrows();
row++) {
507 for (
Int_t col = 0; col<fEigenVectors[sbType]->GetNcols(); col++) {
508 istr >> (*fEigenVectors[sbType])[
row][col];
513 istr.getline(buf,512);
515 fMeanValues[2] =
new TVectorD( *fMeanValues[classIdx] );
516 fEigenVectors[2] =
new TMatrixD( *fEigenVectors[classIdx] );
527 UInt_t nvar = fEigenVectors[0]->GetNrows();
530 UInt_t numC = fMeanValues.size();
533 fout <<
" void X2P_"<<trCounter<<
"( const double*, double*, int ) const;" << std::endl;
534 fout <<
" double fMeanValues_"<<trCounter<<
"["<<numC<<
"]["
535 << fMeanValues[0]->GetNrows() <<
"];" << std::endl;
536 fout <<
" double fEigenVectors_"<<trCounter<<
"["<<numC<<
"]["
537 << fEigenVectors[0]->GetNrows() <<
"]["
538 << fEigenVectors[0]->GetNcols() <<
"];" << std::endl;
544 if (fMeanValues[0]->GetNrows() != fMeanValues[1]->GetNrows() ||
545 fEigenVectors[0]->GetNrows() != fEigenVectors[1]->GetNrows() ||
546 fEigenVectors[0]->GetNcols() != fEigenVectors[1]->GetNcols()) {
547 Log() <<
kFATAL <<
"<MakeFunction> Mismatch in vector/matrix dimensions" <<
Endl;
554 fout <<
"//_______________________________________________________________________" << std::endl;
555 fout <<
"inline void " << fcncName <<
"::X2P_"<<trCounter<<
"( const double* x, double* p, int index ) const" << std::endl;
556 fout <<
"{" << std::endl;
557 fout <<
" // Calculate the principal components from the original data vector" << std::endl;
558 fout <<
" // x, and return it in p (function extracted from TPrincipal::X2P)" << std::endl;
559 fout <<
" // It's the users responsibility to make sure that both x and p are" << std::endl;
560 fout <<
" // of the right size (i.e., memory must be allocated for p)." << std::endl;
561 fout <<
" const int nVar = " << nvar <<
";" << std::endl;
563 fout <<
" for (int i = 0; i < nVar; i++) {" << std::endl;
564 fout <<
" p[i] = 0;" << std::endl;
565 fout <<
" for (int j = 0; j < nVar; j++) p[i] += (x[j] - fMeanValues_"<<trCounter<<
"[index][j]) * fEigenVectors_"<<trCounter<<
"[index][j][i];" << std::endl;
566 fout <<
" }" << std::endl;
567 fout <<
"}" << std::endl;
569 fout <<
"//_______________________________________________________________________" << std::endl;
570 fout <<
"inline void " << fcncName <<
"::InitTransform_"<<trCounter<<
"()" << std::endl;
571 fout <<
"{" << std::endl;
572 fout <<
" // PCA transformation, initialisation" << std::endl;
575 fout <<
" // initialise vector of mean values" << std::endl;
576 std::streamsize dp = fout.precision();
577 for (
UInt_t index=0; index<numC; index++) {
578 for (
int i=0; i<fMeanValues[index]->GetNrows(); i++) {
579 fout <<
" fMeanValues_"<<trCounter<<
"["<<index<<
"]["<<i<<
"] = " << std::setprecision(12)
580 << (*fMeanValues[index])(i) <<
";" << std::endl;
586 fout <<
" // initialise matrix of eigenvectors" << std::endl;
587 for (
UInt_t index=0; index<numC; index++) {
588 for (
int i=0; i<fEigenVectors[index]->GetNrows(); i++) {
589 for (
int j=0; j<fEigenVectors[index]->GetNcols(); j++) {
590 fout <<
" fEigenVectors_"<<trCounter<<
"["<<index<<
"]["<<i<<
"]["<<j<<
"] = " << std::setprecision(12)
591 << (*fEigenVectors[index])(i,j) <<
";" << std::endl;
595 fout << std::setprecision(dp);
596 fout <<
"}" << std::endl;
598 fout <<
"//_______________________________________________________________________" << std::endl;
599 fout <<
"inline void " << fcncName <<
"::Transform_"<<trCounter<<
"( std::vector<double>& iv, int cls ) const" << std::endl;
600 fout <<
"{" << std::endl;
601 fout <<
" // PCA transformation" << std::endl;
602 fout <<
" const int nVar = " << nvar <<
";" << std::endl;
603 fout <<
" double *dv = new double[nVar];" << std::endl;
604 fout <<
" double *rv = new double[nVar];" << std::endl;
605 fout <<
" if (cls < 0 || cls > "<<GetNClasses()<<
") {"<< std::endl;
606 fout <<
" if ("<<GetNClasses()<<
" > 1 ) cls = "<<GetNClasses()<<
";"<< std::endl;
607 fout <<
" else cls = "<<(numC==1?0:2)<<
";"<< std::endl;
608 fout <<
" }"<< std::endl;
612 fout <<
" for (int ivar=0; ivar<nVar; ivar++) dv[ivar] = iv[indicesGet.at(ivar)];" << std::endl;
615 fout <<
" // Perform PCA and put it into PCAed events tree" << std::endl;
616 fout <<
" this->X2P_"<<trCounter<<
"( dv, rv, cls );" << std::endl;
617 fout <<
" for (int ivar=0; ivar<nVar; ivar++) iv[indicesPut.at(ivar)] = rv[ivar];" << std::endl;
620 fout <<
" delete [] dv;" << std::endl;
621 fout <<
" delete [] rv;" << std::endl;
622 fout <<
"}" << std::endl;
Principal Components Analysis (PCA)
MsgLogger & Endl(MsgLogger &ml)
void Print(std::ostream &o) const
print method
TVectorT< Double_t > TVectorD
TMatrixT< Double_t > TMatrixD
void Initialize(Bool_t useTMVAStyle=kTRUE)
static RooMathCoreReg dummy
static void output(int code)