em.cpp 21.3 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
{

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

///////////////////////////////////////////////////////////////////////////////////////////////////////
50

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
51
EM::EM(int _nclusters, int _covMatType, const TermCriteria& _termCrit)
52
{
53 54
    nclusters = _nclusters;
    covMatType = _covMatType;
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
55 56
    maxIters = (_termCrit.type & TermCriteria::MAX_ITER) ? _termCrit.maxCount : DEFAULT_MAX_ITERS;
    epsilon = (_termCrit.type & TermCriteria::EPS) ? _termCrit.epsilon : 0;
57 58
}

59
EM::~EM()
60
{
61
    //clear();
62 63
}

64
void EM::clear()
65
{
66 67 68 69
    trainSamples.release();
    trainProbs.release();
    trainLogLikelihoods.release();
    trainLabels.release();
70

71 72 73
    weights.release();
    means.release();
    covs.clear();
74

75 76 77
    covsEigenValues.clear();
    invCovsEigenValues.clear();
    covsRotateMats.clear();
78

79 80
    logWeightDivDet.release();
}
81

82 83
    
bool EM::train(InputArray samples,
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
84
               OutputArray logLikelihoods,
85
               OutputArray labels,
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
86
               OutputArray probs)
87 88 89
{
    Mat samplesMat = samples.getMat();
    setTrainData(START_AUTO_STEP, samplesMat, 0, 0, 0, 0);
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
90
    return doTrain(START_AUTO_STEP, logLikelihoods, labels, probs);
91 92
}

93 94 95 96
bool EM::trainE(InputArray samples,
                InputArray _means0,
                InputArray _covs0,
                InputArray _weights0,
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
97
                OutputArray logLikelihoods,
98
                OutputArray labels,
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
99
                OutputArray probs)
100
{
101 102 103 104 105 106 107
    Mat samplesMat = samples.getMat();
    vector<Mat> covs0;
    _covs0.getMatVector(covs0);
    
    Mat means0 = _means0.getMat(), weights0 = _weights0.getMat();

    setTrainData(START_E_STEP, samplesMat, 0, !_means0.empty() ? &means0 : 0,
Maria Dimashova's avatar
Maria Dimashova committed
108
                 !_covs0.empty() ? &covs0 : 0, !_weights0.empty() ? &weights0 : 0);
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
109
    return doTrain(START_E_STEP, logLikelihoods, labels, probs);
110
}
111

112 113
bool EM::trainM(InputArray samples,
                InputArray _probs0,
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
114
                OutputArray logLikelihoods,
115
                OutputArray labels,
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
116
                OutputArray probs)
117 118 119 120 121
{
    Mat samplesMat = samples.getMat();
    Mat probs0 = _probs0.getMat();
    
    setTrainData(START_M_STEP, samplesMat, !_probs0.empty() ? &probs0 : 0, 0, 0, 0);
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
122
    return doTrain(START_M_STEP, logLikelihoods, labels, probs);
123
}
124

125
    
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
126
Vec2d EM::predict(InputArray _sample, OutputArray _probs) const
127 128 129
{
    Mat sample = _sample.getMat();
    CV_Assert(isTrained());
130

131 132
    CV_Assert(!sample.empty());
    if(sample.type() != CV_64FC1)
133
    {
134 135 136
        Mat tmp;
        sample.convertTo(tmp, CV_64FC1);
        sample = tmp;
137
    }
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
138
    sample.reshape(1, 1);
139

140 141
    Mat probs;
    if( _probs.needed() )
142
    {
143 144
        _probs.create(1, nclusters, CV_64FC1);
        probs = _probs.getMat();
145 146
    }

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
147
    return computeProbabilities(sample, !probs.empty() ? &probs : 0);
148 149
}

150
bool EM::isTrained() const
151
{
152
    return !means.empty();
153 154 155
}


156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
static
void checkTrainData(int startStep, const Mat& samples,
                    int nclusters, int covMatType, const Mat* probs, const Mat* means,
                    const 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 == EM::START_AUTO_STEP ||
              startStep == EM::START_E_STEP ||
              startStep == EM::START_M_STEP);
    CV_Assert(covMatType == EM::COV_MAT_GENERIC ||
              covMatType == EM::COV_MAT_DIAGONAL ||
              covMatType == EM::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)
197
    {
198 199 200 201 202 203
        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));
        }
