浏览代码

Bugfix RANSAC regression.

Frank Prüfer 11 年之前
父节点
当前提交
b6c5eeb7c1
共有 3 个文件被更改,包括 471 次插入0 次删除
  1. 121 0
      regression/linregression/RANSACReg.cpp
  2. 64 0
      regression/linregression/RANSACReg.h
  3. 286 0
      regression/progs/testRANSACRegression.cpp

+ 121 - 0
regression/linregression/RANSACReg.cpp

@@ -0,0 +1,121 @@
+/**
+* @file RANSACReg.cpp
+* @brief Implementation of RANSAC (RANdom SAmple Consensus) for regression purposes
+* @author Frank Prüfer
+* @date 09/10/2013
+
+*/  
+#ifdef NICE_USELIB_OPENMP
+#include <omp.h>
+#endif
+
+#include <iostream>
+
+#include "vislearning/regression/linregression/LinRegression.h"
+#include "vislearning/regression/linregression/RANSACReg.h"
+
+using namespace OBJREC;
+
+using namespace std;
+using namespace NICE;
+
+RANSACReg::RANSACReg ( const Config *_conf )
+{
+  threshold = _conf->gD("RANSACReg","threshold",0.5);
+  iter = _conf->gI("RANSACReg","iterations",10);
+}
+
+RANSACReg::RANSACReg ( const RANSACReg & src ) : RegressionAlgorithm ( src )
+{
+  threshold = src.threshold;
+  n = src.n;
+  iter = src.iter;
+  dataSet = src.dataSet;
+  labelSet = src.labelSet;
+  modelParams = src.modelParams;
+}
+
+RANSACReg::~RANSACReg()
+{
+}
+
+void RANSACReg::teach ( const NICE::VVector & dataSet, const NICE::Vector & labelSet )
+{
+  //for iter iterations do
+    //choose random subset of n points (n = dataSet[0].size()+1)
+    //do LinRegression on subset
+    //get modelParameters
+    //test how many points, which are not in subset, are close to model (use threshold and distancefunc here) -> these points are consneus set
+    //if consensus set contains more points than any previous one, take this model as best_model
+  //maybe compute best_model again with all points of best_consensusSet  
+  //store best_model and maybe best_consensusSet
+  
+  NICE::VVector best_CS(0,0);
+  std::vector<double> best_labelCS;
+  
+  cerr<<"Size of training data: "<<dataSet.size()<<endl;
+  
+  vector<int> indices;
+  for ( uint i = 0; i < dataSet.size(); i++ )
+    indices.push_back(i);
+  
+  n = dataSet[0].size()+1;
+
+  for ( uint i = 0; i < iter; i++ ){
+    random_shuffle( indices.begin(), indices.end() );
+    NICE::VVector randDataSubset;
+    std::vector<double> randLabelSubset;
+    
+    for ( uint j = 0; j < n; j++ ){	//choose random subset of n points
+      randDataSubset.push_back( dataSet[indices[j]] );
+      randLabelSubset.push_back( labelSet[indices[j]] );
+    }
+    
+    LinRegression *linReg = new LinRegression ();
+    linReg->teach ( randDataSubset, (NICE::Vector)randLabelSubset );	//do LinRegression on subset
+    std::vector<double> tmp_modelParams = linReg->getModelParams();
+    
+    NICE::VVector current_CS;
+    std::vector<double> current_labelCS;
+    
+    for ( uint j = n; j < indices.size(); j++ ){	//compute distance between each datapoint and current model
+      double lengthNormalVector = 0; 
+      double sum = 0;
+      for ( uint k = 0; k < tmp_modelParams.size(); k++ ){
+	sum += tmp_modelParams[k] * dataSet[indices[j]][k];
+	lengthNormalVector += tmp_modelParams[k] * tmp_modelParams[k];
+      }
+      lengthNormalVector = sqrt(lengthNormalVector);
+      
+      double distance = ( sum - labelSet[indices[j]] )/ lengthNormalVector;
+//       cerr<<"distance: "<<distance<<endl;
+      
+
+      if ( abs(distance) < threshold ){	//if point is close to model, it belongs to consensus set
+	current_CS.push_back ( dataSet[indices[j]] );
+	current_labelCS.push_back ( labelSet[indices[j]] );
+      }
+    }
+    
+    if ( current_CS.size() > best_CS.size() ){	//if consensus set contains more points than any previous one, take this model as best_model
+      best_CS = current_CS;
+      best_labelCS = current_labelCS;
+    }
+  }
+  
+  cerr<<"Size of best_CS: "<<best_CS.size()<<endl;
+  LinRegression *best_linReg = new LinRegression ();	//compute best_model again with all points of best_consensusSet
+  best_linReg->teach ( best_CS, (NICE::Vector)best_labelCS );
+  modelParams = best_linReg->getModelParams();    
+}
+  
+double RANSACReg::predict ( const NICE::Vector & x )
+{
+  NICE::Vector nModel(modelParams);
+  NICE:: Vector xTmp(1,1.0);
+  xTmp.append(x);
+  double y = xTmp.scalarProduct(nModel);
+
+  return y;
+  
+}

