Path: blob/master/modules/ml/src/inner_functions.cpp
16337 views
/*M///////////////////////////////////////////////////////////////////////////////////////1//2// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.3//4// By downloading, copying, installing or using the software you agree to this license.5// If you do not agree to this license, do not download, install,6// copy or use the software.7//8//9// Intel License Agreement10//11// Copyright (C) 2000, Intel Corporation, all rights reserved.12// Third party copyrights are property of their respective owners.13//14// Redistribution and use in source and binary forms, with or without modification,15// are permitted provided that the following conditions are met:16//17// * Redistribution's of source code must retain the above copyright notice,18// this list of conditions and the following disclaimer.19//20// * Redistribution's in binary form must reproduce the above copyright notice,21// this list of conditions and the following disclaimer in the documentation22// and/or other materials provided with the distribution.23//24// * The name of Intel Corporation may not be used to endorse or promote products25// derived from this software without specific prior written permission.26//27// This software is provided by the copyright holders and contributors "as is" and28// any express or implied warranties, including, but not limited to, the implied29// warranties of merchantability and fitness for a particular purpose are disclaimed.30// In no event shall the Intel Corporation or contributors be liable for any direct,31// indirect, incidental, special, exemplary, or consequential damages32// (including, but not limited to, procurement of substitute goods or services;33// loss of use, data, or profits; or business interruption) however caused34// and on any theory of liability, whether in contract, strict liability,35// or tort (including negligence or otherwise) arising in any way out of36// the use of this software, even if advised of the possibility of such damage.37//38//M*/3940#include "precomp.hpp"4142namespace cv { namespace ml {4344ParamGrid::ParamGrid() { minVal = maxVal = 0.; logStep = 1; }45ParamGrid::ParamGrid(double _minVal, double _maxVal, double _logStep)46{47CV_TRACE_FUNCTION();48minVal = std::min(_minVal, _maxVal);49maxVal = std::max(_minVal, _maxVal);50logStep = std::max(_logStep, 1.);51}5253Ptr<ParamGrid> ParamGrid::create(double minval, double maxval, double logstep) {54return makePtr<ParamGrid>(minval, maxval, logstep);55}5657bool StatModel::empty() const { return !isTrained(); }5859int StatModel::getVarCount() const { return 0; }6061bool StatModel::train( const Ptr<TrainData>&, int )62{63CV_TRACE_FUNCTION();64CV_Error(CV_StsNotImplemented, "");65return false;66}6768bool StatModel::train( InputArray samples, int layout, InputArray responses )69{70CV_TRACE_FUNCTION();71return train(TrainData::create(samples, layout, responses));72}7374class ParallelCalcError : public ParallelLoopBody75{76private:77const Ptr<TrainData>& data;78bool &testerr;79Mat &resp;80const StatModel &s;81vector<double> &errStrip;82public:83ParallelCalcError(const Ptr<TrainData>& d, bool &t, Mat &_r,const StatModel &w, vector<double> &e) :84data(d),85testerr(t),86resp(_r),87s(w),88errStrip(e)89{90}91virtual void operator()(const Range& range) const CV_OVERRIDE92{93int idxErr = range.start;94CV_TRACE_FUNCTION_SKIP_NESTED();95Mat samples = data->getSamples();96Mat weights=testerr? data->getTestSampleWeights() : data->getTrainSampleWeights();97int layout = data->getLayout();98Mat sidx = testerr ? data->getTestSampleIdx() : data->getTrainSampleIdx();99const int* sidx_ptr = sidx.ptr<int>();100bool isclassifier = s.isClassifier();101Mat responses = data->getResponses();102int responses_type = responses.type();103double err = 0;104105106const float* sw = weights.empty() ? 0 : weights.ptr<float>();107for (int i = range.start; i < range.end; i++)108{109int si = sidx_ptr ? sidx_ptr[i] : i;110double sweight = sw ? static_cast<double>(sw[i]) : 1.;111Mat sample = layout == ROW_SAMPLE ? samples.row(si) : samples.col(si);112float val = s.predict(sample);113float val0 = (responses_type == CV_32S) ? (float)responses.at<int>(si) : responses.at<float>(si);114115if (isclassifier)116err += sweight * fabs(val - val0) > FLT_EPSILON;117else118err += sweight * (val - val0)*(val - val0);119if (!resp.empty())120resp.at<float>(i) = val;121}122123124errStrip[idxErr]=err ;125126};127ParallelCalcError& operator=(const ParallelCalcError &) {128return *this;129};130};131132133float StatModel::calcError(const Ptr<TrainData>& data, bool testerr, OutputArray _resp) const134{135CV_TRACE_FUNCTION_SKIP_NESTED();136Mat samples = data->getSamples();137Mat sidx = testerr ? data->getTestSampleIdx() : data->getTrainSampleIdx();138Mat weights = testerr ? data->getTestSampleWeights() : data->getTrainSampleWeights();139int n = (int)sidx.total();140bool isclassifier = isClassifier();141Mat responses = data->getResponses();142143if (n == 0)144{145n = data->getNSamples();146weights = data->getTrainSampleWeights();147testerr =false;148}149150if (n == 0)151return -FLT_MAX;152153Mat resp;154if (_resp.needed())155resp.create(n, 1, CV_32F);156157double err = 0;158vector<double> errStrip(n,0.0);159ParallelCalcError x(data, testerr, resp, *this,errStrip);160161parallel_for_(Range(0,n),x);162163for (size_t i = 0; i < errStrip.size(); i++)164err += errStrip[i];165float weightSum= weights.empty() ? n: static_cast<float>(sum(weights)(0));166if (_resp.needed())167resp.copyTo(_resp);168169return (float)(err/ weightSum * (isclassifier ? 100 : 1));170}171172/* Calculates upper triangular matrix S, where A is a symmetrical matrix A=S'*S */173static void Cholesky( const Mat& A, Mat& S )174{175CV_TRACE_FUNCTION();176CV_Assert(A.type() == CV_32F);177178S = A.clone();179cv::Cholesky ((float*)S.ptr(),S.step, S.rows,NULL, 0, 0);180S = S.t();181for (int i=1;i<S.rows;i++)182for (int j=0;j<i;j++)183S.at<float>(i,j)=0;184}185186/* Generates <sample> from multivariate normal distribution, where <mean> - is an187average row vector, <cov> - symmetric covariation matrix */188void randMVNormal( InputArray _mean, InputArray _cov, int nsamples, OutputArray _samples )189{190CV_TRACE_FUNCTION();191// check mean vector and covariance matrix192Mat mean = _mean.getMat(), cov = _cov.getMat();193int dim = (int)mean.total(); // dimensionality194CV_Assert(mean.rows == 1 || mean.cols == 1);195CV_Assert(cov.rows == dim && cov.cols == dim);196mean = mean.reshape(1,1); // ensure a row vector197198// generate n-samples of the same dimension, from ~N(0,1)199_samples.create(nsamples, dim, CV_32F);200Mat samples = _samples.getMat();201randn(samples, Scalar::all(0), Scalar::all(1));202203// decompose covariance using Cholesky: cov = U'*U204// (cov must be square, symmetric, and positive semi-definite matrix)205Mat utmat;206Cholesky(cov, utmat);207208// transform random numbers using specified mean and covariance209for( int i = 0; i < nsamples; i++ )210{211Mat sample = samples.row(i);212sample = sample * utmat + mean;213}214}215216}}217218/* End of file */219220221