summaryrefslogtreecommitdiffstats
path: root/ml/dlib/dlib/svm/ranking_tools.h
blob: 3c77b41ae1d7aaf49e9ac007d701b06632ff0252 (plain)
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
// Copyright (C) 2012  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#ifndef DLIB_RANKING_ToOLS_Hh_
#define DLIB_RANKING_ToOLS_Hh_

#include "ranking_tools_abstract.h"

#include "../algs.h"
#include "../matrix.h"
#include <vector>
#include <utility>
#include <algorithm>
#include "sparse_vector.h"
#include "../statistics.h"

namespace dlib
{

// ----------------------------------------------------------------------------------------

    template <
        typename T
        >
    struct ranking_pair
    {
        ranking_pair() {}

        ranking_pair(
            const std::vector<T>& r, 
            const std::vector<T>& nr
        ) :
            relevant(r), nonrelevant(nr) 
        {}

        std::vector<T> relevant;
        std::vector<T> nonrelevant;
    };

    template <
        typename T
        >
    void serialize (
        const ranking_pair<T>& item,
        std::ostream& out
    )
    {
        int version = 1;
        serialize(version, out);
        serialize(item.relevant, out);
        serialize(item.nonrelevant, out);
    }


    template <
        typename T
        >
    void deserialize (
        ranking_pair<T>& item,
        std::istream& in 
    )
    {
        int version = 0;
        deserialize(version, in);
        if (version != 1)
            throw dlib::serialization_error("Wrong version found while deserializing dlib::ranking_pair");

        deserialize(item.relevant, in);
        deserialize(item.nonrelevant, in);
    }

// ----------------------------------------------------------------------------------------

    template <
        typename T
        >
    typename disable_if<is_matrix<T>,bool>::type is_ranking_problem (
        const std::vector<ranking_pair<T> >& samples
    )
    {
        if (samples.size() == 0)
            return false;


        for (unsigned long i = 0; i < samples.size(); ++i)
        {
            if (samples[i].relevant.size() == 0)
                return false;
            if (samples[i].nonrelevant.size() == 0)
                return false;
        }

        return true;
    }

    template <
        typename T
        >
    typename enable_if<is_matrix<T>,bool>::type is_ranking_problem (
        const std::vector<ranking_pair<T> >& samples
    )
    {
        if (samples.size() == 0)
            return false;


        for (unsigned long i = 0; i < samples.size(); ++i)
        {
            if (samples[i].relevant.size() == 0)
                return false;
            if (samples[i].nonrelevant.size() == 0)
                return false;
        }

        // If these are dense vectors then they must all have the same dimensionality.
        const long dims = max_index_plus_one(samples[0].relevant);
        for (unsigned long i = 0; i < samples.size(); ++i)
        {
            for (unsigned long j = 0; j < samples[i].relevant.size(); ++j)
            {
                if (is_vector(samples[i].relevant[j]) == false)
                    return false;

                if (samples[i].relevant[j].size() != dims)
                    return false;
            }
            for (unsigned long j = 0; j < samples[i].nonrelevant.size(); ++j)
            {
                if (is_vector(samples[i].nonrelevant[j]) == false)
                    return false;

                if (samples[i].nonrelevant[j].size() != dims)
                    return false;
            }
        }

        return true;
    }

// ----------------------------------------------------------------------------------------

    template <
        typename T
        >
    unsigned long max_index_plus_one (
        const ranking_pair<T>& item
    )
    {
        return std::max(max_index_plus_one(item.relevant), max_index_plus_one(item.nonrelevant));
    }

    template <
        typename T
        >
    unsigned long max_index_plus_one (
        const std::vector<ranking_pair<T> >& samples
    )
    {
        unsigned long dims = 0;
        for (unsigned long i = 0; i < samples.size(); ++i)
        {
            dims = std::max(dims, max_index_plus_one(samples[i]));
        }
        return dims;
    }

// ----------------------------------------------------------------------------------------

