em.cpp 29.1 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 43
/*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
//                For Open Source Computer Vision Library
//
// 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 ifadvised of the possibility of such damage.
//
//M*/

#include "precomp.hpp"

44
namespace cv
45
{
46 47
namespace ml
{
48

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
49
const double minEigenValue = DBL_EPSILON;
50

51
EM::Params::Params(int _nclusters, int _covMatType, const TermCriteria& _termCrit)
52
{
53 54
    nclusters = _nclusters;
    covMatType = _covMatType;
55
    termCrit = _termCrit;
56 57
}

58
class CV_EXPORTS EMImpl : public EM
59
{
60 61 62 63 64
public:
    EMImpl(const Params& _params)
    {
        setParams(_params);
    }
65

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    virtual ~EMImpl() {}

    void setParams(const Params& _params)
    {
        params = _params;
        CV_Assert(params.nclusters > 1);
        CV_Assert(params.covMatType == COV_MAT_SPHERICAL ||
                  params.covMatType == COV_MAT_DIAGONAL ||
                  params.covMatType == COV_MAT_GENERIC);
    }

    Params getParams() const
    {
        return params;
    }
81

82 83 84 85 86 87
    void clear()
    {
        trainSamples.release();
        trainProbs.release();
        trainLogLikelihoods.release();
        trainLabels.release();
88

89 90 91
        weights.release();
        means.release();
        covs.clear();
92

93 94 95
        covsEigenValues.clear();
        invCovsEigenValues.clear();
        covsRotateMats.clear();
96

97 98
        logWeightDivDet.release();
    }
99

100 101 102 103 104 105 106
    bool train(const Ptr<TrainData>& data, int)
    {
        Mat samples = data->getTrainSamples(), labels;
        return train_(samples, labels, noArray(), noArray());
    }

    bool train_(InputArray samples,
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
107
               OutputArray logLikelihoods,
108
               OutputArray labels,
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
109
               OutputArray probs)
110 111 112 113 114
    {
        Mat samplesMat = samples.getMat();
        setTrainData(START_AUTO_STEP, samplesMat, 0, 0, 0, 0);
        return doTrain(START_AUTO_STEP, logLikelihoods, labels, probs);
    }
115

116
    bool trainE(InputArray samples,
117 118 119
                InputArray _means0,
                InputArray _covs0,
                InputArray _weights0,
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
120
                OutputArray logLikelihoods,
121
                OutputArray labels,
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
122
                OutputArray probs)
123 124 125 126
    {
        Mat samplesMat = samples.getMat();
        std::vector<Mat> covs0;
        _covs0.getMatVector(covs0);
127

128
        Mat means0 = _means0.getMat(), weights0 = _weights0.getMat();
129

130 131 132 133
        setTrainData(START_E_STEP, samplesMat, 0, !_means0.empty() ? &means0 : 0,
                     !_covs0.empty() ? &covs0 : 0, !_weights0.empty() ? &weights0 : 0);
        return doTrain(START_E_STEP, logLikelihoods, labels, probs);
    }
134

135
    bool trainM(InputArray samples,
136
                InputArray _probs0,
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
137
                OutputArray logLikelihoods,
138
                OutputArray labels,
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
139
                OutputArray probs)
140
    {
141 142
        Mat samplesMat = samples.getMat();
        Mat probs0 = _probs0.getMat();
143

144 145
        setTrainData(START_M_STEP, samplesMat, !_probs0.empty() ? &probs0 : 0, 0, 0, 0);
        return doTrain(START_M_STEP, logLikelihoods, labels, probs);
146 147
    }

148 149 150 151 152 153 154
    float predict(InputArray _inputs, OutputArray _outputs, int) const
    {
        bool needprobs = _outputs.needed();
        Mat samples = _inputs.getMat(), probs, probsrow;
        int ptype = CV_32F;
        float firstres = 0.f;
        int i, nsamples = samples.rows;
155

156 157 158 159 160 161 162 163
        if( needprobs )
        {
            if( _outputs.fixedType() )
                ptype = _outputs.type();
            _outputs.create(samples.rows, params.nclusters, ptype);
        }
        else
            nsamples = std::min(nsamples, 1);
164

165
        for( i = 0; i < nsamples; i++ )
166
        {
167 168 169 170 171
            if( needprobs )
                probsrow = probs.row(i);
            Vec2d res = computeProbabilities(samples.row(i), needprobs ? &probsrow : 0, ptype);
            if( i == 0 )
                firstres = (float)res[1];
172
        }
173
        return firstres;
174 175
    }

176
    Vec2d predict2(InputArray _sample, OutputArray _probs) const
177
    {
178 179 180
        int ptype = CV_32F;
        Mat sample = _sample.getMat();
        CV_Assert(isTrained());
181

182 183 184 185 186 187 188 189
        CV_Assert(!sample.empty());
        if(sample.type() != CV_64FC1)
        {
            Mat tmp;
            sample.convertTo(tmp, CV_64FC1);
            sample = tmp;
        }
        sample.reshape(1, 1);
190

191 192 193 194 195 196 197 198
        Mat probs;
        if( _probs.needed() )
        {
            if( _probs.fixedType() )
                ptype = _probs.type();
            _probs.create(1, params.nclusters, ptype);
            probs = _probs.getMat();
        }
199

200
        return computeProbabilities(sample, !probs.empty() ? &probs : 0, ptype);
201
    }
202

203
    bool isTrained() const
204
    {
205
        return !means.empty();
206 207
    }

208
    bool isClassifier() const
209
    {
210
        return true;
211 212
    }

213
    int getVarCount() const
214
    {
215
        return means.cols;
216 217
    }

218
    String getDefaultModelName() const
219
    {
220 221
        return "opencv_ml_em";
    }
222

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
    static void checkTrainData(int startStep, const Mat& samples,
                               int nclusters, int covMatType, const Mat* probs, const Mat* means,
                               const std::vector<Mat>* covs, const Mat* weights)
    {
        // Check samples.
        CV_Assert(!samples.empty());
        CV_Assert(samples.channels() == 1);

        int nsamples = samples.rows;
        int dim = samples.cols;

        // Check training params.
        CV_Assert(nclusters > 0);
        CV_Assert(nclusters <= nsamples);
        CV_Assert(startStep == START_AUTO_STEP ||
                  startStep == START_E_STEP ||
                  startStep == START_M_STEP);
        CV_Assert(covMatType == COV_MAT_GENERIC ||
                  covMatType == COV_MAT_DIAGONAL ||
                  covMatType == COV_MAT_SPHERICAL);

        CV_Assert(!probs ||
            (!probs->empty() &&
             probs->rows == nsamples && probs->cols == nclusters &&
             (probs->type() == CV_32FC1 || probs->type() == CV_64FC1)));

        CV_Assert(!weights ||
            (!weights->empty() &&
             (weights->cols == 1 || weights->rows == 1) && static_cast<int>(weights->total()) == nclusters &&
             (weights->type() == CV_32FC1 || weights->type() == CV_64FC1)));

        CV_Assert(!means ||
            (!means->empty() &&
             means->rows == nclusters && means->cols == dim &&
             means->channels() == 1));

        CV_Assert(!covs ||
            (!covs->empty() &&
             static_cast<int>(covs->size()) == nclusters));
        if(covs)
263
        {
264 265 266 267 268 269
            const Size covSize(dim, dim);
            for(size_t i = 0; i < covs->size(); i++)
            {
                const Mat& m = (*covs)[i];
                CV_Assert(!m.empty() && m.size() == covSize && (m.channels() == 1));
            }
270
        }
271 272

        if(startStep == START_E_STEP)
273
        {
274
            CV_Assert(means);
275
        }
276
        else if(startStep == START_M_STEP)
277
        {
278
            CV_Assert(probs);
279
        }
280
    }
281

282
    static void preprocessSampleData(const Mat& src, Mat& dst, int dstType, bool isAlwaysClone)
283
    {
284 285
        if(src.type() == dstType && !isAlwaysClone)
            dst = src;
286
        else
287
            src.convertTo(dst, dstType);
288
    }
289

290
    static void preprocessProbability(Mat& probs)
291
    {
292
        max(probs, 0., probs);
293

294 295
        const double uniformProbability = (double)(1./probs.cols);
        for(int y = 0; y < probs.rows; y++)
296
        {
297
            Mat sampleProbs = probs.row(y);
298

299 300 301 302 303 304 305
            double maxVal = 0;
            minMaxLoc(sampleProbs, 0, &maxVal);
            if(maxVal < FLT_EPSILON)
                sampleProbs.setTo(uniformProbability);
            else
                normalize(sampleProbs, sampleProbs, 1, 0, NORM_L1);
        }
306 307
    }

308 309 310 311 312 313 314 315
    void setTrainData(int startStep, const Mat& samples,
                      const Mat* probs0,
                      const Mat* means0,
                      const std::vector<Mat>* covs0,
                      const Mat* weights0)
    {
        int nclusters = params.nclusters, covMatType = params.covMatType;
        clear();
316

317
        checkTrainData(startStep, samples, nclusters, covMatType, probs0, means0, covs0, weights0);
318

319 320 321
        bool isKMeansInit = (startStep == START_AUTO_STEP) || (startStep == START_E_STEP && (covs0 == 0 || weights0 == 0));
        // Set checked data
        preprocessSampleData(samples, trainSamples, isKMeansInit ? CV_32FC1 : CV_64FC1, false);
322

323 324 325 326 327 328
        // set probs
        if(probs0 && startStep == START_M_STEP)
        {
            preprocessSampleData(*probs0, trainProbs, CV_64FC1, true);
            preprocessProbability(trainProbs);
        }
329

330 331 332 333 334 335 336
        // set weights
        if(weights0 && (startStep == START_E_STEP && covs0))
        {
            weights0->convertTo(weights, CV_64FC1);
            weights.reshape(1,1);
            preprocessProbability(weights);
        }
337

338 339 340 341 342 343 344 345 346 347 348
        // set means
        if(means0 && (startStep == START_E_STEP/* || startStep == START_AUTO_STEP*/))
            means0->convertTo(means, isKMeansInit ? CV_32FC1 : CV_64FC1);

        // set covs
        if(covs0 && (startStep == START_E_STEP && weights0))
        {
            covs.resize(nclusters);
            for(size_t i = 0; i < covs0->size(); i++)
                (*covs0)[i].convertTo(covs[i], CV_64FC1);
        }
349
    }
350

351
    void decomposeCovs()
352
    {
353 354 355 356 357 358 359
        int nclusters = params.nclusters, covMatType = params.covMatType;
        CV_Assert(!covs.empty());
        covsEigenValues.resize(nclusters);
        if(covMatType == COV_MAT_GENERIC)
            covsRotateMats.resize(nclusters);
        invCovsEigenValues.resize(nclusters);
        for(int clusterIndex = 0; clusterIndex < nclusters; clusterIndex++)
360
        {
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
            CV_Assert(!covs[clusterIndex].empty());

            SVD svd(covs[clusterIndex], SVD::MODIFY_A + SVD::FULL_UV);

            if(covMatType == COV_MAT_SPHERICAL)
            {
                double maxSingularVal = svd.w.at<double>(0);
                covsEigenValues[clusterIndex] = Mat(1, 1, CV_64FC1, Scalar(maxSingularVal));
            }
            else if(covMatType == COV_MAT_DIAGONAL)
            {
                covsEigenValues[clusterIndex] = svd.w;
            }
            else //COV_MAT_GENERIC
            {
                covsEigenValues[clusterIndex] = svd.w;
                covsRotateMats[clusterIndex] = svd.u;
            }
            max(covsEigenValues[clusterIndex], minEigenValue, covsEigenValues[clusterIndex]);
            invCovsEigenValues[clusterIndex] = 1./covsEigenValues[clusterIndex];
381 382 383
        }
    }

384
    void clusterTrainSamples()
385
    {
386 387
        int nclusters = params.nclusters;
        int nsamples = trainSamples.rows;
388

389
        // Cluster samples, compute/update means
390

391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
        // Convert samples and means to 32F, because kmeans requires this type.
        Mat trainSamplesFlt, meansFlt;
        if(trainSamples.type() != CV_32FC1)
            trainSamples.convertTo(trainSamplesFlt, CV_32FC1);
        else
            trainSamplesFlt = trainSamples;
        if(!means.empty())
        {
            if(means.type() != CV_32FC1)
                means.convertTo(meansFlt, CV_32FC1);
            else
                meansFlt = means;
        }

        Mat labels;
        kmeans(trainSamplesFlt, nclusters, labels,
               TermCriteria(TermCriteria::COUNT, means.empty() ? 10 : 1, 0.5),
               10, KMEANS_PP_CENTERS, meansFlt);
409

410 411 412 413 414 415 416 417 418
        // Convert samples and means back to 64F.
        CV_Assert(meansFlt.type() == CV_32FC1);
        if(trainSamples.type() != CV_64FC1)
        {
            Mat trainSamplesBuffer;
            trainSamplesFlt.convertTo(trainSamplesBuffer, CV_64FC1);
            trainSamples = trainSamplesBuffer;
        }
        meansFlt.convertTo(means, CV_64FC1);
419

420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
        // Compute weights and covs
        weights = Mat(1, nclusters, CV_64FC1, Scalar(0));
        covs.resize(nclusters);
        for(int clusterIndex = 0; clusterIndex < nclusters; clusterIndex++)
        {
            Mat clusterSamples;
            for(int sampleIndex = 0; sampleIndex < nsamples; sampleIndex++)
            {
                if(labels.at<int>(sampleIndex) == clusterIndex)
                {
                    const Mat sample = trainSamples.row(sampleIndex);
                    clusterSamples.push_back(sample);
                }
            }
            CV_Assert(!clusterSamples.empty());
435

436 437 438 439
            calcCovarMatrix(clusterSamples, covs[clusterIndex], means.row(clusterIndex),
                CV_COVAR_NORMAL + CV_COVAR_ROWS + CV_COVAR_USE_AVG + CV_COVAR_SCALE, CV_64FC1);
            weights.at<double>(clusterIndex) = static_cast<double>(clusterSamples.rows)/static_cast<double>(nsamples);
        }
440

441
        decomposeCovs();
442
    }
443

444
    void computeLogWeightDivDet()
445
    {
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
        int nclusters = params.nclusters;
        CV_Assert(!covsEigenValues.empty());

        Mat logWeights;
        cv::max(weights, DBL_MIN, weights);
        log(weights, logWeights);

        logWeightDivDet.create(1, nclusters, CV_64FC1);
        // note: logWeightDivDet = log(weight_k) - 0.5 * log(|det(cov_k)|)

        for(int clusterIndex = 0; clusterIndex < nclusters; clusterIndex++)
        {
            double logDetCov = 0.;
            const int evalCount = static_cast<int>(covsEigenValues[clusterIndex].total());
            for(int di = 0; di < evalCount; di++)
                logDetCov += std::log(covsEigenValues[clusterIndex].at<double>(params.covMatType != COV_MAT_SPHERICAL ? di : 0));

            logWeightDivDet.at<double>(clusterIndex) = logWeights.at<double>(clusterIndex) - 0.5 * logDetCov;
        }
465 466
    }

467
    bool doTrain(int startStep, OutputArray logLikelihoods, OutputArray labels, OutputArray probs)
468
    {
469 470 471 472
        int nclusters = params.nclusters;
        int dim = trainSamples.cols;
        // Precompute the empty initial train data in the cases of START_E_STEP and START_AUTO_STEP
        if(startStep != START_M_STEP)
473
        {
474 475 476 477 478
            if(covs.empty())
            {
                CV_Assert(weights.empty());
                clusterTrainSamples();
            }
479
        }
480 481

        if(!covs.empty() && covsEigenValues.empty() )
482
        {
483 484
            CV_Assert(invCovsEigenValues.empty());
            decomposeCovs();
485
        }
486

487 488
        if(startStep == START_M_STEP)
            mStep();
489

490 491 492 493
        double trainLogLikelihood, prevTrainLogLikelihood = 0.;
        int maxIters = (params.termCrit.type & TermCriteria::MAX_ITER) ?
            params.termCrit.maxCount : DEFAULT_MAX_ITERS;
        double epsilon = (params.termCrit.type & TermCriteria::EPS) ? params.termCrit.epsilon : 0.;
494

495 496 497 498
        for(int iter = 0; ; iter++)
        {
            eStep();
            trainLogLikelihood = sum(trainLogLikelihoods)[0];
499

500 501 502 503 504 505 506 507
            if(iter >= maxIters - 1)
                break;

            double trainLogLikelihoodDelta = trainLogLikelihood - prevTrainLogLikelihood;
            if( iter != 0 &&
                (trainLogLikelihoodDelta < -DBL_EPSILON ||
                 trainLogLikelihoodDelta < epsilon * std::fabs(trainLogLikelihood)))
                break;
508

509
            mStep();
510

511 512 513 514
            prevTrainLogLikelihood = trainLogLikelihood;
        }

        if( trainLogLikelihood <= -DBL_MAX/10000. )
515
        {
516 517
            clear();
            return false;
518 519
        }

520 521 522 523 524 525 526 527 528 529 530 531 532 533
        // postprocess covs
        covs.resize(nclusters);
        for(int clusterIndex = 0; clusterIndex < nclusters; clusterIndex++)
        {
            if(params.covMatType == COV_MAT_SPHERICAL)
            {
                covs[clusterIndex].create(dim, dim, CV_64FC1);
                setIdentity(covs[clusterIndex], Scalar(covsEigenValues[clusterIndex].at<double>(0)));
            }
            else if(params.covMatType == COV_MAT_DIAGONAL)
            {
                covs[clusterIndex] = Mat::diag(covsEigenValues[clusterIndex]);
            }
        }
534

535 536 537 538 539 540
        if(labels.needed())
            trainLabels.copyTo(labels);
        if(probs.needed())
            trainProbs.copyTo(probs);
        if(logLikelihoods.needed())
            trainLogLikelihoods.copyTo(logLikelihoods);
541

542 543 544 545
        trainSamples.release();
        trainProbs.release();
        trainLabels.release();
        trainLogLikelihoods.release();
546

547 548
        return true;
    }
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
549

550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
    Vec2d computeProbabilities(const Mat& sample, Mat* probs, int ptype) const
    {
        // L_ik = log(weight_k) - 0.5 * log(|det(cov_k)|) - 0.5 *(x_i - mean_k)' cov_k^(-1) (x_i - mean_k)]
        // q = arg(max_k(L_ik))
        // probs_ik = exp(L_ik - L_iq) / (1 + sum_j!=q (exp(L_ij - L_iq))
        // see Alex Smola's blog http://blog.smola.org/page/2 for
        // details on the log-sum-exp trick

        int nclusters = params.nclusters, covMatType = params.covMatType;
        int stype = sample.type();
        CV_Assert(!means.empty());
        CV_Assert((stype == CV_32F || stype == CV_64F) && (ptype == CV_32F || ptype == CV_64F));
        CV_Assert(sample.size() == Size(means.cols, 1));

        int dim = sample.cols;

        Mat L(1, nclusters, CV_64FC1), centeredSample(1, dim, CV_64F);
        int i, label = 0;
        for(int clusterIndex = 0; clusterIndex < nclusters; clusterIndex++)
        {
            const double* mptr = means.ptr<double>(clusterIndex);
            double* dptr = centeredSample.ptr<double>();
            if( stype == CV_32F )
            {
                const float* sptr = sample.ptr<float>();
                for( i = 0; i < dim; i++ )
                    dptr[i] = sptr[i] - mptr[i];
            }
            else
            {
                const double* sptr = sample.ptr<double>();
                for( i = 0; i < dim; i++ )
                    dptr[i] = sptr[i] - mptr[i];
            }
584

585 586
            Mat rotatedCenteredSample = covMatType != COV_MAT_GENERIC ?
                    centeredSample : centeredSample * covsRotateMats[clusterIndex];
587

588 589 590 591 592 593 594 595 596
            double Lval = 0;
            for(int di = 0; di < dim; di++)
            {
                double w = invCovsEigenValues[clusterIndex].at<double>(covMatType != COV_MAT_SPHERICAL ? di : 0);
                double val = rotatedCenteredSample.at<double>(di);
                Lval += w * val * val;
            }
            CV_DbgAssert(!logWeightDivDet.empty());
            L.at<double>(clusterIndex) = logWeightDivDet.at<double>(clusterIndex) - 0.5 * Lval;
597

598 599 600
            if(L.at<double>(clusterIndex) > L.at<double>(label))
                label = clusterIndex;
        }
601

602 603 604 605 606 607 608 609
        double maxLVal = L.at<double>(label);
        double expDiffSum = 0;
        for( i = 0; i < L.cols; i++ )
        {
            double v = std::exp(L.at<double>(i) - maxLVal);
            L.at<double>(i) = v;
            expDiffSum += v; // sum_j(exp(L_ij - L_iq))
        }
610

611 612
        if(probs)
            L.convertTo(*probs, ptype, 1./expDiffSum);
613

614 615 616
        Vec2d res;
        res[0] = std::log(expDiffSum)  + maxLVal - 0.5 * dim * CV_LOG2PI;
        res[1] = label;
617

618 619
        return res;
    }
620

621
    void eStep()
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
622
    {
623 624 625 626
        // Compute probs_ik from means_k, covs_k and weights_k.
        trainProbs.create(trainSamples.rows, params.nclusters, CV_64FC1);
        trainLabels.create(trainSamples.rows, 1, CV_32SC1);
        trainLogLikelihoods.create(trainSamples.rows, 1, CV_64FC1);
627

628 629 630 631
        computeLogWeightDivDet();

        CV_DbgAssert(trainSamples.type() == CV_64FC1);
        CV_DbgAssert(means.type() == CV_64FC1);
632

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
633
        for(int sampleIndex = 0; sampleIndex < trainSamples.rows; sampleIndex++)
634 635 636 637 638 639
        {
            Mat sampleProbs = trainProbs.row(sampleIndex);
            Vec2d res = computeProbabilities(trainSamples.row(sampleIndex), &sampleProbs, CV_64F);
            trainLogLikelihoods.at<double>(sampleIndex) = res[0];
            trainLabels.at<int>(sampleIndex) = static_cast<int>(res[1]);
        }
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
640 641
    }

642
    void mStep()
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
643
    {
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
        // Update means_k, covs_k and weights_k from probs_ik
        int nclusters = params.nclusters;
        int covMatType = params.covMatType;
        int dim = trainSamples.cols;

        // Update weights
        // not normalized first
        reduce(trainProbs, weights, 0, CV_REDUCE_SUM);

        // Update means
        means.create(nclusters, dim, CV_64FC1);
        means = Scalar(0);

        const double minPosWeight = trainSamples.rows * DBL_EPSILON;
        double minWeight = DBL_MAX;
        int minWeightClusterIndex = -1;
        for(int clusterIndex = 0; clusterIndex < nclusters; clusterIndex++)
        {
            if(weights.at<double>(clusterIndex) <= minPosWeight)
                continue;
664

665 666 667 668 669
            if(weights.at<double>(clusterIndex) < minWeight)
            {
                minWeight = weights.at<double>(clusterIndex);
                minWeightClusterIndex = clusterIndex;
            }
670

671 672 673 674 675
            Mat clusterMean = means.row(clusterIndex);
            for(int sampleIndex = 0; sampleIndex < trainSamples.rows; sampleIndex++)
                clusterMean += trainProbs.at<double>(sampleIndex, clusterIndex) * trainSamples.row(sampleIndex);
            clusterMean /= weights.at<double>(clusterIndex);
        }
676

677 678 679 680 681 682 683
        // Update covsEigenValues and invCovsEigenValues
        covs.resize(nclusters);
        covsEigenValues.resize(nclusters);
        if(covMatType == COV_MAT_GENERIC)
            covsRotateMats.resize(nclusters);
        invCovsEigenValues.resize(nclusters);
        for(int clusterIndex = 0; clusterIndex < nclusters; clusterIndex++)
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
684
        {
685 686
            if(weights.at<double>(clusterIndex) <= minPosWeight)
                continue;
687

688 689
            if(covMatType != COV_MAT_SPHERICAL)
                covsEigenValues[clusterIndex].create(1, dim, CV_64FC1);
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
690
            else
691 692 693 694 695 696 697 698 699 700 701 702
                covsEigenValues[clusterIndex].create(1, 1, CV_64FC1);

            if(covMatType == COV_MAT_GENERIC)
                covs[clusterIndex].create(dim, dim, CV_64FC1);

            Mat clusterCov = covMatType != COV_MAT_GENERIC ?
                covsEigenValues[clusterIndex] : covs[clusterIndex];

            clusterCov = Scalar(0);

            Mat centeredSample;
            for(int sampleIndex = 0; sampleIndex < trainSamples.rows; sampleIndex++)
703
            {
704 705 706 707 708
                centeredSample = trainSamples.row(sampleIndex) - means.row(clusterIndex);

                if(covMatType == COV_MAT_GENERIC)
                    clusterCov += trainProbs.at<double>(sampleIndex, clusterIndex) * centeredSample.t() * centeredSample;
                else
709
                {
710 711 712 713 714 715
                    double p = trainProbs.at<double>(sampleIndex, clusterIndex);
                    for(int di = 0; di < dim; di++ )
                    {
                        double val = centeredSample.at<double>(di);
                        clusterCov.at<double>(covMatType != COV_MAT_SPHERICAL ? di : 0) += p*val*val;
                    }
716
                }
717 718
            }

719 720 721 722 723 724 725 726 727 728 729 730
            if(covMatType == COV_MAT_SPHERICAL)
                clusterCov /= dim;

            clusterCov /= weights.at<double>(clusterIndex);

            // Update covsRotateMats for COV_MAT_GENERIC only
            if(covMatType == COV_MAT_GENERIC)
            {
                SVD svd(covs[clusterIndex], SVD::MODIFY_A + SVD::FULL_UV);
                covsEigenValues[clusterIndex] = svd.w;
                covsRotateMats[clusterIndex] = svd.u;
            }
731

732
            max(covsEigenValues[clusterIndex], minEigenValue, covsEigenValues[clusterIndex]);
733

734 735 736 737 738
            // update invCovsEigenValues
            invCovsEigenValues[clusterIndex] = 1./covsEigenValues[clusterIndex];
        }

        for(int clusterIndex = 0; clusterIndex < nclusters; clusterIndex++)
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
739
        {
740 741 742 743 744 745 746 747 748 749
            if(weights.at<double>(clusterIndex) <= minPosWeight)
            {
                Mat clusterMean = means.row(clusterIndex);
                means.row(minWeightClusterIndex).copyTo(clusterMean);
                covs[minWeightClusterIndex].copyTo(covs[clusterIndex]);
                covsEigenValues[minWeightClusterIndex].copyTo(covsEigenValues[clusterIndex]);
                if(covMatType == COV_MAT_GENERIC)
                    covsRotateMats[minWeightClusterIndex].copyTo(covsRotateMats[clusterIndex]);
                invCovsEigenValues[minWeightClusterIndex].copyTo(invCovsEigenValues[clusterIndex]);
            }
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
750
        }
751

752 753 754
        // Normalize weights
        weights /= trainSamples.rows;
    }
755

756 757 758 759 760 761 762 763
    void write_params(FileStorage& fs) const
    {
        fs << "nclusters" << params.nclusters;
        fs << "cov_mat_type" << (params.covMatType == COV_MAT_SPHERICAL ? String("spherical") :
                                 params.covMatType == COV_MAT_DIAGONAL ? String("diagonal") :
                                 params.covMatType == COV_MAT_GENERIC ? String("generic") :
                                 format("unknown_%d", params.covMatType));
        writeTermCrit(fs, params.termCrit);
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
764
    }
765

766
    void write(FileStorage& fs) const
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
767
    {
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
        fs << "training_params" << "{";
        write_params(fs);
        fs << "}";
        fs << "weights" << weights;
        fs << "means" << means;

        size_t i, n = covs.size();

        fs << "covs" << "[";
        for( i = 0; i < n; i++ )
            fs << covs[i];
        fs << "]";
    }

    void read_params(const FileNode& fn)
    {
        Params _params;
        _params.nclusters = (int)fn["nclusters"];
        String s = (String)fn["cov_mat_type"];
        _params.covMatType = s == "spherical" ? COV_MAT_SPHERICAL :
                             s == "diagonal" ? COV_MAT_DIAGONAL :
                             s == "generic" ? COV_MAT_GENERIC : -1;
        CV_Assert(_params.covMatType >= 0);
        _params.termCrit = readTermCrit(fn);
        setParams(_params);
    }

    void read(const FileNode& fn)
    {
        clear();
        read_params(fn["training_params"]);

        fn["weights"] >> weights;
        fn["means"] >> means;

        FileNode cfn = fn["covs"];
        FileNodeIterator cfn_it = cfn.begin();
        int i, n = (int)cfn.size();
        covs.resize(n);

        for( i = 0; i < n; i++, ++cfn_it )
            (*cfn_it) >> covs[i];

        decomposeCovs();
        computeLogWeightDivDet();
813
    }
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
814

815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
    Mat getWeights() const { return weights; }
    Mat getMeans() const { return means; }
    void getCovs(std::vector<Mat>& _covs) const
    {
        _covs.resize(covs.size());
        std::copy(covs.begin(), covs.end(), _covs.begin());
    }

    Params params;

    // all inner matrices have type CV_64FC1
    Mat trainSamples;
    Mat trainProbs;
    Mat trainLogLikelihoods;
    Mat trainLabels;

    Mat weights;
    Mat means;
    std::vector<Mat> covs;

    std::vector<Mat> covsEigenValues;
    std::vector<Mat> covsRotateMats;
    std::vector<Mat> invCovsEigenValues;
    Mat logWeightDivDet;
};


Ptr<EM> EM::train(InputArray samples, OutputArray logLikelihoods,
                  OutputArray labels, OutputArray probs,
                  const EM::Params& params)
{
    Ptr<EMImpl> em = makePtr<EMImpl>(params);
    if(!em->train_(samples, logLikelihoods, labels, probs))
        em.release();
    return em;
850 851
}

852 853 854 855
Ptr<EM> EM::train_startWithE(InputArray samples, InputArray means0,
                             InputArray covs0, InputArray weights0,
                             OutputArray logLikelihoods, OutputArray labels,
                             OutputArray probs, const EM::Params& params)
856
{
857 858 859 860 861
    Ptr<EMImpl> em = makePtr<EMImpl>(params);
    if(!em->trainE(samples, means0, covs0, weights0, logLikelihoods, labels, probs))
        em.release();
    return em;
}
862

863 864 865 866 867 868 869 870
Ptr<EM> EM::train_startWithM(InputArray samples, InputArray probs0,
                             OutputArray logLikelihoods, OutputArray labels,
                             OutputArray probs, const EM::Params& params)
{
    Ptr<EMImpl> em = makePtr<EMImpl>(params);
    if(!em->trainM(samples, probs0, logLikelihoods, labels, probs))
        em.release();
    return em;
871 872
}

873 874 875 876 877 878
Ptr<EM> EM::create(const Params& params)
{
    return makePtr<EMImpl>(params);
}

}
879
} // namespace cv
880 881

/* End of file. */