stump.cpp 6.93 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
/*

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.


                          License Agreement
               For Open Source Computer Vision Library
                       (3-clause BSD License)

Copyright (C) 2013, OpenCV Foundation, 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:

  * Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

  * Redistributions 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.

  * Neither the names of the copyright holders nor the names of the contributors
    may 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 copyright holders 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 if advised of the possibility of such damage.

*/

#include "precomp.hpp"

44 45
namespace cv
{
46
namespace xobjdetect
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
{

/* Cumulative sum by rows */
static void cumsum(const Mat_<float>& src, Mat_<float> dst)
{
    CV_Assert(src.cols > 0);

    for( int row = 0; row < src.rows; ++row )
    {
        dst(row, 0) = src(row, 0);
        for( int col = 1; col < src.cols; ++col )
        {
            dst(row, col) = dst(row, col - 1) + src(row, col);
        }
    }
}

manuele's avatar
manuele committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
//fast log implementation. A bit less accurate but ~5x faster
inline float fast_log2 (float val)
{
   int * const    exp_ptr = reinterpret_cast <int *> (&val);
   int            x = *exp_ptr;
   const int      log_2 = ((x >> 23) & 255) - 128;
   x &= ~(255 << 23);
   x += 127 << 23;
   *exp_ptr = x;

   val = ((-1.0f/3) * val + 2) * val - 2.0f/3;   // (1)

   return (val + log_2);
} 

inline float fast_log (const float &val)
{
   return (fast_log2 (val) * 0.69314718f);
}

int Stump::train(const Mat& data, const Mat& labels, const Mat& weights, const std::vector<int>& visited_features, bool use_fast_log)
85 86 87
{
    CV_Assert(labels.rows == 1 && labels.cols == data.cols);
    CV_Assert(weights.rows == 1 && weights.cols == data.cols);
Vlad Shakhuro's avatar
Vlad Shakhuro committed
88
    CV_Assert(data.cols > 1);
89 90 91
    /* Assert that data and labels have int type */
    /* Assert that weights have float type */

Vlad Shakhuro's avatar
Vlad Shakhuro committed
92 93 94
    Mat_<int> d = Mat_<int>::zeros(1, data.cols);
    const Mat_<int>& l = labels;
    const Mat_<float>& w = weights;
95

Vlad Shakhuro's avatar
Vlad Shakhuro committed
96
    Mat_<int> indices(1, l.cols);
97

Vlad Shakhuro's avatar
Vlad Shakhuro committed
98 99 100
    Mat_<int> sorted_d(1, data.cols);
    Mat_<int> sorted_l(1, l.cols);
    Mat_<float> sorted_w(1, w.cols);
101

Vlad Shakhuro's avatar
Vlad Shakhuro committed
102 103 104 105 106 107 108 109 110 111 112 113 114 115

    Mat_<float> pos_c_w = Mat_<float>::zeros(1, w.cols);
    Mat_<float> neg_c_w = Mat_<float>::zeros(1, w.cols);


    float min_err = FLT_MAX;
    int min_row = -1;
    int min_thr = -1;
    int min_pol = -1;
    float min_pos = 1;
    float min_neg = -1;
    float eps = 1.0f / (4 * l.cols);

    /* For every feature */
116 117
    for( int row = 0; row < data.rows; ++row )
    {
manuele's avatar
manuele committed
118 119 120 121 122
        if(std::find(visited_features.begin(), visited_features.end(), row) != visited_features.end()) {
              //feature discarded
              continue;
        }
        data.row(row).copyTo(d.row(0));
123

Vlad Shakhuro's avatar
Vlad Shakhuro committed
124
        sortIdx(d, indices, cv::SORT_EVERY_ROW | cv::SORT_ASCENDING);
125

Vlad Shakhuro's avatar
Vlad Shakhuro committed
126 127 128 129 130 131 132
        for( int col = 0; col < indices.cols; ++col )
        {
            int ind = indices(0, col);
            sorted_d(0, col) = d(0, ind);
            sorted_l(0, col) = l(0, ind);
            sorted_w(0, col) = w(0, ind);
        }
133

Vlad Shakhuro's avatar
Vlad Shakhuro committed
134 135 136 137 138 139 140 141 142 143
        Mat_<float> pos_w = Mat_<float>::zeros(1, w.cols);
        Mat_<float> neg_w = Mat_<float>::zeros(1, w.cols);
        for( int col = 0; col < d.cols; ++col )
        {
            float weight = sorted_w(0, col);
            if( sorted_l(0, col) == +1)
                pos_w(0, col) = weight;
            else
                neg_w(0, col) = weight;
        }
144

Vlad Shakhuro's avatar
Vlad Shakhuro committed
145 146
        cumsum(pos_w, pos_c_w);
        cumsum(neg_w, neg_c_w);
147

Vlad Shakhuro's avatar
Vlad Shakhuro committed
148 149
        float pos_total_w = pos_c_w(0, w.cols - 1);
        float neg_total_w = neg_c_w(0, w.cols - 1);
150

Vlad Shakhuro's avatar
Vlad Shakhuro committed
151
        for( int col = 0; col < w.cols - 1; ++col )
152 153
        {
            float err, h_pos, h_neg;
Vlad Shakhuro's avatar
Vlad Shakhuro committed
154 155
            float pos_wrong, pos_right;
            float neg_wrong, neg_right;
156

Vlad Shakhuro's avatar
Vlad Shakhuro committed
157
            /* Direct polarity */
158

Vlad Shakhuro's avatar
Vlad Shakhuro committed
159 160
            pos_wrong = pos_c_w(0, col);
            pos_right = pos_total_w - pos_wrong;
161

Vlad Shakhuro's avatar
Vlad Shakhuro committed
162 163
            neg_right = neg_c_w(0, col);
            neg_wrong = neg_total_w - neg_right;
164 165 166

            err = sqrt(pos_right * neg_wrong) + sqrt(pos_wrong * neg_right);

manuele's avatar
manuele committed
167 168 169 170 171 172 173 174 175 176
            if(use_fast_log)
            {
              h_pos = .5f * fast_log((pos_right + eps) / (pos_wrong + eps));
              h_neg = .5f * fast_log((neg_wrong + eps) / (neg_right + eps));
            }
            else
            {
              h_pos = .5f * log((pos_right + eps) / (pos_wrong + eps));
              h_neg = .5f * log((neg_wrong + eps) / (neg_right + eps));
            }
Vlad Shakhuro's avatar
Vlad Shakhuro committed
177

178 179 180 181
            if( err < min_err )
            {
                min_err = err;
                min_row = row;
Vlad Shakhuro's avatar
Vlad Shakhuro committed
182 183 184 185
                min_thr = (sorted_d(0, col) + sorted_d(0, col + 1)) / 2;
                min_pol = +1;
                min_pos = h_pos;
                min_neg = h_neg;
186 187
            }

Vlad Shakhuro's avatar
Vlad Shakhuro committed
188 189
            /* Opposite polarity */

190 191 192 193 194 195 196 197 198
            swap(pos_right, pos_wrong);
            swap(neg_right, neg_wrong);

            err = sqrt(pos_right * neg_wrong) + sqrt(pos_wrong * neg_right);

            if( err < min_err )
            {
                min_err = err;
                min_row = row;
Vlad Shakhuro's avatar
Vlad Shakhuro committed
199 200 201 202
                min_thr = (sorted_d(0, col) + sorted_d(0, col + 1)) / 2;
                min_pol = -1;
                min_pos = -h_pos;
                min_neg = -h_neg;
203
            }
Vlad Shakhuro's avatar
Vlad Shakhuro committed
204

205 206 207
        }
    }

Vlad Shakhuro's avatar
Vlad Shakhuro committed
208 209 210 211
    threshold_ = min_thr;
    polarity_ = min_pol;
    pos_value_ = min_pos;
    neg_value_ = min_neg;
212 213 214 215

    return min_row;
}

216
float Stump::predict(int value) const
217 218 219 220
{
    return polarity_ * (value - threshold_) > 0 ? pos_value_ : neg_value_;
}

Vlad Shakhuro's avatar
Vlad Shakhuro committed
221 222 223 224 225 226 227 228 229 230 231 232 233 234

void read(const FileNode& node, Stump& s, const Stump& default_value)
{
    if( node.empty() )
        s = default_value;
    else
        s.read(node);
}

void write(FileStorage& fs, String&, const Stump& s)
{
    s.write(fs);
}

235
} /* namespace xobjdetect */
236
} /* namespace cv */