PLearn 0.1
Public Types | Public Member Functions | Static Public Member Functions | Public Attributes | Static Public Attributes | Static Protected Member Functions | Private Member Functions
PLearn::Grapher Class Reference

#include <Grapher.h>

Inheritance diagram for PLearn::Grapher:
Inheritance graph
[legend]
Collaboration diagram for PLearn::Grapher:
Collaboration graph
[legend]

List of all members.

Public Types

typedef Object inherited

Public Member Functions

 Grapher ()
virtual void run ()
 Overload this for runnable objects (default method issues a runtime error)
virtual void build ()
 Post-constructor.
virtual void makeDeepCopyFromShallowCopy (CopiesMap &copies)
 Transforms a shallow copy into a deep copy.
virtual string classname () const
virtual OptionListgetOptionList () const
virtual OptionMapgetOptionMap () const
virtual RemoteMethodMapgetRemoteMethodMap () const
virtual GrapherdeepCopy (CopiesMap &copies) const

Static Public Member Functions

static string _classname_ ()
 Declares name and deepCopy methods.
static OptionList_getOptionList_ ()
static RemoteMethodMap_getRemoteMethodMap_ ()
static Object_new_instance_for_typemap_ ()
static bool _isa_ (const Object *o)
static void _static_initialize_ ()
static const PPathdeclaringFile ()
static void plot_2D_classification (string epsfname, VMat trainset, TVec< int > griddim, TVec< pair< real, real > > gridrange, VMat gridoutputs, real radius, bool bw=false)
static void plot_1D_regression (string basename, VMat trainset, TVec< int > griddim, TVec< pair< real, real > > gridrange, VMat gridoutputs, VMat trainoutputs, bool bw=false)

Public Attributes

string basename
string task
real class1_threshold
PP< PLearnerlearner
VMat trainset
TVec< intgriddim
TVec< pair< real, real > > gridrange
real radius
bool bw
string save_learner_as

Static Public Attributes

static StaticInitializer _static_initializer_

Static Protected Member Functions

static void declareOptions (OptionList &ol)
 Declares this class' options.

Private Member Functions

void build_ ()
 This does the actual building.
void computeAutoGridrange ()

Detailed Description

Definition at line 50 of file Grapher.h.


Member Typedef Documentation

Reimplemented from PLearn::Object.

Definition at line 62 of file Grapher.h.


Constructor & Destructor Documentation

PLearn::Grapher::Grapher ( )

Definition at line 498 of file Grapher.cc.

    :basename("dxplot"), task(""), class1_threshold(0.5),
     radius(-0.01), bw(false)
{
}

Member Function Documentation

string PLearn::Grapher::_classname_ ( ) [static]

Declares name and deepCopy methods.

Reimplemented from PLearn::Object.

Definition at line 504 of file Grapher.cc.

OptionList & PLearn::Grapher::_getOptionList_ ( ) [static]

Reimplemented from PLearn::Object.

Definition at line 504 of file Grapher.cc.

RemoteMethodMap & PLearn::Grapher::_getRemoteMethodMap_ ( ) [static]

Reimplemented from PLearn::Object.

Definition at line 504 of file Grapher.cc.

bool PLearn::Grapher::_isa_ ( const Object o) [static]

Reimplemented from PLearn::Object.

Definition at line 504 of file Grapher.cc.

Object * PLearn::Grapher::_new_instance_for_typemap_ ( ) [static]

Reimplemented from PLearn::Object.

Definition at line 504 of file Grapher.cc.

StaticInitializer Grapher::_static_initializer_ & PLearn::Grapher::_static_initialize_ ( ) [static]

Reimplemented from PLearn::Object.

Definition at line 504 of file Grapher.cc.

void PLearn::Grapher::build ( ) [virtual]

Post-constructor.

The normal implementation should call simply inherited::build(), then this class's build_(). This method should be callable again at later times, after modifying some option fields to change the "architecture" of the object.

Reimplemented from PLearn::Object.

Definition at line 826 of file Grapher.cc.

References PLearn::Object::build(), and build_().

Here is the call graph for this function:

void PLearn::Grapher::build_ ( ) [private]

This does the actual building.

Reimplemented from PLearn::Object.

