1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
5 // By downloading, copying, installing or using the software you agree to this license.
6 // If you do not agree to this license, do not download, install,
7 // copy or use the software.
10 // Intel License Agreement
12 // Copyright (C) 2000, Intel Corporation, all rights reserved.
13 // Third party copyrights are property of their respective owners.
15 // Redistribution and use in source and binary forms, with or without modification,
16 // are permitted provided that the following conditions are met:
18 // * Redistribution's of source code must retain the above copyright notice,
19 // this list of conditions and the following disclaimer.
21 // * Redistribution's in binary form must reproduce the above copyright notice,
22 // this list of conditions and the following disclaimer in the documentation
23 // and/or other materials provided with the distribution.
25 // * The name of Intel Corporation may not be used to endorse or promote products
26 // derived from this software without specific prior written permission.
28 // This software is provided by the copyright holders and contributors "as is" and
29 // any express or implied warranties, including, but not limited to, the implied
30 // warranties of merchantability and fitness for a particular purpose are disclaimed.
31 // In no event shall the Intel Corporation or contributors be liable for any direct,
32 // indirect, incidental, special, exemplary, or consequential damages
33 // (including, but not limited to, procurement of substitute goods or services;
34 // loss of use, data, or profits; or business interruption) however caused
35 // and on any theory of liability, whether in contract, strict liability,
36 // or tort (including negligence or otherwise) arising in any way out of
37 // the use of this software, even if advised of the possibility of such damage.
41 #include "precomp.hpp"
43 namespace cv { namespace ml {
45 ParamGrid::ParamGrid() { minVal = maxVal = 0.; logStep = 1; }
46 ParamGrid::ParamGrid(double _minVal, double _maxVal, double _logStep)
49 minVal = std::min(_minVal, _maxVal);
50 maxVal = std::max(_minVal, _maxVal);
51 logStep = std::max(_logStep, 1.);
54 Ptr<ParamGrid> ParamGrid::create(double minval, double maxval, double logstep) {
55 return makePtr<ParamGrid>(minval, maxval, logstep);
58 bool StatModel::empty() const { return !isTrained(); }
60 int StatModel::getVarCount() const { return 0; }
62 bool StatModel::train( const Ptr<TrainData>&, int )
65 CV_Error(CV_StsNotImplemented, "");
69 bool StatModel::train( InputArray samples, int layout, InputArray responses )
72 return train(TrainData::create(samples, layout, responses));
75 class ParallelCalcError : public ParallelLoopBody
78 const Ptr<TrainData>& data;
82 vector<double> &errStrip;
84 ParallelCalcError(const Ptr<TrainData>& d, bool &t, Mat &_r,const StatModel &w, vector<double> &e) :
92 virtual void operator()(const Range& range) const
94 int idxErr = range.start;
95 CV_TRACE_FUNCTION_SKIP_NESTED();
96 Mat samples = data->getSamples();
97 int layout = data->getLayout();
98 Mat sidx = testerr ? data->getTestSampleIdx() : data->getTrainSampleIdx();
99 const int* sidx_ptr = sidx.ptr<int>();
100 bool isclassifier = s.isClassifier();
101 Mat responses = data->getResponses();
102 int responses_type = responses.type();
106 for (int i = range.start; i < range.end; i++)
108 int si = sidx_ptr ? sidx_ptr[i] : i;
109 Mat sample = layout == ROW_SAMPLE ? samples.row(si) : samples.col(si);
110 float val = s.predict(sample);
111 float val0 = (responses_type == CV_32S) ? (float)responses.at<int>(si) : responses.at<float>(si);
114 err += fabs(val - val0) > FLT_EPSILON;
116 err += (val - val0)*(val - val0);
118 resp.at<float>(i) = val;
122 errStrip[idxErr]=err ;
125 ParallelCalcError& operator=(const ParallelCalcError &) {
131 float StatModel::calcError(const Ptr<TrainData>& data, bool testerr, OutputArray _resp) const
133 CV_TRACE_FUNCTION_SKIP_NESTED();
134 Mat samples = data->getSamples();
135 Mat sidx = testerr ? data->getTestSampleIdx() : data->getTrainSampleIdx();
136 int n = (int)sidx.total();
137 bool isclassifier = isClassifier();
138 Mat responses = data->getResponses();
141 n = data->getNSamples();
148 resp.create(n, 1, CV_32F);
151 vector<double> errStrip(n,0.0);
152 ParallelCalcError x(data, testerr, resp, *this,errStrip);
154 parallel_for_(Range(0,n),x);
156 for (size_t i = 0; i < errStrip.size(); i++)
162 return (float)(err / n * (isclassifier ? 100 : 1));
165 /* Calculates upper triangular matrix S, where A is a symmetrical matrix A=S'*S */
166 static void Cholesky( const Mat& A, Mat& S )
169 CV_Assert(A.type() == CV_32F);
172 cv::Cholesky ((float*)S.ptr(),S.step, S.rows,NULL, 0, 0);
174 for (int i=1;i<S.rows;i++)
175 for (int j=0;j<i;j++)
179 /* Generates <sample> from multivariate normal distribution, where <mean> - is an
180 average row vector, <cov> - symmetric covariation matrix */
181 void randMVNormal( InputArray _mean, InputArray _cov, int nsamples, OutputArray _samples )
184 // check mean vector and covariance matrix
185 Mat mean = _mean.getMat(), cov = _cov.getMat();
186 int dim = (int)mean.total(); // dimensionality
187 CV_Assert(mean.rows == 1 || mean.cols == 1);
188 CV_Assert(cov.rows == dim && cov.cols == dim);
189 mean = mean.reshape(1,1); // ensure a row vector
191 // generate n-samples of the same dimension, from ~N(0,1)
192 _samples.create(nsamples, dim, CV_32F);
193 Mat samples = _samples.getMat();
194 randn(samples, Scalar::all(0), Scalar::all(1));
196 // decompose covariance using Cholesky: cov = U'*U
197 // (cov must be square, symmetric, and positive semi-definite matrix)
199 Cholesky(cov, utmat);
201 // transform random numbers using specified mean and covariance
202 for( int i = 0; i < nsamples; i++ )
204 Mat sample = samples.row(i);
205 sample = sample * utmat + mean;