rtrees.cpp 14.8 KB
Newer Older
1 2 3 4 5 6 7 8 9
/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
10 11
//                           License Agreement
//                For Open Source Computer Vision Library
12 13
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
14
// Copyright (C) 2014, Itseez Inc, all rights reserved.
15 16 17 18 19 20 21 22 23 24 25 26
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
27
//   * The name of the copyright holders may not be used to endorse or promote products
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "precomp.hpp"

45 46
namespace cv {
namespace ml {
47

48 49 50
//////////////////////////////////////////////////////////////////////////////////////////
//                                  Random trees                                        //
//////////////////////////////////////////////////////////////////////////////////////////
51
RTreeParams::RTreeParams()
52
{
53 54 55
    calcVarImportance = false;
    nactiveVars = 0;
    termCrit = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 50, 0.1);
56 57
}

58 59 60
RTreeParams::RTreeParams(bool _calcVarImportance,
                         int _nactiveVars,
                         TermCriteria _termCrit )
61
{
62 63 64
    calcVarImportance = _calcVarImportance;
    nactiveVars = _nactiveVars;
    termCrit = _termCrit;
65 66 67
}


68
class DTreesImplForRTrees : public DTreesImpl
69
{
70
public:
71
    DTreesImplForRTrees()
72
    {
73 74 75 76 77 78 79 80 81
        params.setMaxDepth(5);
        params.setMinSampleCount(10);
        params.setRegressionAccuracy(0.f);
        params.useSurrogates = false;
        params.setMaxCategories(10);
        params.setCVFolds(0);
        params.use1SERule = false;
        params.truncatePrunedTree = false;
        params.priors = Mat();
82
    }
83
    virtual ~DTreesImplForRTrees() {}
84

85
    void clear()
86
    {
87 88
        DTreesImpl::clear();
        oobError = 0.;
89
        rng = RNG((uint64)-1);
90
    }
91

92
    const vector<int>& getActiveVars()
93
    {
94 95
        int i, nvars = (int)allVars.size(), m = (int)activeVars.size();
        for( i = 0; i < nvars; i++ )
96
        {
97 98 99
            int i1 = rng.uniform(0, nvars);
            int i2 = rng.uniform(0, nvars);
            std::swap(allVars[i1], allVars[i2]);
100
        }
101 102 103
        for( i = 0; i < m; i++ )
            activeVars[i] = allVars[i];
        return activeVars;
104 105
    }

106
    void startTraining( const Ptr<TrainData>& trainData, int flags )
107
    {
108 109 110 111 112 113 114 115
        DTreesImpl::startTraining(trainData, flags);
        int nvars = w->data->getNVars();
        int i, m = rparams.nactiveVars > 0 ? rparams.nactiveVars : cvRound(std::sqrt((double)nvars));
        m = std::min(std::max(m, 1), nvars);
        allVars.resize(nvars);
        activeVars.resize(m);
        for( i = 0; i < nvars; i++ )
            allVars[i] = varIdx[i];
116 117
    }

118
    void endTraining()
119
    {
120 121 122 123 124
        DTreesImpl::endTraining();
        vector<int> a, b;
        std::swap(allVars, a);
        std::swap(activeVars, b);
    }
125

126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
    bool train( const Ptr<TrainData>& trainData, int flags )
    {
        startTraining(trainData, flags);
        int treeidx, ntrees = (rparams.termCrit.type & TermCriteria::COUNT) != 0 ?
            rparams.termCrit.maxCount : 10000;
        int i, j, k, vi, vi_, n = (int)w->sidx.size();
        int nclasses = (int)classLabels.size();
        double eps = (rparams.termCrit.type & TermCriteria::EPS) != 0 &&
            rparams.termCrit.epsilon > 0 ? rparams.termCrit.epsilon : 0.;
        vector<int> sidx(n);
        vector<uchar> oobmask(n);
        vector<int> oobidx;
        vector<int> oobperm;
        vector<double> oobres(n, 0.);
        vector<int> oobcount(n, 0);
        vector<int> oobvotes(n*nclasses, 0);
        int nvars = w->data->getNVars();
        int nallvars = w->data->getNAllVars();
        const int* vidx = !varIdx.empty() ? &varIdx[0] : 0;
        vector<float> samplebuf(nallvars);
        Mat samples = w->data->getSamples();
        float* psamples = samples.ptr<float>();
        size_t sstep0 = samples.step1(), sstep1 = 1;
        Mat sample0, sample(nallvars, 1, CV_32F, &samplebuf[0]);
        int predictFlags = _isClassifier ? (PREDICT_MAX_VOTE + RAW_OUTPUT) : PREDICT_SUM;

        bool calcOOBError = eps > 0 || rparams.calcVarImportance;
        double max_response = 0.;

        if( w->data->getLayout() == COL_SAMPLE )
            std::swap(sstep0, sstep1);

        if( !_isClassifier )
159
        {
160 161 162 163 164
            for( i = 0; i < n; i++ )
            {
                double val = std::abs(w->ord_responses[w->sidx[i]]);
                max_response = std::max(max_response, val);
            }
165 166
        }

167 168
        if( rparams.calcVarImportance )
            varImportance.resize(nallvars, 0.f);
169

170
        for( treeidx = 0; treeidx < ntrees; treeidx++ )
171
        {
172 173
            for( i = 0; i < n; i++ )
                oobmask[i] = (uchar)1;
174

175 176 177 178 179
            for( i = 0; i < n; i++ )
            {
                j = rng.uniform(0, n);
                sidx[i] = w->sidx[j];
                oobmask[j] = (uchar)0;
180
            }
181 182 183
            int root = addTree( sidx );
            if( root < 0 )
                return false;
184

185
            if( calcOOBError )
186
            {
187 188 189
                oobidx.clear();
                for( i = 0; i < n; i++ )
                {
190
                    if( oobmask[i] )
191 192 193 194 195 196 197 198
                        oobidx.push_back(i);
                }
                int n_oob = (int)oobidx.size();
                // if there is no out-of-bag samples, we can not compute OOB error
                // nor update the variable importance vector; so we proceed to the next tree
                if( n_oob == 0 )
                    continue;
                double ncorrect_responses = 0.;
199

200 201
                oobError = 0.;
                for( i = 0; i < n_oob; i++ )
202
                {
203 204
                    j = oobidx[i];
                    sample = Mat( nallvars, 1, CV_32F, psamples + sstep0*w->sidx[j], sstep1*sizeof(psamples[0]) );
205

206 207
                    double val = predictTrees(Range(treeidx, treeidx+1), sample, predictFlags);
                    if( !_isClassifier )
208
                    {
209 210 211 212 213 214 215
                        oobres[j] += val;
                        oobcount[j]++;
                        double true_val = w->ord_responses[w->sidx[j]];
                        double a = oobres[j]/oobcount[j] - true_val;
                        oobError += a*a;
                        val = (val - true_val)/max_response;
                        ncorrect_responses += std::exp( -val*val );
216
                    }
217
                    else
218
                    {
219
                        int ival = cvRound(val);
220
                        //Voting scheme to combine OOB errors of each tree
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
                        int* votes = &oobvotes[j*nclasses];
                        votes[ival]++;
                        int best_class = 0;
                        for( k = 1; k < nclasses; k++ )
                            if( votes[best_class] < votes[k] )
                                best_class = k;
                        int diff = best_class != w->cat_responses[w->sidx[j]];
                        oobError += diff;
                        ncorrect_responses += diff == 0;
                    }
                }

                oobError /= n_oob;
                if( rparams.calcVarImportance && n_oob > 1 )
                {
236
                    Mat sample_clone;
237 238 239
                    oobperm.resize(n_oob);
                    for( i = 0; i < n_oob; i++ )
                        oobperm[i] = oobidx[i];
240 241
                    for (i = n_oob - 1; i > 0; --i)  //Randomly shuffle indices so we can permute features
                    {
242
                        int r_i = rng.uniform(0, n_oob);
243 244
                        std::swap(oobperm[i], oobperm[r_i]);
                    }
245

246 247
                    for( vi_ = 0; vi_ < nvars; vi_++ )
                    {
248
                        vi = vidx ? vidx[vi_] : vi_; //Ensure that only the user specified predictors are used for training
249
                        double ncorrect_responses_permuted = 0;
250

251
                        for( i = 0; i < n_oob; i++ )
252
                        {
253 254 255
                            j = oobidx[i];
                            int vj = oobperm[i];
                            sample0 = Mat( nallvars, 1, CV_32F, psamples + sstep0*w->sidx[j], sstep1*sizeof(psamples[0]) );
256
                            sample0.copyTo(sample_clone); //create a copy so we don't mess up the original data
257
                            sample_clone.at<float>(vi) = psamples[sstep0*w->sidx[vj] + sstep1*vi];
258

259
                            double val = predictTrees(Range(treeidx, treeidx+1), sample_clone, predictFlags);
260 261 262 263 264 265
                            if( !_isClassifier )
                            {
                                val = (val - w->ord_responses[w->sidx[j]])/max_response;
                                ncorrect_responses_permuted += exp( -val*val );
                            }
                            else
266
                            {
267
                                ncorrect_responses_permuted += cvRound(val) == w->cat_responses[w->sidx[j]];
268
                            }
269
                        }
270
                        varImportance[vi] += (float)(ncorrect_responses - ncorrect_responses_permuted);
271 272 273
                    }
                }
            }
274 275
            if( calcOOBError && oobError < eps )
                break;
276 277
        }

278
        if( rparams.calcVarImportance )
279
        {
280 281 282
            for( vi_ = 0; vi_ < nallvars; vi_++ )
                varImportance[vi_] = std::max(varImportance[vi_], 0.f);
            normalize(varImportance, varImportance, 1., 0, NORM_L1);
283
        }
284 285
        endTraining();
        return true;
286
    }
287 288

    void writeTrainingParams( FileStorage& fs ) const
289
    {
290 291
        DTreesImpl::writeTrainingParams(fs);
        fs << "nactive_vars" << rparams.nactiveVars;
292
    }
Andrey Kamaev's avatar
Andrey Kamaev committed
293

294
    void write( FileStorage& fs ) const
295
    {
296 297
        if( roots.empty() )
            CV_Error( CV_StsBadArg, "RTrees have not been trained" );
Andrey Kamaev's avatar
Andrey Kamaev committed
298

299
        writeFormat(fs);
300
        writeParams(fs);
301

302 303 304
        fs << "oob_error" << oobError;
        if( !varImportance.empty() )
            fs << "var_importance" << varImportance;
305

306
        int k, ntrees = (int)roots.size();
307

308 309
        fs << "ntrees" << ntrees
           << "trees" << "[";
310 311 312

        for( k = 0; k < ntrees; k++ )
        {
313 314 315
            fs << "{";
            writeTree(fs, roots[k]);
            fs << "}";
316 317
        }

318 319
        fs << "]";
    }
320

321
    void readParams( const FileNode& fn )
322
    {
323 324 325 326
        DTreesImpl::readParams(fn);

        FileNode tparams_node = fn["training_params"];
        rparams.nactiveVars = (int)tparams_node["nactive_vars"];
327 328
    }

329 330 331
    void read( const FileNode& fn )
    {
        clear();
332

333 334 335 336
        //int nclasses = (int)fn["nclasses"];
        //int nsamples = (int)fn["nsamples"];
        oobError = (double)fn["oob_error"];
        int ntrees = (int)fn["ntrees"];
337

338
        readVectorOrMat(fn["var_importance"], varImportance);
339

340
        readParams(fn);
341

342 343 344
        FileNode trees_node = fn["trees"];
        FileNodeIterator it = trees_node.begin();
        CV_Assert( ntrees == (int)trees_node.size() );
345

346 347 348 349 350
        for( int treeidx = 0; treeidx < ntrees; treeidx++, ++it )
        {
            FileNode nfn = (*it)["nodes"];
            readTree(nfn);
        }
351 352
    }

353
    RTreeParams rparams;
354 355 356 357 358
    double oobError;
    vector<float> varImportance;
    vector<int> allVars, activeVars;
    RNG rng;
};
359 360


361
class RTreesImpl : public RTrees
362
{
363
public:
364 365 366 367 368 369 370 371 372 373 374 375 376 377
    CV_IMPL_PROPERTY(bool, CalculateVarImportance, impl.rparams.calcVarImportance)
    CV_IMPL_PROPERTY(int, ActiveVarCount, impl.rparams.nactiveVars)
    CV_IMPL_PROPERTY_S(TermCriteria, TermCriteria, impl.rparams.termCrit)

    CV_WRAP_SAME_PROPERTY(int, MaxCategories, impl.params)
    CV_WRAP_SAME_PROPERTY(int, MaxDepth, impl.params)
    CV_WRAP_SAME_PROPERTY(int, MinSampleCount, impl.params)
    CV_WRAP_SAME_PROPERTY(int, CVFolds, impl.params)
    CV_WRAP_SAME_PROPERTY(bool, UseSurrogates, impl.params)
    CV_WRAP_SAME_PROPERTY(bool, Use1SERule, impl.params)
    CV_WRAP_SAME_PROPERTY(bool, TruncatePrunedTree, impl.params)
    CV_WRAP_SAME_PROPERTY(float, RegressionAccuracy, impl.params)
    CV_WRAP_SAME_PROPERTY_S(cv::Mat, Priors, impl.params)

378 379
    RTreesImpl() {}
    virtual ~RTreesImpl() {}
380

381
    String getDefaultName() const { return "opencv_ml_rtrees"; }
382

383
    bool train( const Ptr<TrainData>& trainData, int flags )
384
    {
385 386
        if (impl.getCVFolds() != 0)
            CV_Error(Error::StsBadArg, "Cross validation for RTrees is not implemented");
387
        return impl.train(trainData, flags);
388 389
    }

390
    float predict( InputArray samples, OutputArray results, int flags ) const
391
    {
392
        return impl.predict(samples, results, flags);
393 394
    }

395 396 397 398
    void write( FileStorage& fs ) const
    {
        impl.write(fs);
    }
399

400 401 402 403
    void read( const FileNode& fn )
    {
        impl.read(fn);
    }
404

405 406
    Mat getVarImportance() const { return Mat_<float>(impl.varImportance, true); }
    int getVarCount() const { return impl.getVarCount(); }
407

408 409
    bool isTrained() const { return impl.isTrained(); }
    bool isClassifier() const { return impl.isClassifier(); }
410

411 412 413 414
    const vector<int>& getRoots() const { return impl.getRoots(); }
    const vector<Node>& getNodes() const { return impl.getNodes(); }
    const vector<Split>& getSplits() const { return impl.getSplits(); }
    const vector<int>& getSubsets() const { return impl.getSubsets(); }
415

416 417
    DTreesImplForRTrees impl;
};
418 419


420
Ptr<RTrees> RTrees::create()
421
{
422
    return makePtr<RTreesImpl>();
423 424
}

425
}}
426 427

// End of file.