Definition at line 551 of file Grapher.cc.

Referenced by build().

{
    // ### This method should do the real building of the object,
    // ### according to set 'options', in *any* situation. 
    // ### Typical situations include:
    // ###  - Initial building of an object from a few user-specified options
    // ###  - Building of a "reloaded" object: i.e. from the complete set of all serialised options.
    // ###  - Updating or "re-building" of an object after a few "tuning" options have been modified.
    // ### You should assume that the parent class' build_() has already been called.
}

Here is the caller graph for this function:

string PLearn::Grapher::classname ( ) const [virtual]

Reimplemented from PLearn::Object.

Definition at line 504 of file Grapher.cc.

void PLearn::Grapher::computeAutoGridrange ( ) [private]

Definition at line 464 of file Grapher.cc.

References d, PLearn::TVec< T >::first(), i, and j.

Referenced by run().

{
    int d = trainset->inputsize();
    gridrange.resize(d);
    for(int j=0; j<d; j++)
        gridrange[j] = pair<real,real>(FLT_MAX,-FLT_MAX);
    Vec input;
    Vec target;
    real weight;
    int l = trainset.length();
    for(int i=0; i<l; i++)
    {
        trainset->getExample(i, input, target, weight);
        for(int j=0; j<d; j++)
        {
            real x_j = input[j];
            if(x_j<gridrange[j].first)
                gridrange[j].first = x_j;
            if(x_j>gridrange[j].second)
                gridrange[j].second = x_j;
        }      
    }

    // Now add extra 10%
    real extra = .10;
    for(int j=0; j<d; j++)
    {
        real extent = extra*(gridrange[j].second-gridrange[j].first);
        gridrange[j].first -= extent;
        gridrange[j].second += extent;
    }
}

Here is the call graph for this function:

Here is the caller graph for this function:

void PLearn::Grapher::declareOptions ( OptionList ol) [static, protected]

Declares this class' options.

Reimplemented from PLearn::Object.

Definition at line 506 of file Grapher.cc.

References basename, PLearn::OptionBase::buildoption, bw, class1_threshold, PLearn::declareOption(), PLearn::Object::declareOptions(), griddim, gridrange, learner, radius, save_learner_as, task, and trainset.

{
    // ### Declare all of this object's options here
    // ### For the "flags" of each option, you should typically specify  
    // ### one of OptionBase::buildoption, OptionBase::learntoption or 
    // ### OptionBase::tuningoption. Another possible flag to be combined with
    // ### is OptionBase::nosave

    declareOption(ol, "basename", &Grapher::basename, OptionBase::buildoption,
                  "Base name of the .dx data file to generate. Running this class will generate\n"
                  "files basename_dset.dx containing targets and outputs for the given dataset positions\n"
                  "and basename_outputs.dx containing outputs computed at grid positions\n");
    declareOption(ol, "task", &Grapher::task, OptionBase::buildoption,
                  "Desired plotting task. Can be \"1D regression\",\n"
                  "\"2D clustering\", \"2D density\", \"2D classification\",\n"
                  "\"2D regression\"");
    declareOption(ol, "class1_threshold", &Grapher::class1_threshold, OptionBase::buildoption,
                  "In the case of 1 output 2D classification, the output threshold to\n"
                  "have class=1 (below the threshold, the class = 0).  The default\n"
                  "is 0.5, which appropriate for sigmoidal-output learners, but use 0\n"
                  "if the learner outputs -1/1, such as for SVM's");
    declareOption(ol, "learner", &Grapher::learner, OptionBase::buildoption,
                  "The learner to train/test");
    declareOption(ol, "trainset", &Grapher::trainset, OptionBase::buildoption,
                  "The training set to train the learner on\n");
    declareOption(ol, "gridrange", &Grapher::gridrange, OptionBase::buildoption,
                  "A vector of low:high pairs with as many dimensions as the input space\n"
                  "ex for 2D: [ -10:10 -3:4 ] \n"
                  "If empty, it will be automatically inferred from the range of the\n"
                  "trainset inputs (with an extra 10%)");
    declareOption(ol, "griddim", &Grapher::griddim, OptionBase::buildoption,
                  "A vector of integers giving the number of sample coordinates\n"
                  "for each dimension of the grid. Ex for 2D: [ 100 100 ]\n");
    declareOption(ol, "radius", &Grapher::radius, OptionBase::buildoption,
                  "The radius of the discs around data points.\n"
                  "(If negative, it's considered to be expressed as a percentage of the x range)\n");
    declareOption(ol, "bw", &Grapher::bw, OptionBase::buildoption,
                  "Set this to true if you want to generate black and white eps");
    declareOption(ol, "save_learner_as", &Grapher::save_learner_as, OptionBase::buildoption,
                  "(Optionally) save trained learner in this file (.psave)");

    // Now call the parent class' declareOptions
    inherited::declareOptions(ol);
}