204 205
    }

206
    if(startStep == EM::START_E_STEP)
207
    {
208
        CV_Assert(means);
209
    }
210
    else if(startStep == EM::START_M_STEP)
211
    {
212
        CV_Assert(probs);
213 214 215
    }
}

216 217
static
void preprocessSampleData(const Mat& src, Mat& dst, int dstType, bool isAlwaysClone)
218
{
219 220 221 222 223
    if(src.type() == dstType && !isAlwaysClone)
        dst = src;
    else
        src.convertTo(dst, dstType);
}
224

225 226 227 228
static
void preprocessProbability(Mat& probs)
{
    max(probs, 0., probs);
229

230 231 232 233
    const double uniformProbability = (double)(1./probs.cols);
    for(int y = 0; y < probs.rows; y++)
    {
        Mat sampleProbs = probs.row(y);
234

235 236 237 238 239 240 241
        double maxVal = 0;
        minMaxLoc(sampleProbs, 0, &maxVal);
        if(maxVal < FLT_EPSILON)
            sampleProbs.setTo(uniformProbability);
        else
            normalize(sampleProbs, sampleProbs, 1, 0, NORM_L1);
    }
242
}
243

244 245 246 247 248
void EM::setTrainData(int startStep, const Mat& samples,
                      const Mat* probs0,
                      const Mat* means0,
                      const vector<Mat>* covs0,
                      const Mat* weights0)
249
{
250
    clear();
251

252
    checkTrainData(startStep, samples, nclusters, covMatType, probs0, means0, covs0, weights0);
253

254 255 256
    bool isKMeansInit = (startStep == EM::START_AUTO_STEP) || (startStep == EM::START_E_STEP && (covs0 == 0 || weights0 == 0));
    // Set checked data
    preprocessSampleData(samples, trainSamples, isKMeansInit ? CV_32FC1 : CV_64FC1, false);
257

258 259
    // set probs
    if(probs0 && startStep == EM::START_M_STEP)
260
    {
261 262
        preprocessSampleData(*probs0, trainProbs, CV_64FC1, true);
        preprocessProbability(trainProbs);
263 264
    }

265 266
    // set weights
    if(weights0 && (startStep == EM::START_E_STEP && covs0))
267
    {
268 269 270
        weights0->convertTo(weights, CV_64FC1);
        weights.reshape(1,1);
        preprocessProbability(weights);
271 272
    }

273 274 275
    // set means
    if(means0 && (startStep == EM::START_E_STEP/* || startStep == EM::START_AUTO_STEP*/))
        means0->convertTo(means, isKMeansInit ? CV_32FC1 : CV_64FC1);
276

277 278
    // set covs
    if(covs0 && (startStep == EM::START_E_STEP && weights0))
279
    {
280 281 282
        covs.resize(nclusters);
        for(size_t i = 0; i < covs0->size(); i++)
            (*covs0)[i].convertTo(covs[i], CV_64FC1);
283 284 285
    }
}

286
void EM::decomposeCovs()
287
{
288 289 290 291 292 293 294 295
    CV_Assert(!covs.empty());
    covsEigenValues.resize(nclusters);
    if(covMatType == EM::COV_MAT_GENERIC)
        covsRotateMats.resize(nclusters);
    invCovsEigenValues.resize(nclusters);
    for(int clusterIndex = 0; clusterIndex < nclusters; clusterIndex++)
    {
        CV_Assert(!covs[clusterIndex].empty());
296

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

299
        if(covMatType == EM::COV_MAT_SPHERICAL)
300
        {
301 302
            double maxSingularVal = svd.w.at<double>(0);
            covsEigenValues[clusterIndex] = Mat(1, 1, CV_64FC1, Scalar(maxSingularVal));
303
        }
304
        else if(covMatType == EM::COV_MAT_DIAGONAL)
305
        {
306
            covsEigenValues[clusterIndex] = svd.w;
307
        }
308 309 310 311 312 313 314
        else //EM::COV_MAT_GENERIC
        {
            covsEigenValues[clusterIndex] = svd.w;
            covsRotateMats[clusterIndex] = svd.u;
        }
        max(covsEigenValues[clusterIndex], minEigenValue, covsEigenValues[clusterIndex]);
        invCovsEigenValues[clusterIndex] = 1./covsEigenValues[clusterIndex];
315 316
    }
}
317