+ 64 - 0
regression/linregression/RANSACReg.h

@@ -0,0 +1,64 @@
+/**
+* @file RANSACReg.h
+* @brief Implementation of RANSAC (RANdom SAmple Consensus) for regression purposes
+* @author Frank Prüfer
+* @date 09/10/2013
+
+*/   
+#ifndef RANSACREGINCLUDE
+#define RANSACREGINCLUDE
+
+#include "core/vector/VectorT.h"
+#include "core/vector/VVector.h"
+#include "core/vector/MatrixT.h"
+
+#include "core/basics/Config.h"
+
+#include "vislearning/regression/regressionbase/RegressionAlgorithm.h"
+
+namespace OBJREC
+{
+class RANSACReg : public RegressionAlgorithm
+{
+  protected:
+    /** threshold value for determining when a datum fits a model */
+    double threshold;
+    
+    /** mminimum number of data required to fit the model */
+    uint n;
+    
+    /** number of iterations performed by the algorithm */
+    uint iter;
+    
+    /** vector of model parameters */
+    std::vector<double> modelParams;
+    
+    /** set of data points */
+    NICE::VVector dataSet;
+    
+    /** set of responses according to dataset */
+    std::vector<double> labelSet;
+    
+
+  public:
+    /** simple constructor */
+    RANSACReg ( const NICE::Config *conf );
+    
+    /** copy constructor */
+    RANSACReg ( const RANSACReg & src );
+    
+    /** simple destructor */
+    virtual ~RANSACReg();
+    
+    /** predict response using simple vector */
+    double predict ( const NICE::Vector & x );
+    
+    /** teach whole set at once */
+    void teach ( const NICE::VVector & dataSet, const NICE::Vector & labelSet );
+
+};
+}	//namespace
+
+
+
+#endif

+ 286 - 0
regression/progs/testRANSACRegression.cpp

