nbayes.cpp 15.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
/*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.
//
//
//            Intel License Agreement
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// 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.
//
//   * The name of Intel Corporation may not be used to endorse or promote products
//     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"

43 44
namespace cv {
namespace ml {
45 46


47
class NormalBayesClassifierImpl : public NormalBayesClassifier
48
{
49 50
public:
    NormalBayesClassifierImpl()
51
    {
52
        nallvars = 0;
53 54
    }

55
    bool train( const Ptr<TrainData>& trainData, int flags )
56
    {
57 58 59 60 61 62
        const float min_variation = FLT_EPSILON;
        Mat responses = trainData->getNormCatResponses();
        Mat __cls_labels = trainData->getClassLabels();
        Mat __var_idx = trainData->getVarIdx();
        Mat samples = trainData->getTrainSamples();
        int nclasses = (int)__cls_labels.total();
63

64 65
        int nvars = trainData->getNVars();
        int s, c1, c2, cls;
66

67 68
        int __nallvars = trainData->getNAllVars();
        bool update = (flags & UPDATE_MODEL) != 0;
69

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
        if( !update )
        {
            nallvars = __nallvars;
            count.resize(nclasses);
            sum.resize(nclasses);
            productsum.resize(nclasses);
            avg.resize(nclasses);
            inv_eigen_values.resize(nclasses);
            cov_rotate_mats.resize(nclasses);

            for( cls = 0; cls < nclasses; cls++ )
            {
                count[cls]            = Mat::zeros( 1, nvars, CV_32SC1 );
                sum[cls]              = Mat::zeros( 1, nvars, CV_64FC1 );
                productsum[cls]       = Mat::zeros( nvars, nvars, CV_64FC1 );
                avg[cls]              = Mat::zeros( 1, nvars, CV_64FC1 );
                inv_eigen_values[cls] = Mat::zeros( 1, nvars, CV_64FC1 );
                cov_rotate_mats[cls]  = Mat::zeros( nvars, nvars, CV_64FC1 );
            }
89

90 91
            var_idx = __var_idx;
            cls_labels = __cls_labels;
92

93 94 95
            c.create(1, nclasses, CV_64FC1);
        }
        else
96
        {
97 98 99 100 101 102 103 104
            // check that the new training data has the same dimensionality etc.
            if( nallvars != __nallvars ||
                var_idx.size() != __var_idx.size() ||
                norm(var_idx, __var_idx, NORM_INF) != 0 ||
                cls_labels.size() != __cls_labels.size() ||
                norm(cls_labels, __cls_labels, NORM_INF) != 0 )
                CV_Error( CV_StsBadArg,
                "The new training data is inconsistent with the original training data; varIdx and the class labels should be the same" );
105 106
        }

107 108
        Mat cov( nvars, nvars, CV_64FC1 );
        int nsamples = samples.rows;
109

110 111
        // process train data (count, sum , productsum)
        for( s = 0; s < nsamples; s++ )
112
        {
113 114 115 116 117
            cls = responses.at<int>(s);
            int* count_data = count[cls].ptr<int>();
            double* sum_data = sum[cls].ptr<double>();
            double* prod_data = productsum[cls].ptr<double>();
            const float* train_vec = samples.ptr<float>(s);
118

119 120 121 122 123 124 125 126 127
            for( c1 = 0; c1 < nvars; c1++, prod_data += nvars )
            {
                double val1 = train_vec[c1];
                sum_data[c1] += val1;
                count_data[c1]++;
                for( c2 = c1; c2 < nvars; c2++ )
                    prod_data[c2] += train_vec[c2]*val1;
            }
        }
128

129
        Mat vt;
130

131 132
        // calculate avg, covariance matrix, c
        for( cls = 0; cls < nclasses; cls++ )
133
        {
134 135 136 137 138 139
            double det = 1;
            int i, j;
            Mat& w = inv_eigen_values[cls];
            int* count_data = count[cls].ptr<int>();
            double* avg_data = avg[cls].ptr<double>();
            double* sum1 = sum[cls].ptr<double>();
140

141
            completeSymm(productsum[cls], 0);
142

143
            for( j = 0; j < nvars; j++ )
144
            {
145 146
                int n = count_data[j];
                avg_data[j] = n ? sum1[j] / n : 0.;
147 148
            }

149 150 151
            count_data = count[cls].ptr<int>();
            avg_data = avg[cls].ptr<double>();
            sum1 = sum[cls].ptr<double>();
152

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
            for( i = 0; i < nvars; i++ )
            {
                double* avg2_data = avg[cls].ptr<double>();
                double* sum2 = sum[cls].ptr<double>();
                double* prod_data = productsum[cls].ptr<double>(i);
                double* cov_data = cov.ptr<double>(i);
                double s1val = sum1[i];
                double avg1 = avg_data[i];
                int _count = count_data[i];

                for( j = 0; j <= i; j++ )
                {
                    double avg2 = avg2_data[j];
                    double cov_val = prod_data[j] - avg1 * sum2[j] - avg2 * s1val + avg1 * avg2 * _count;
                    cov_val = (_count > 1) ? cov_val / (_count - 1) : cov_val;
                    cov_data[j] = cov_val;
                }
            }
171

172
            completeSymm( cov, 1 );
173

174 175 176 177 178
            SVD::compute(cov, w, cov_rotate_mats[cls], noArray());
            transpose(cov_rotate_mats[cls], cov_rotate_mats[cls]);
            cv::max(w, min_variation, w);
            for( j = 0; j < nvars; j++ )
                det *= w.at<double>(j);
179

180 181 182
            divide(1., w, w);
            c.at<double>(cls) = det > 0 ? log(det) : -700;
        }
183

184
        return true;
185
    }
186

187
    class NBPredictBody : public ParallelLoopBody
188
    {
189 190 191 192 193 194
    public:
        NBPredictBody( const Mat& _c, const vector<Mat>& _cov_rotate_mats,
                       const vector<Mat>& _inv_eigen_values,
                       const vector<Mat>& _avg,
                       const Mat& _samples, const Mat& _vidx, const Mat& _cls_labels,
                       Mat& _results, Mat& _results_prob, bool _rawOutput )
195
        {
196 197 198 199 200 201 202 203
            c = &_c;
            cov_rotate_mats = &_cov_rotate_mats;
            inv_eigen_values = &_inv_eigen_values;
            avg = &_avg;
            samples = &_samples;
            vidx = &_vidx;
            cls_labels = &_cls_labels;
            results = &_results;
204
            results_prob = !_results_prob.empty() ? &_results_prob : 0;
205 206
            rawOutput = _rawOutput;
        }
207

208 209 210 211 212 213 214
        const Mat* c;
        const vector<Mat>* cov_rotate_mats;
        const vector<Mat>* inv_eigen_values;
        const vector<Mat>* avg;
        const Mat* samples;
        const Mat* vidx;
        const Mat* cls_labels;
215

216 217 218 219
        Mat* results_prob;
        Mat* results;
        float* value;
        bool rawOutput;
220

221 222 223 224 225 226 227 228 229 230 231
        void operator()( const Range& range ) const
        {
            int cls = -1;
            int rtype = 0, rptype = 0;
            size_t rstep = 0, rpstep = 0;
            int nclasses = (int)cls_labels->total();
            int nvars = avg->at(0).cols;
            double probability = 0;
            const int* vptr = vidx && !vidx->empty() ? vidx->ptr<int>() : 0;

            if (results)
232
            {
233 234
                rtype = results->type();
                rstep = results->isContinuous() ? 1 : results->step/results->elemSize();
235
            }
236
            if (results_prob)
237
            {
238
                rptype = results_prob->type();
239
                rpstep = results_prob->isContinuous() ? results_prob->cols : results_prob->step/results_prob->elemSize();
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
            }
            // allocate memory and initializing headers for calculating
            cv::AutoBuffer<double> _buffer(nvars*2);
            double* _diffin = _buffer;
            double* _diffout = _buffer + nvars;
            Mat diffin( 1, nvars, CV_64FC1, _diffin );
            Mat diffout( 1, nvars, CV_64FC1, _diffout );

            for(int k = range.start; k < range.end; k++ )
            {
                double opt = FLT_MAX;

                for(int i = 0; i < nclasses; i++ )
                {
                    double cur = c->at<double>(i);
                    const Mat& u = cov_rotate_mats->at(i);
                    const Mat& w = inv_eigen_values->at(i);

                    const double* avg_data = avg->at(i).ptr<double>();
                    const float* x = samples->ptr<float>(k);

                    // cov = u w u'  -->  cov^(-1) = u w^(-1) u'
                    for(int j = 0; j < nvars; j++ )
                        _diffin[j] = avg_data[j] - x[vptr ? vptr[j] : j];

                    gemm( diffin, u, 1, noArray(), 0, diffout, GEMM_2_T );
                    for(int j = 0; j < nvars; j++ )
                    {
                        double d = _diffout[j];
                        cur += d*d*w.ptr<double>()[j];
                    }

                    if( cur < opt )
                    {
                        cls = i;
                        opt = cur;
                    }
                    probability = exp( -0.5 * cur );

                    if( results_prob )
                    {
                        if ( rptype == CV_32FC1 )
                            results_prob->ptr<float>()[k*rpstep + i] = (float)probability;
                        else
                            results_prob->ptr<double>()[k*rpstep + i] = probability;
                    }
                }

                int ival = rawOutput ? cls : cls_labels->at<int>(cls);
                if( results )
                {
                    if( rtype == CV_32SC1 )
                        results->ptr<int>()[k*rstep] = ival;
                    else
                        results->ptr<float>()[k*rstep] = (float)ival;
                }
296
            }
297
        }
298
    };
299

300
    float predict( InputArray _samples, OutputArray _results, int flags ) const
301
    {
302
        return predictProb(_samples, _results, noArray(), flags);
303 304
    }

305
    float predictProb( InputArray _samples, OutputArray _results, OutputArray _resultsProb, int flags ) const
306
    {
307 308 309 310
        int value=0;
        Mat samples = _samples.getMat(), results, resultsProb;
        int nsamples = samples.rows, nclasses = (int)cls_labels.total();
        bool rawOutput = (flags & RAW_OUTPUT) != 0;
311

312 313 314
        if( samples.type() != CV_32F || samples.cols != nallvars )
            CV_Error( CV_StsBadArg,
                     "The input samples must be 32f matrix with the number of columns = nallvars" );
315

316
        if( (samples.rows > 1) && (! _results.needed()) )
317 318
            CV_Error( CV_StsNullPtr,
                     "When the number of input samples is >1, the output vector of results must be passed" );
319

320 321 322 323 324 325 326
        if( _results.needed() )
        {
            _results.create(nsamples, 1, CV_32S);
            results = _results.getMat();
        }
        else
            results = Mat(1, 1, CV_32S, &value);
327

328 329 330 331 332
        if( _resultsProb.needed() )
        {
            _resultsProb.create(nsamples, nclasses, CV_32F);
            resultsProb = _resultsProb.getMat();
        }
333

334 335 336
        cv::parallel_for_(cv::Range(0, nsamples),
                          NBPredictBody(c, cov_rotate_mats, inv_eigen_values, avg, samples,
                                       var_idx, cls_labels, results, resultsProb, rawOutput));
337

338 339
        return (float)value;
    }
340

341 342 343
    void write( FileStorage& fs ) const
    {
        int nclasses = (int)cls_labels.total(), i;
344

345
        writeFormat(fs);
346 347
        fs << "var_count" << (var_idx.empty() ? nallvars : (int)var_idx.total());
        fs << "var_all" << nallvars;
348

349 350 351
        if( !var_idx.empty() )
            fs << "var_idx" << var_idx;
        fs << "cls_labels" << cls_labels;
352

353 354 355
        fs << "count" << "[";
        for( i = 0; i < nclasses; i++ )
            fs << count[i];
356

357 358 359
        fs << "]" << "sum" << "[";
        for( i = 0; i < nclasses; i++ )
            fs << sum[i];
360

361 362 363
        fs << "]" << "productsum" << "[";
        for( i = 0; i < nclasses; i++ )
            fs << productsum[i];
364

365 366 367
        fs << "]" << "avg" << "[";
        for( i = 0; i < nclasses; i++ )
            fs << avg[i];
368

369 370 371
        fs << "]" << "inv_eigen_values" << "[";
        for( i = 0; i < nclasses; i++ )
            fs << inv_eigen_values[i];
372

373 374 375
        fs << "]" << "cov_rotate_mats" << "[";
        for( i = 0; i < nclasses; i++ )
            fs << cov_rotate_mats[i];
376

377
        fs << "]";
378

379 380
        fs << "c" << c;
    }
381

382 383 384
    void read( const FileNode& fn )
    {
        clear();
385

386
        fn["var_all"] >> nallvars;
387

388 389 390
        if( nallvars <= 0 )
            CV_Error( CV_StsParseError,
                     "The field \"var_count\" of NBayes classifier is missing or non-positive" );
391

392 393
        fn["var_idx"] >> var_idx;
        fn["cls_labels"] >> cls_labels;
394

395
        int nclasses = (int)cls_labels.total(), i;
396

397 398
        if( cls_labels.empty() || nclasses < 1 )
            CV_Error( CV_StsParseError, "No or invalid \"cls_labels\" in NBayes classifier" );
399

400 401 402 403 404 405 406
        FileNodeIterator
            count_it = fn["count"].begin(),
            sum_it = fn["sum"].begin(),
            productsum_it = fn["productsum"].begin(),
            avg_it = fn["avg"].begin(),
            inv_eigen_values_it = fn["inv_eigen_values"].begin(),
            cov_rotate_mats_it = fn["cov_rotate_mats"].begin();
407

408 409 410 411 412 413
        count.resize(nclasses);
        sum.resize(nclasses);
        productsum.resize(nclasses);
        avg.resize(nclasses);
        inv_eigen_values.resize(nclasses);
        cov_rotate_mats.resize(nclasses);
414

415 416 417 418 419 420 421 422 423 424
        for( i = 0; i < nclasses; i++, ++count_it, ++sum_it, ++productsum_it, ++avg_it,
                                    ++inv_eigen_values_it, ++cov_rotate_mats_it )
        {
            *count_it >> count[i];
            *sum_it >> sum[i];
            *productsum_it >> productsum[i];
            *avg_it >> avg[i];
            *inv_eigen_values_it >> inv_eigen_values[i];
            *cov_rotate_mats_it >> cov_rotate_mats[i];
        }
425

426
        fn["c"] >> c;
427 428
    }

429
    void clear()
430
    {
431 432 433 434 435 436 437 438 439 440 441
        count.clear();
        sum.clear();
        productsum.clear();
        avg.clear();
        inv_eigen_values.clear();
        cov_rotate_mats.clear();

        var_idx.release();
        cls_labels.release();
        c.release();
        nallvars = 0;
442 443
    }

444 445 446
    bool isTrained() const { return !avg.empty(); }
    bool isClassifier() const { return true; }
    int getVarCount() const { return nallvars; }
447
    String getDefaultName() const { return "opencv_ml_nbayes"; }
448

449 450 451 452
    int nallvars;
    Mat var_idx, cls_labels, c;
    vector<Mat> count, sum, productsum, avg, inv_eigen_values, cov_rotate_mats;
};
453 454


455
Ptr<NormalBayesClassifier> NormalBayesClassifier::create()
456
{
457 458
    Ptr<NormalBayesClassifierImpl> p = makePtr<NormalBayesClassifierImpl>();
    return p;
459 460
}

461 462 463 464
}
}

/* End of file. */