em.cpp 7.52 KB
Newer Older
1
/*M///////////////////////////////////////////////////////////////////////////////////////
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
//
//  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*/
41 42 43 44 45 46

#include "precomp.hpp"

using namespace cv;

CvEMParams::CvEMParams() : nclusters(10), cov_mat_type(CvEM::COV_MAT_DIAGONAL),
47
    start_step(CvEM::START_AUTO_STEP), probs(0), weights(0), means(0), covs(0)
48 49 50 51 52
{
    term_crit=cvTermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, FLT_EPSILON );
}

CvEMParams::CvEMParams( int _nclusters, int _cov_mat_type, int _start_step,
53 54 55 56
                        CvTermCriteria _term_crit, const CvMat* _probs,
                        const CvMat* _weights, const CvMat* _means, const CvMat** _covs ) :
                        nclusters(_nclusters), cov_mat_type(_cov_mat_type), start_step(_start_step),
                        probs(_probs), weights(_weights), means(_means), covs(_covs), term_crit(_term_crit)
57 58
{}

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
59
CvEM::CvEM() : logLikelihood(DBL_MAX)
60 61 62 63
{
}

CvEM::CvEM( const CvMat* samples, const CvMat* sample_idx,
64
            CvEMParams params, CvMat* labels ) : logLikelihood(DBL_MAX)
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
{
    train(samples, sample_idx, params, labels);
}

CvEM::~CvEM()
{
    clear();
}

void CvEM::clear()
{
    emObj.clear();
}

void CvEM::read( CvFileStorage* fs, CvFileNode* node )
{
    FileNode fn(fs, node);
    emObj.read(fn);
    set_mat_hdrs();
}

void CvEM::write( CvFileStorage* _fs, const char* name ) const
{
    FileStorage fs = _fs;
    if(name)
        fs << name << "{";
    emObj.write(fs);
    if(name)
        fs << "}";
    fs.fs.obj = 0;
}

double CvEM::calcLikelihood( const Mat &input_sample ) const
{
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
99
    return emObj.predict(input_sample)[0];
100 101 102 103 104 105
}

float
CvEM::predict( const CvMat* _sample, CvMat* _probs ) const
{
    Mat prbs0 = cvarrToMat(_probs), prbs = prbs0, sample = cvarrToMat(_sample);
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
106
    int cls = static_cast<int>(emObj.predict(sample, _probs ? _OutputArray(prbs) : cv::noArray())[1]);
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
    if(_probs)
    {
        if( prbs.data != prbs0.data )
        {
            CV_Assert( prbs.size == prbs0.size );
            prbs.convertTo(prbs0, prbs0.type());
        }
    }
    return (float)cls;
}

void CvEM::set_mat_hdrs()
{
    if(emObj.isTrained())
    {
        meansHdr = emObj.get<Mat>("means");
        int K = emObj.get<int>("nclusters");
        covsHdrs.resize(K);
        covsPtrs.resize(K);
126
        const std::vector<Mat>& covs = emObj.get<std::vector<Mat> >("covs");
127 128 129 130 131 132 133 134 135 136 137 138 139
        for(size_t i = 0; i < covsHdrs.size(); i++)
        {
            covsHdrs[i] = covs[i];
            covsPtrs[i] = &covsHdrs[i];
        }
        weightsHdr = emObj.get<Mat>("weights");
        probsHdr = probs;
    }
}

static
void init_params(const CvEMParams& src,
                 Mat& prbs, Mat& weights,
140
                 Mat& means, std::vector<Mat>& covsHdrs)
141 142 143 144
{
    prbs = src.probs;
    weights = src.weights;
    means = src.means;
145

146 147 148 149 150 151 152 153 154
    if(src.covs)
    {
        covsHdrs.resize(src.nclusters);
        for(size_t i = 0; i < covsHdrs.size(); i++)
            covsHdrs[i] = src.covs[i];
    }
}

bool CvEM::train( const CvMat* _samples, const CvMat* _sample_idx,
155
                  CvEMParams _params, CvMat* _labels )
156 157 158 159 160
{
    CV_Assert(_sample_idx == 0);
    Mat samples = cvarrToMat(_samples), labels0, labels;
    if( _labels )
        labels0 = labels = cvarrToMat(_labels);
161

162 163
    bool isOk = train(samples, Mat(), _params, _labels ? &labels : 0);
    CV_Assert( labels0.data == labels.data );
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 197 198 199 200 201 202 203
    return isOk;
}

int CvEM::get_nclusters() const
{
    return emObj.get<int>("nclusters");
}

const CvMat* CvEM::get_means() const
{
    return emObj.isTrained() ? &meansHdr : 0;
}

const CvMat** CvEM::get_covs() const
{
    return emObj.isTrained() ? (const CvMat**)&covsPtrs[0] : 0;
}

const CvMat* CvEM::get_weights() const
{
    return emObj.isTrained() ? &weightsHdr : 0;
}

const CvMat* CvEM::get_probs() const
{
    return emObj.isTrained() ? &probsHdr : 0;
}

using namespace cv;

CvEM::CvEM( const Mat& samples, const Mat& sample_idx, CvEMParams params )
{
    train(samples, sample_idx, params, 0);
}

bool CvEM::train( const Mat& _samples, const Mat& _sample_idx,
                 CvEMParams _params, Mat* _labels )
{
    CV_Assert(_sample_idx.empty());
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
204
    Mat prbs, weights, means, logLikelihoods;
205 206
    std::vector<Mat> covshdrs;
    init_params(_params, prbs, weights, means, covshdrs);
207

208 209 210
    emObj = EM(_params.nclusters, _params.cov_mat_type, _params.term_crit);
    bool isOk = false;
    if( _params.start_step == EM::START_AUTO_STEP )
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
211 212
        isOk = emObj.train(_samples,
                           logLikelihoods, _labels ? _OutputArray(*_labels) : cv::noArray(), probs);
213
    else if( _params.start_step == EM::START_E_STEP )
214
        isOk = emObj.trainE(_samples, means, covshdrs, weights,
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
215
                            logLikelihoods, _labels ? _OutputArray(*_labels) : cv::noArray(), probs);
216 217
    else if( _params.start_step == EM::START_M_STEP )
        isOk = emObj.trainM(_samples, prbs,
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
218
                            logLikelihoods, _labels ? _OutputArray(*_labels) : cv::noArray(), probs);
219 220
    else
        CV_Error(CV_StsBadArg, "Bad start type of EM algorithm");
221

222 223
    if(isOk)
    {
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
224
        logLikelihood = sum(logLikelihoods).val[0];
225 226
        set_mat_hdrs();
    }
227

228 229 230 231 232 233
    return isOk;
}

float
CvEM::predict( const Mat& _sample, Mat* _probs ) const
{
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
234
    return static_cast<float>(emObj.predict(_sample, _probs ? _OutputArray(*_probs) : cv::noArray())[1]);
235 236 237 238 239 240 241 242 243 244 245 246
}

int CvEM::getNClusters() const
{
    return emObj.get<int>("nclusters");
}

Mat CvEM::getMeans() const
{
    return emObj.get<Mat>("means");
}

247
void CvEM::getCovs(std::vector<Mat>& _covs) const
248
{
249
    _covs = emObj.get<std::vector<Mat> >("covs");
250 251 252 253 254 255 256 257 258 259 260 261 262 263
}

Mat CvEM::getWeights() const
{
    return emObj.get<Mat>("weights");
}

Mat CvEM::getProbs() const
{
    return probs;
}


/* End of file. */