318
void EM::clusterTrainSamples()
319
{
320
    int nsamples = trainSamples.rows;
321

322
    // Cluster samples, compute/update means
323

324 325 326 327 328 329 330 331 332 333 334 335 336
    // 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;
    }
337

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

341 342 343 344 345 346 347 348 349
    // 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);
350

351 352 353 354
    // Compute weights and covs
    weights = Mat(1, nclusters, CV_64FC1, Scalar(0));
    covs.resize(nclusters);
    for(int clusterIndex = 0; clusterIndex < nclusters; clusterIndex++)
355
    {
356 357
        Mat clusterSamples;
        for(int sampleIndex = 0; sampleIndex < nsamples; sampleIndex++)
358
        {
359
            if(labels.at<int>(sampleIndex) == clusterIndex)
360
            {
361 362
                const Mat sample = trainSamples.row(sampleIndex);
                clusterSamples.push_back(sample);
363 364
            }
        }
365
        CV_Assert(!clusterSamples.empty());
366

367 368 369
        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);
370 371
    }

372
    decomposeCovs();
373 374
}

375
void EM::computeLogWeightDivDet()
376
{
377
    CV_Assert(!covsEigenValues.empty());
378

379 380 381
    Mat logWeights;
    cv::max(weights, DBL_MIN, weights);
    log(weights, logWeights);
382

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

386
    for(int clusterIndex = 0; clusterIndex < nclusters; clusterIndex++)
387
    {
388
        double logDetCov = 0.;
Maria Dimashova's avatar
Maria Dimashova committed
389 390
        const int evalCount = covsEigenValues[clusterIndex].total();
        for(int di = 0; di < evalCount; di++)
391
            logDetCov += std::log(covsEigenValues[clusterIndex].at<double>(covMatType != EM::COV_MAT_SPHERICAL ? di : 0));
392

393 394 395
        logWeightDivDet.at<double>(clusterIndex) = logWeights.at<double>(clusterIndex) - 0.5 * logDetCov;
    }
}
396

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
397
bool EM::doTrain(int startStep, OutputArray logLikelihoods, OutputArray labels, OutputArray probs)
398 399 400 401
{
    int dim = trainSamples.cols;
    // Precompute the empty initial train data in the cases of EM::START_E_STEP and START_AUTO_STEP
    if(startStep != EM::START_M_STEP)
402
    {
403
        if(covs.empty())
404
        {
405 406
            CV_Assert(weights.empty());
            clusterTrainSamples();
407 408 409
        }
    }

410 411 412 413 414
    if(!covs.empty() && covsEigenValues.empty() )
    {
        CV_Assert(invCovsEigenValues.empty());
        decomposeCovs();
    }
415

416 417
    if(startStep == EM::START_M_STEP)
        mStep();
418

419 420 421 422 423
    double trainLogLikelihood, prevTrainLogLikelihood = 0.;
    for(int iter = 0; ; iter++)
    {
        eStep();
        trainLogLikelihood = sum(trainLogLikelihoods)[0];
424

425 426
        if(iter >= maxIters - 1)
            break;
427

428 429 430 431 432
        double trainLogLikelihoodDelta = trainLogLikelihood - prevTrainLogLikelihood;
        if( iter != 0 &&
            (trainLogLikelihoodDelta < -DBL_EPSILON ||
             trainLogLikelihoodDelta < epsilon * std::fabs(trainLogLikelihood)))
            break;
433

434
        mStep();
435

436
        prevTrainLogLikelihood = trainLogLikelihood;
437
    }
438 439

    if( trainLogLikelihood <= -DBL_MAX/10000. )
440
    {
441 442
        clear();
        return false;
443 444
    }

445 446 447
    // postprocess covs
    covs.resize(nclusters);
    for(int clusterIndex = 0; clusterIndex < nclusters; clusterIndex++)
448
    {
449
        if(covMatType == EM::COV_MAT_SPHERICAL)
450
        {
451 452
            covs[clusterIndex].create(dim, dim, CV_64FC1);
            setIdentity(covs[clusterIndex], Scalar(covsEigenValues[clusterIndex].at<double>(0)));
453
        }
454
        else if(covMatType == EM::COV_MAT_DIAGONAL)
455
        {
456
            covs[clusterIndex] = Mat::diag(covsEigenValues[clusterIndex]);
457 458
        }
    }
459 460 461 462 463 464 465 466 467 468 469 470 471 472
    
    if(labels.needed())
        trainLabels.copyTo(labels);
    if(probs.needed())
        trainProbs.copyTo(probs);
    if(logLikelihoods.needed())
        trainLogLikelihoods.copyTo(logLikelihoods);
    
    trainSamples.release();
    trainProbs.release();
    trainLabels.release();
    trainLogLikelihoods.release();

    return true;
473 474
}

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
475
Vec2d EM::computeProbabilities(const Mat& sample, Mat* probs) const
476
{
477 478 479 480 481
    // 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
482

483 484 485 486
    CV_Assert(!means.empty());
    CV_Assert(sample.type() == CV_64FC1);
    CV_Assert(sample.rows == 1);
    CV_Assert(sample.cols == means.cols);
487

488
    int dim = sample.cols;
489

490
    Mat L(1, nclusters, CV_64FC1);
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
491
    int label = 0;
492
    for(int clusterIndex = 0; clusterIndex < nclusters; clusterIndex++)
493
    {
494
        const Mat centeredSample = sample - means.row(clusterIndex);
495

496 497
        Mat rotatedCenteredSample = covMatType != EM::COV_MAT_GENERIC ?
                centeredSample : centeredSample * covsRotateMats[clusterIndex];
498

499 500
        double Lval = 0;
        for(int di = 0; di < dim; di++)
501
        {
502 503 504
            double w = invCovsEigenValues[clusterIndex].at<double>(covMatType != EM::COV_MAT_SPHERICAL ? di : 0);
            double val = rotatedCenteredSample.at<double>(di);
            Lval += w * val * val;
505
        }
506
        CV_DbgAssert(!logWeightDivDet.empty());
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
507
        L.at<double>(clusterIndex) = logWeightDivDet.at<double>(clusterIndex) - 0.5 * Lval;
508

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
509
        if(L.at<double>(clusterIndex) > L.at<double>(label))
510 511
            label = clusterIndex;
    }
512

513 514 515 516 517
    double maxLVal = L.at<double>(label);
    Mat expL_Lmax = L; // exp(L_ij - L_iq)
    for(int i = 0; i < L.cols; i++)
        expL_Lmax.at<double>(i) = std::exp(L.at<double>(i) - maxLVal);
    double expDiffSum = sum(expL_Lmax)[0]; // sum_j(exp(L_ij - L_iq))
518

519 520 521 522 523 524
    if(probs)
    {
        probs->create(1, nclusters, CV_64FC1);
        double factor = 1./expDiffSum;
        expL_Lmax *= factor;
        expL_Lmax.copyTo(*probs);
525 526
    }

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
527 528 529 530 531
    Vec2d res;
    res[0] = std::log(expDiffSum)  + maxLVal - 0.5 * dim * CV_LOG2PI;
    res[1] = label;

    return res;
532 533
}