Here is the call graph for this function:

static const PPath& PLearn::Grapher::declaringFile ( ) [inline, static]

Reimplemented from PLearn::Object.

Definition at line 115 of file Grapher.h.

Grapher * PLearn::Grapher::deepCopy ( CopiesMap copies) const [virtual]

Reimplemented from PLearn::Object.

Definition at line 504 of file Grapher.cc.

OptionList & PLearn::Grapher::getOptionList ( ) const [virtual]

Reimplemented from PLearn::Object.

Definition at line 504 of file Grapher.cc.

OptionMap & PLearn::Grapher::getOptionMap ( ) const [virtual]

Reimplemented from PLearn::Object.

Definition at line 504 of file Grapher.cc.

RemoteMethodMap & PLearn::Grapher::getRemoteMethodMap ( ) const [virtual]

Reimplemented from PLearn::Object.

Definition at line 504 of file Grapher.cc.

void PLearn::Grapher::makeDeepCopyFromShallowCopy ( CopiesMap copies) [virtual]

Transforms a shallow copy into a deep copy.

Reimplemented from PLearn::Object.

Definition at line 833 of file Grapher.cc.

References PLearn::Object::makeDeepCopyFromShallowCopy().

Here is the call graph for this function:

void PLearn::Grapher::plot_1D_regression ( string  basename,
VMat  trainset,
TVec< int griddim,
TVec< pair< real, real > >  gridrange,
VMat  gridoutputs,
VMat  trainoutputs,
bool  bw = false 
) [static]

Definition at line 589 of file Grapher.cc.

References PLearn::endl(), PLearn::TVec< T >::first(), PLearn::VMat::getExample(), gridrange, i, PLearn::VMat::length(), PLearn::pgetline(), PLERROR, PLearn::saveAscii(), PLearn::TVec< T >::size(), PLearn::sortRows(), w, and x.

Referenced by run().

{
    if(griddim.size()!=1)
        PLERROR("In Grapher::plot_1D_regression, not a 1D grid!");  
  
    int nx = griddim[0];
    real x = gridrange[0].first;
    real w = gridrange[0].second - x;
    real dx = w/(nx-1);
    int l = trainset.length();
    Mat curve(nx+l,2);
    Mat points(l,2);
    for(int i=0; i<nx; i++)
    {
        curve(i,0) = x;
        curve(i,1) = gridoutputs(i,0);
        x += dx;
    }

    Vec input(1);
    Vec target(1);
    Vec output(1);
    real weight;
    for(int i=0; i<l; i++)
    {
        trainset->getExample(i, input, target, weight);
        trainoutputs->getRow(i, output);
        points(i,0) = input[0];
        points(i,1) = target[0];
        curve(nx+i,0) = input[0];
        curve(nx+i,1) = output[0];
    }

    sortRows(curve);

    saveAscii(basename+"_points.amat", points);
    saveAscii(basename+"_curve.amat", curve);
    Gnuplot gp;
    gp << "plot '" << basename+"_points.amat" << "' with points, '" 
       << basename + "_curve.amat" << "' with lines" << endl;

    pgetline(cin);
}

Here is the call graph for this function:

Here is the caller graph for this function:

void PLearn::Grapher::plot_2D_classification ( string  epsfname,
VMat  trainset,
TVec< int griddim,
TVec< pair< real, real > >  gridrange,
VMat  gridoutputs,
real  radius,
bool  bw = false 
) [static]

Definition at line 635 of file Grapher.cc.