    template <typename T>
    void count_ranking_inversions (
        const std::vector<T>& x,
        const std::vector<T>& y,
        std::vector<unsigned long>& x_count,
        std::vector<unsigned long>& y_count
    )
    {
        x_count.assign(x.size(),0);
        y_count.assign(y.size(),0);

        if (x.size() == 0 || y.size() == 0)
            return;

        std::vector<std::pair<T,unsigned long> > xsort(x.size());
        std::vector<std::pair<T,unsigned long> > ysort(y.size());
        for (unsigned long i = 0; i < x.size(); ++i)
            xsort[i] = std::make_pair(x[i], i);
        for (unsigned long j = 0; j < y.size(); ++j)
            ysort[j] = std::make_pair(y[j], j);

        std::sort(xsort.begin(), xsort.end());
        std::sort(ysort.begin(), ysort.end());


        unsigned long i, j;

        // Do the counting for the x values.
        for (i = 0, j = 0; i < x_count.size(); ++i)
        {
            // Skip past y values that are in the correct order with respect to xsort[i].
            while (j < ysort.size() && ysort[j].first < xsort[i].first) 
                ++j;

            x_count[xsort[i].second] = ysort.size() - j;
        }


        // Now do the counting for the y values.
        for (i = 0, j = 0; j < y_count.size(); ++j)
        {
            // Skip past x values that are in the incorrect order with respect to ysort[j].
            while (i < xsort.size() && !(ysort[j].first < xsort[i].first)) 
                ++i;

            y_count[ysort[j].second] = i;
        }
    }

// ----------------------------------------------------------------------------------------

    namespace impl
    {
        inline bool compare_first_reverse_second (
            const std::pair<double,bool>& a,
            const std::pair<double,bool>& b
        )
        {
            if (a.first < b.first)
                return true;
            else if (a.first > b.first)
                return false;
            else if (a.second && !b.second)
                return true;
            else
                return false;
        }
    }

    template <
        typename ranking_function,
        typename T
        >
    matrix<double,1,2> test_ranking_function (
        const ranking_function& funct,
        const std::vector<ranking_pair<T> >& samples
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(is_ranking_problem(samples),
            "\t double test_ranking_function()"
            << "\n\t invalid inputs were given to this function"
            << "\n\t samples.size(): " << samples.size() 
            << "\n\t is_ranking_problem(samples): " << is_ranking_problem(samples)
            );

        unsigned long total_pairs = 0;
        unsigned long total_wrong = 0;

        std::vector<double> rel_scores;
        std::vector<double> nonrel_scores;
        std::vector<unsigned long> rel_counts;
        std::vector<unsigned long> nonrel_counts;

        running_stats<double> rs;
        std::vector<std::pair<double,bool> > total_scores;
        std::vector<bool> total_ranking;

        for (unsigned long i = 0; i < samples.size(); ++i)
        {
            rel_scores.resize(samples[i].relevant.size());
            nonrel_scores.resize(samples[i].nonrelevant.size());
            total_scores.clear();

            for (unsigned long k = 0; k < rel_scores.size(); ++k)
            {
                rel_scores[k] = funct(samples[i].relevant[k]);
                total_scores.push_back(std::make_pair(rel_scores[k], true));
            }

            for (unsigned long k = 0; k < nonrel_scores.size(); ++k)
            {
                nonrel_scores[k] = funct(samples[i].nonrelevant[k]);
                total_scores.push_back(std::make_pair(nonrel_scores[k], false));
            }

            // Now compute the average precision for this sample.  We need to sort the
            // results and the back them into total_ranking.  Note that we sort them so
            // that, if you get a block of ranking values that are all equal, the elements
            // marked as true will come last.  This prevents a ranking from outputting a
            // constant value for everything and still getting a good MAP score.
            std::sort(total_scores.rbegin(), total_scores.rend(), impl::compare_first_reverse_second);
            total_ranking.clear();
            for (unsigned long i = 0; i < total_scores.size(); ++i)
                total_ranking.push_back(total_scores[i].second);
            rs.add(average_precision(total_ranking));


            count_ranking_inversions(rel_scores, nonrel_scores, rel_counts, nonrel_counts);

            total_pairs += rel_scores.size()*nonrel_scores.size();

            // Note that we don't need to look at nonrel_counts since it is redundant with
            // the information in rel_counts in this case.
            total_wrong += sum(mat(rel_counts));
        }

        const double rank_swaps = static_cast<double>(total_pairs - total_wrong) / total_pairs;
        const double mean_average_precision = rs.mean();
        matrix<double,1,2> res;
        res = rank_swaps, mean_average_precision;
        return res;
    }

// ----------------------------------------------------------------------------------------