@@ -0,0 +1,286 @@
+/**
+* @file testRANSACRegression.cpp
+* @brief test of RANSAC regression
+* @author Frank Prüfer
+* @date 09/11/2013
+
+*/
+
+#include <sstream>
+#include <iostream>
+#include <fstream>
+#include <sstream>
+#include <string>
+#include <vector>
+#include <stdlib.h>
+#include <assert.h>
+
+#include "core/basics/Config.h"
+#include "core/vector/VectorT.h"
+#include "core/vector/VVector.h"
+
+#include "vislearning/baselib/ICETools.h"
+
+#include "vislearning/regression/linregression/RANSACReg.h"
+
+using namespace OBJREC;
+using namespace NICE;
+using namespace std;
+
+void csvline_populate ( vector<string> &record,
+                       const string& line,
+                       char delimiter )
+{
+  int linepos=0;
+  int inquotes=false;
+  char c;
+  int linemax=line.length();
+  string curstring;
+  record.clear();
+
+  while(line[linepos]!=0 && linepos < linemax)
+  {
+    c = line[linepos];
+
+    if (!inquotes && curstring.length()==0 && c=='"')
+    {
+      //beginquotechar
+      inquotes=true;
+    }
+    else if (inquotes && c=='"')
+    {
+      //quotechar
+      if ( (linepos+1 <linemax) && (line[linepos+1]=='"') )
+      {
+        //encountered 2 double quotes in a row (resolves to 1 double quote)
+        curstring.push_back(c);
+        linepos++;
+      }
+      else
+      {
+        //endquotechar
+        inquotes=false;
+      }
+    }
+    else if (!inquotes && c==delimiter)
+    {
+      //end of field
+      record.push_back( curstring );
+      curstring="";
+    }
+    else if (!inquotes && (c=='\r' || c=='\n') )
+    {
+     record.push_back( curstring );
+     return;
+    }
+    else
+    {
+      curstring.push_back(c);
+    }
+    linepos++;
+  }
+  
+  record.push_back( curstring );
+}
+
+void loadData( NICE::VVector &Data,
+               NICE::Vector &y,
+               const string &path,
+               const string &xdat,
+               const string &ydat )
+{
+
+  vector<string> row;
+  string line;
+
+  cerr<<"Preloading Data...";
+  ifstream in( (path+xdat).c_str() );
+  if ( in.fail() )
+  {
+    cout << "File not found" <<endl;
+    exit(EXIT_FAILURE);
+  }
+
+  int numData = 0;
+
+  while ( getline(in, line)  && in.good() )
+  {
+    csvline_populate(row, line, ',');
+    vector<double> vec;
+    for (int i = 0; i < (int)row.size(); i++)
+    {
+      double dval = 0.0;
+      dval = atof(row[i].data() );
+      vec.push_back(dval);
+    }
+    NICE::Vector nvec(vec);
+    Data.push_back(nvec);
+    numData++;
+  }
+  in.close();
+
+  cerr<<"Finished."<<endl<<"Starting to get preloaded Labels...";
+
+  in.open( (path+ydat).c_str() );
+  if ( in.fail() )
+  {
+    cout << "File not found! Setting default value 0.0..." <<endl;
+    y.resize(numData);
+    y.set(0.0);
+  }
+  else
+  {
+    y.resize(numData);
+    int count = 0;
+    while(getline(in, line)  && in.good() )
+    {
+      csvline_populate(row, line, ',');
+      for ( int i = 0; i < (int)row.size(); i++ )
+      {
+        double dval = 0.0;
+        dval = atof(row[i].data() );
+        y.set(count,dval);
+        count++;
+      }
+    }
+    in.close();
+  }
+
+  cerr<<"Finished."<<endl;
+}
+
+void testFrame (  Config conf,
+		  NICE::VVector &xdata,
+		  NICE::Vector &y )
+{
+  cerr<<"\nStarting test framework..."<<endl;
+  
+  /*------------Initialize Variables-----------*/
+  ofstream storeEvalData;
+  double trainRatio = conf.gD( "debug", "training_ratio", .9 );
+  
+  int trainingSize = (int)(trainRatio*xdata.size());
+  int testingSize = xdata.size() - trainingSize;
+  
+  vector<int> indices;
+  for ( int i = 0; i < (int)xdata.size(); i++ )
+    indices.push_back(i);
+  
+  int nfolds = conf.gI( "debug", "nfolds", 10 );
+  Vector mef_v ( nfolds );
+  Vector corr_v ( nfolds );
+  Vector resub_v ( nfolds );
+  Vector diff_v ( nfolds );
+
+  bool saveConfig = conf.gB( "debug", "save_config", false );
+  
+  /*------------Store Configuration------------*/
+  string filename = conf.gS( "debug", "filename" );
+  
+  if ( saveConfig )
+  {
+    cout << "Configuration will be stored in: " << filename << "_config" << endl;
+    
+    storeEvalData.open ( (filename+"_config").c_str() );
+
+    storeEvalData.close();
+  } else
+  {
+    cout << "Configuration will not be stored." << endl;
+  }
+  
+  /*------------Setting up PreRDF--------------*/
+  for ( int k = 0; k < nfolds; k++)
+  {
+    string fold;
+    ostringstream convert;
+    convert << k;
+    fold = convert.str();
+    
+    cout << "\nFOLD " << k << ":\n======" << endl;
+    
+
+    cerr << "Initializing LinRegression...";
+    RANSACReg *RReg = new RANSACReg ( &conf );
+    cerr << "Finished." << endl;
+    
+    cerr << "Teaching the LinRegression algorithm...";
+    NICE::VVector trainData, testData;
+    NICE::Vector trainVals ( trainingSize );
+    NICE::Vector testVals ( testingSize );
+    random_shuffle( indices.begin(), indices.end() );
+    for ( int i = 0; i < trainingSize; i++ )
+    {
+      trainData.push_back ( xdata[ indices[i] ] );
+      trainVals.set( i, y[ indices[i] ] );
+    }
+    for ( int j = 0; j < testingSize; j++ )
+    {
+      testData.push_back ( xdata[ indices[j+trainingSize] ] );
+      testVals.set( j, y[ indices[j+trainingSize] ] );
+    }
+    
+    RReg->teach ( trainData, trainVals );
+    cerr << "Finished." << endl;
+    
+    /*-------------Testing RDF-GP--------------*/
+
+    cerr << "\nGetting prediction values for all data points...";
+    NICE::Vector predictionValues( testingSize );
+    predictionValues.set ( 0.0 );
+    for ( int j = 0; j < testingSize; j++ )
+    {
+      predictionValues[j] = RReg->predict( testData[j] );
+    }
+    cerr << "Finished." << endl;
+    
+    /*---------------Evaluation----------------*/
+    NICE::Vector diff = testVals - predictionValues;
+    
+    double mod_var = diff.StdDev()*diff.StdDev();
+    double tar_var = testVals.StdDev()*testVals.StdDev();
+    mef_v.set( k, (1-mod_var/tar_var) );
+    
+    NICE::Vector meanv( predictionValues.size() );
+    meanv.set( diff.Mean() );
+    NICE::Vector lhs = diff - meanv;
+    meanv.set( testVals.Mean() );
+    NICE::Vector rhs = testVals - meanv;
+    lhs *= rhs;
+    double corr = lhs.Mean() / sqrt( diff.StdDev()*diff.StdDev()*testVals.StdDev()*testVals.StdDev() );
+    corr_v.set( k, corr );
+    
+    diff *= diff;
+    diff_v.set( k, diff.Mean());
+    resub_v.set( k, (diff.Mean() / tar_var) );
+  }
+  
+  /*------------------Output-------------------*/
+  cout << "\nSimple Cross Validation Stats:\n==============================" << endl;
+  cout << "  Modelling Efficiency: " << mef_v.Mean() << endl;
+  cout << "  Correlation: " << corr_v.Mean() << endl;
+  cout << "  Mean Square Error: " << diff_v.Mean() << endl;
+  cout << "  Standardized MSE: " << resub_v.Mean() << endl;
+}
+
+
+int main (int argc, char **argv) {
+
+  Config conf ( argc, argv );   //get config from user input
+  
+  string path = conf.gS( "debug", "path", "." );
+  string dataset = conf.gS( "debug", "dataset", "flux" );
+
+  NICE::VVector xdata;
+  NICE::Vector y;
+
+  loadData(xdata, y, path, (dataset+"_x.csv"), (dataset+"_y.csv") ); //load all data
+  
+  testFrame( conf, xdata, y );
+
+  return 0;
+}
+
+
+ 
+