References PLearn::argmax(), PLearn::color(), PLearn::GhostScript::displayGray(), PLearn::GhostScript::displayRGB(), PLearn::endl(), PLearn::fast_exact_is_equal(), PLearn::GhostScript::fillCircle(), PLearn::TVec< T >::first(), PLearn::VMat::getExample(), gridrange, i, j, PLearn::TVec< T >::length(), PLearn::VMat::length(), PLearn::GhostScript::mapping(), PLERROR, PLearn::GhostScript::setcolor(), PLearn::GhostScript::setgray(), PLearn::TVec< T >::size(), w, PLearn::VMat::width(), and x.

Referenced by run().

{
    cerr << "Plotting 2D classification result" << endl;
    if(griddim.size()!=2 || gridrange.size()!=2)
        PLERROR("In Grapher::plot_2D_classification griddim and gridrange must be of size 2");
    int nx = griddim[0];
    int ny = griddim[1];
    int nclasses = gridoutputs.width();
    real x = gridrange[0].first;
    real y = gridrange[1].first;
    real w = gridrange[0].second - x;
    real h = gridrange[1].second - y;
    if(nclasses<2)
        PLERROR("In Grapher::plot_2D_classification number of classes (width of gridoutputs) must be at least 2: it is currently %d",nclasses);

    real gswidth = 600;
    real gsheight = gswidth/w*h;
    GhostScript gs(epsfname, 0, 0, gswidth, gsheight);
    gs.mapping(x, y, w, h, 0, 0, gswidth, gsheight);


    Mat image(ny,nx);
    Vec output(nclasses);
    for(int i=0; i<ny; i++)
        for(int j=0; j<nx; j++)
        {
            gridoutputs->getRow((ny-i-1)+ny*j,output);
            int winner = argmax(output);
            // cout << i << " " << j << " " << output << endl;
            // real winnerval = output[winner];
            if(bw) // grayscale
                image(i,j) = (winner==0 ?0.7 :0.3);
            else // color
                image(i,j) = color(winner,0.7);
        }

    // cout << "IMAGE:" << endl << image << endl;
  
    if(bw)
        gs.displayGray(image, x, y, w, h);
    else
        gs.displayRGB(image, x, y, w, h);

    int l = trainset.length();
    Vec input;
    Vec target;
    real weight;
    gs.setgray(0); // black
    for(int i=0; i<l; i++)
    {
        trainset->getExample(i,input,target,weight);
        if(target.length()==1)
        {
            if(bw)
                gs.setgray(fast_exact_is_equal(target[0], 0) ?0 :1);
            else
                gs.setcolor(color(int(target[0]),0.2));
        }
        else
        {
            if(bw)
                gs.setgray(fast_exact_is_equal(target[0], 0) ?0 :1);
            else
                gs.setcolor(color(argmax(target),0.2));
        }
        gs.fillCircle(input[0],input[1],radius);
    }

}

Here is the call graph for this function:

Here is the caller graph for this function:

void PLearn::Grapher::run ( ) [virtual]

Overload this for runnable objects (default method issues a runtime error)

Reimplemented from PLearn::Object.

Definition at line 720 of file Grapher.cc.

References bw, class1_threshold, computeAutoGridrange(), PLearn::endl(), griddim, gridrange, i, PLearn::TVec< T >::isEmpty(), PLearn::VMat::length(), PLERROR, plot_1D_regression(), plot_2D_classification(), radius, PLearn::Object::save(), save_learner_as, task, and trainset.