534
void EM::eStep()
535
{
536 537 538 539
    // Compute probs_ik from means_k, covs_k and weights_k.
    trainProbs.create(trainSamples.rows, nclusters, CV_64FC1);
    trainLabels.create(trainSamples.rows, 1, CV_32SC1);
    trainLogLikelihoods.create(trainSamples.rows, 1, CV_64FC1);
540

541
    computeLogWeightDivDet();
542

543 544
    CV_DbgAssert(trainSamples.type() == CV_64FC1);
    CV_DbgAssert(means.type() == CV_64FC1);
545

546
    for(int sampleIndex = 0; sampleIndex < trainSamples.rows; sampleIndex++)
547
    {
548
        Mat sampleProbs = trainProbs.row(sampleIndex);
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
549 550 551
        Vec2d res = computeProbabilities(trainSamples.row(sampleIndex), &sampleProbs);
        trainLogLikelihoods.at<double>(sampleIndex) = res[0];
        trainLabels.at<int>(sampleIndex) = static_cast<int>(res[1]);
552
    }
553
}
554

555 556
void EM::mStep()
{
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
557 558
    // Update means_k, covs_k and weights_k from probs_ik
    int dim = trainSamples.cols;
559

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
560 561 562
    // Update weights
    // not normalized first
    reduce(trainProbs, weights, 0, CV_REDUCE_SUM);
563

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
564 565 566
    // Update means
    means.create(nclusters, dim, CV_64FC1);
    means = Scalar(0);
567

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
568 569 570 571 572 573 574
    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;
575

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
576
        if(weights.at<double>(clusterIndex) < minWeight)
577
        {
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
578 579
            minWeight = weights.at<double>(clusterIndex);
            minWeightClusterIndex = clusterIndex;
580 581
        }

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
        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);
    }

    // Update covsEigenValues and invCovsEigenValues
    covs.resize(nclusters);
    covsEigenValues.resize(nclusters);
    if(covMatType == EM::COV_MAT_GENERIC)
        covsRotateMats.resize(nclusters);
    invCovsEigenValues.resize(nclusters);
    for(int clusterIndex = 0; clusterIndex < nclusters; clusterIndex++)
    {
        if(weights.at<double>(clusterIndex) <= minPosWeight)
            continue;

        if(covMatType != EM::COV_MAT_SPHERICAL)
            covsEigenValues[clusterIndex].create(1, dim, CV_64FC1);
        else
            covsEigenValues[clusterIndex].create(1, 1, CV_64FC1);

604
        if(covMatType == EM::COV_MAT_GENERIC)
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
605
            covs[clusterIndex].create(dim, dim, CV_64FC1);
606

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
607 608
        Mat clusterCov = covMatType != EM::COV_MAT_GENERIC ?
            covsEigenValues[clusterIndex] : covs[clusterIndex];
609

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
610
        clusterCov = Scalar(0);
611

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
612 613 614 615
        Mat centeredSample;
        for(int sampleIndex = 0; sampleIndex < trainSamples.rows; sampleIndex++)
        {
            centeredSample = trainSamples.row(sampleIndex) - means.row(clusterIndex);
616

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
617 618 619
            if(covMatType == EM::COV_MAT_GENERIC)
                clusterCov += trainProbs.at<double>(sampleIndex, clusterIndex) * centeredSample.t() * centeredSample;
            else
620
            {
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
621 622
                double p = trainProbs.at<double>(sampleIndex, clusterIndex);
                for(int di = 0; di < dim; di++ )
623
                {
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
624 625
                    double val = centeredSample.at<double>(di);
                    clusterCov.at<double>(covMatType != EM::COV_MAT_SPHERICAL ? di : 0) += p*val*val;
626
                }
627
            }
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
628
        }
629

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
630 631
        if(covMatType == EM::COV_MAT_SPHERICAL)
            clusterCov /= dim;
632

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
633
        clusterCov /= weights.at<double>(clusterIndex);
634

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
635 636 637 638 639 640 641
        // Update covsRotateMats for EM::COV_MAT_GENERIC only
        if(covMatType == EM::COV_MAT_GENERIC)
        {
            SVD svd(covs[clusterIndex], SVD::MODIFY_A + SVD::FULL_UV);
            covsEigenValues[clusterIndex] = svd.w;
            covsRotateMats[clusterIndex] = svd.u;
        }
642

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
643
        max(covsEigenValues[clusterIndex], minEigenValue, covsEigenValues[clusterIndex]);
644

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
645 646 647
        // update invCovsEigenValues
        invCovsEigenValues[clusterIndex] = 1./covsEigenValues[clusterIndex];
    }
648

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
649 650 651 652 653 654 655 656 657 658 659 660
    for(int clusterIndex = 0; clusterIndex < nclusters; clusterIndex++)
    {
        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 == EM::COV_MAT_GENERIC)
                covsRotateMats[minWeightClusterIndex].copyTo(covsRotateMats[clusterIndex]);
            invCovsEigenValues[minWeightClusterIndex].copyTo(invCovsEigenValues[clusterIndex]);
        }
661
    }
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
662 663 664

    // Normalize weights
    weights /= trainSamples.rows;
665 666
}

667
void EM::read(const FileNode& fn)
668
{
669
    Algorithm::read(fn);
670

671 672
    decomposeCovs();
    computeLogWeightDivDet();
673 674
}

675
} // namespace cv
676 677

/* End of file. */