    template <
        typename ranking_function,
        typename T
        >
    matrix<double,1,2> test_ranking_function (
        const ranking_function& funct,
        const ranking_pair<T>& sample
    )
    {
        return test_ranking_function(funct, std::vector<ranking_pair<T> >(1,sample));
    }

// ----------------------------------------------------------------------------------------

    template <
        typename trainer_type,
        typename T
        >
    matrix<double,1,2> cross_validate_ranking_trainer (
        const trainer_type& trainer,
        const std::vector<ranking_pair<T> >& samples,
        const long folds
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(is_ranking_problem(samples) &&
                    1 < folds && folds <= static_cast<long>(samples.size()),
            "\t double cross_validate_ranking_trainer()"
            << "\n\t invalid inputs were given to this function"
            << "\n\t samples.size(): " << samples.size() 
            << "\n\t folds:  " << folds 
            << "\n\t is_ranking_problem(samples): " << is_ranking_problem(samples)
            );


        const long num_in_test  = samples.size()/folds;
        const long num_in_train = samples.size() - num_in_test;


        std::vector<ranking_pair<T> > samples_test, samples_train;


        long next_test_idx = 0;

        unsigned long total_pairs = 0;
        unsigned long total_wrong = 0;

        std::vector<double> rel_scores;
        std::vector<double> nonrel_scores;
        std::vector<unsigned long> rel_counts;
        std::vector<unsigned long> nonrel_counts;

        running_stats<double> rs;
        std::vector<std::pair<double,bool> > total_scores;
        std::vector<bool> total_ranking;

        for (long i = 0; i < folds; ++i)
        {
            samples_test.clear();
            samples_train.clear();

            // load up the test samples
            for (long cnt = 0; cnt < num_in_test; ++cnt)
            {
                samples_test.push_back(samples[next_test_idx]);
                next_test_idx = (next_test_idx + 1)%samples.size();
            }

            // load up the training samples
            long next = next_test_idx;
            for (long cnt = 0; cnt < num_in_train; ++cnt)
            {
                samples_train.push_back(samples[next]);
                next = (next + 1)%samples.size();
            }


            const typename trainer_type::trained_function_type& df = trainer.train(samples_train);

            // check how good df is on the test data
            for (unsigned long i = 0; i < samples_test.size(); ++i)
            {
                rel_scores.resize(samples_test[i].relevant.size());
                nonrel_scores.resize(samples_test[i].nonrelevant.size());

                total_scores.clear();

                for (unsigned long k = 0; k < rel_scores.size(); ++k)
                {
                    rel_scores[k] = df(samples_test[i].relevant[k]);
                    total_scores.push_back(std::make_pair(rel_scores[k], true));
                }

                for (unsigned long k = 0; k < nonrel_scores.size(); ++k)
                {
                    nonrel_scores[k] = df(samples_test[i].nonrelevant[k]);
                    total_scores.push_back(std::make_pair(nonrel_scores[k], false));
                }

                // Now compute the average precision for this sample.  We need to sort the
                // results and the back them into total_ranking.  Note that we sort them so
                // that, if you get a block of ranking values that are all equal, the elements
                // marked as true will come last.  This prevents a ranking from outputting a
                // constant value for everything and still getting a good MAP score.
                std::sort(total_scores.rbegin(), total_scores.rend(), impl::compare_first_reverse_second);
                total_ranking.clear();
                for (unsigned long i = 0; i < total_scores.size(); ++i)
                    total_ranking.push_back(total_scores[i].second);
                rs.add(average_precision(total_ranking));


                count_ranking_inversions(rel_scores, nonrel_scores, rel_counts, nonrel_counts);

                total_pairs += rel_scores.size()*nonrel_scores.size();

                // Note that we don't need to look at nonrel_counts since it is redundant with
                // the information in rel_counts in this case.
                total_wrong += sum(mat(rel_counts));
            }

        } // for (long i = 0; i < folds; ++i)

        const double rank_swaps = static_cast<double>(total_pairs - total_wrong) / total_pairs;
        const double mean_average_precision = rs.mean();
        matrix<double,1,2> res;
        res = rank_swaps, mean_average_precision;
        return res;
    }

// ----------------------------------------------------------------------------------------

}

#endif // DLIB_RANKING_ToOLS_Hh_