{
    int l = trainset->length();
    PP<VecStatsCollector> statscol = new VecStatsCollector();
    learner->setTrainStatsCollector(statscol);
    learner->setTrainingSet(trainset);

    cerr << "*** Training learner on trainset of length " << l << " ... ***" << endl; 
    learner->train();
    cerr << "Final traincosts: " << statscol->getMean() << endl;

    if(save_learner_as!="")
    {
        cerr << "Saving trained learner in file " << save_learner_as << endl;
        PLearn::save(save_learner_as, *learner);
    }


    cerr << "*** Computing outputs on trainset inputs... ***" << endl; 
    Mat trainoutputs(l, learner->outputsize());
    learner->use(trainset, trainoutputs);

    // Try to determine the task if not specified
    if (task == "") {
        if(trainset->inputsize()==1 &&
           trainset->targetsize()==1 && learner->outputsize()==1)
            task = "1D regression";
        else if(trainset->inputsize()==2)
        {
            switch(trainset->targetsize())
            {
            case 0:  // density estimation or clustering
                if(learner->outputsize()>1)
                    task = "2D clustering";
                else
                    task = "2D density";
                break;
            case 1: // classif or regression
                if(learner->outputsize()>1)
                    task = "2D classification";
                else
                    task = "2D regression";
                break;
            default:
                PLERROR("Tasks with targetsize > 1 (multi-regression) not supported");
            }
        }
        else
            PLERROR("Task wih inputsize=%d, targetsize=%d, outputsize=%d not supported", 
                    trainset->inputsize(), trainset->targetsize(), learner->outputsize());
    }
    
    // Now compute outputs on grid
    if(gridrange.isEmpty())
        computeAutoGridrange();
    cerr << "*** Computing outputs on " << griddim << " grid... ***" << endl; 
    VMat gridinputs = new RegularGridVMatrix(griddim, gridrange);
    Mat gridoutputs(gridinputs->length(),learner->outputsize());
    learner->use(gridinputs, gridoutputs);

    if (task == "2D classification" && learner->outputsize() == 1) {
        // Transform a one-class output into a two-class one...
        Mat newgridoutputs(gridinputs->length(), 2);
        for (int i=0; i<gridinputs->length(); ++i) {
            newgridoutputs(i,0) = gridoutputs(i,0) <= class1_threshold;
            newgridoutputs(i,1) = gridoutputs(i,0) > class1_threshold;
        }
        gridoutputs = newgridoutputs;
    }

    cerr << ">>> TASK PERFORMED: " << task << endl;

    string epsfname = basename+".eps";
    cerr << "Creating file: " << epsfname << endl;

    if(radius<0)
        radius = fabs(radius * (gridrange[0].second-gridrange[0].first));

    if(task=="2D classification" || task=="2D clustering")
        plot_2D_classification(epsfname, trainset, griddim, gridrange, gridoutputs, radius, bw);
    else if(task=="1D regression")
        plot_1D_regression(basename, trainset, griddim, gridrange, gridoutputs, trainoutputs, bw);
    //  else if(task=="2D regression")
    //  plot_2D-regression(basename, 
    /*
      else if(task=="2D density")
      plot_2D_density(gridoutputs);
    */

    // Old DX stuff
    /*
      string dset_fname = basename+"_dset.dx";
      cerr << "Computing and writing trainset output field to file " << dset_fname << endl;
      DX_create_dataset_outputs_file(dset_fname, learner, trainset);

      string outputs_fname = basename+"_outputs.dx";
      cerr << "Computing and writing grid output field to file " << outputs_fname << endl; 
      DX_create_grid_outputs_file(outputs_fname, learner, trainset, nx, ny, 
      include_datapoint_grid, 
      xmin, xmax, ymin, ymax);
      cerr << "You can now view those files with OpenDX." << endl;
    */
}

Here is the call graph for this function:


Member Data Documentation

Reimplemented from PLearn::Object.

Definition at line 115 of file Grapher.h.

Definition at line 68 of file Grapher.h.

Referenced by declareOptions().

Definition at line 76 of file Grapher.h.

Referenced by declareOptions(), and run().

Definition at line 70 of file Grapher.h.

Referenced by declareOptions(), and run().

Definition at line 73 of file Grapher.h.

Referenced by declareOptions(), and run().

Definition at line 74 of file Grapher.h.

Referenced by declareOptions(), plot_1D_regression(), plot_2D_classification(), and run().

Definition at line 71 of file Grapher.h.

Referenced by declareOptions().

Definition at line 75 of file Grapher.h.

Referenced by declareOptions(), and run().

Definition at line 78 of file Grapher.h.

Referenced by declareOptions(), and run().

Definition at line 69 of file Grapher.h.

Referenced by declareOptions(), and run().

Definition at line 72 of file Grapher.h.

Referenced by declareOptions(), and run().


The documentation for this class was generated from the following files:
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines