krr_trainer.h 10.9 KB
Newer Older
1
2
// Copyright (C) 2010  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
3
4
#ifndef DLIB_KRR_TRAInER_Hh_
#define DLIB_KRR_TRAInER_Hh_
5
6
7
8
9
10

#include "../algs.h"
#include "function.h"
#include "kernel.h"
#include "empirical_kernel_map.h"
#include "linearly_independent_subset_finder.h"
11
#include "../statistics.h"
12
#include "rr_trainer.h"
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
#include "krr_trainer_abstract.h"
#include <vector>
#include <iostream>

namespace dlib
{
    template <
        typename K 
        >
    class krr_trainer
    {

    public:
        typedef K kernel_type;
        typedef typename kernel_type::scalar_type scalar_type;
        typedef typename kernel_type::sample_type sample_type;
        typedef typename kernel_type::mem_manager_type mem_manager_type;
        typedef decision_function<kernel_type> trained_function_type;

        krr_trainer (
        ) :
            verbose(false),
            max_basis_size(400),
            ekm_stale(true)
        {
        }

        void be_verbose (
        )
        {
            verbose = true;
44
            trainer.be_verbose();
45
46
47
48
49
50
        }

        void be_quiet (
        )
        {
            verbose = false;
51
            trainer.be_quiet();
52
53
        }

54
        void use_regression_loss_for_loo_cv (
55
56
        )
        {
57
            trainer.use_regression_loss_for_loo_cv();
58
59
        }

60
        void use_classification_loss_for_loo_cv (
61
62
        )
        {
63
            trainer.use_classification_loss_for_loo_cv();
64
65
        }

66
        bool will_use_regression_loss_for_loo_cv (
67
        ) const
68
        {
69
            return trainer.will_use_regression_loss_for_loo_cv();
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
        }

        const kernel_type get_kernel (
        ) const
        {
            return kern;
        }

        void set_kernel (
            const kernel_type& k
        )
        {
            kern = k;
        }

        template <typename T>
        void set_basis (
            const T& basis_samples
        )
        {
            // make sure requires clause is not broken
91
            DLIB_ASSERT(basis_samples.size() > 0 && is_vector(mat(basis_samples)),
92
93
94
                "\tvoid krr_trainer::set_basis(basis_samples)"
                << "\n\t You have to give a non-empty set of basis_samples and it must be a vector"
                << "\n\t basis_samples.size():                       " << basis_samples.size() 
95
                << "\n\t is_vector(mat(basis_samples)): " << is_vector(mat(basis_samples)) 
96
97
98
                << "\n\t this: " << this
                );

99
            basis = mat(basis_samples);
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
            ekm_stale = true;
        }

        bool basis_loaded (
        ) const
        {
            return (basis.size() != 0);
        }

        void clear_basis (
        )
        {
            basis.set_size(0);
            ekm.clear();
            ekm_stale = true;
        }

        unsigned long get_max_basis_size (
        ) const
        {
            return max_basis_size;
        }

        void set_max_basis_size (
            unsigned long max_basis_size_
        )
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(max_basis_size_ > 0,
                "\t void krr_trainer::set_max_basis_size()"
                << "\n\t max_basis_size_ must be greater than 0"
                << "\n\t max_basis_size_: " << max_basis_size_ 
                << "\n\t this:            " << this
                );

            max_basis_size = max_basis_size_;
        }

        void set_lambda (
            scalar_type lambda_ 
        )
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(lambda_ >= 0,
                "\t void krr_trainer::set_lambda()"
                << "\n\t lambda must be greater than or equal to 0"
146
                << "\n\t lambda_: " << lambda_
147
148
149
                << "\n\t this:   " << this
                );

150
            trainer.set_lambda(lambda_);
151
152
153
154
155
        }

        const scalar_type get_lambda (
        ) const
        {
156
            return trainer.get_lambda();
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
        }

        template <typename EXP>
        void set_search_lambdas (
            const matrix_exp<EXP>& lambdas
        )
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(is_vector(lambdas) && lambdas.size() > 0 && min(lambdas) > 0,
                "\t void krr_trainer::set_search_lambdas()"
                << "\n\t lambdas must be a non-empty vector of values"
                << "\n\t is_vector(lambdas): " << is_vector(lambdas) 
                << "\n\t lambdas.size():     " << lambdas.size()
                << "\n\t min(lambdas):       " << min(lambdas) 
                << "\n\t this:   " << this
                );

174
            trainer.set_search_lambdas(lambdas);
175
176
177
178
179
        }

        const matrix<scalar_type,0,0,mem_manager_type>& get_search_lambdas (
        ) const
        {
180
            return trainer.get_search_lambdas();
181
182
183
184
185
186
187
188
189
190
191
        }

        template <
            typename in_sample_vector_type,
            typename in_scalar_vector_type
            >
        const decision_function<kernel_type> train (
            const in_sample_vector_type& x,
            const in_scalar_vector_type& y
        ) const
        {
192
193
            std::vector<scalar_type> temp;
            scalar_type temp2;
194
            return do_train(mat(x), mat(y), false, temp, temp2);
195
196
197
198
199
200
201
202
203
        }

        template <
            typename in_sample_vector_type,
            typename in_scalar_vector_type
            >
        const decision_function<kernel_type> train (
            const in_sample_vector_type& x,
            const in_scalar_vector_type& y,
204
            std::vector<scalar_type>& loo_values
205
206
207
        ) const
        {
            scalar_type temp;
208
            return do_train(mat(x), mat(y), true, loo_values, temp);
209
210
211
212
213
214
215
216
217
        }

        template <
            typename in_sample_vector_type,
            typename in_scalar_vector_type
            >
        const decision_function<kernel_type> train (
            const in_sample_vector_type& x,
            const in_scalar_vector_type& y,
218
            std::vector<scalar_type>& loo_values,
219
220
221
            scalar_type& lambda_used 
        ) const
        {
222
            return do_train(mat(x), mat(y), true, loo_values, lambda_used);
223
224
225
226
227
228
229
230
231
232
233
234
        }


    private:

        template <
            typename in_sample_vector_type,
            typename in_scalar_vector_type
            >
        const decision_function<kernel_type> do_train (
            const in_sample_vector_type& x,
            const in_scalar_vector_type& y,
235
236
            const bool output_loo_values,
            std::vector<scalar_type>& loo_values,
237
238
239
240
            scalar_type& the_lambda
        ) const
        {
            // make sure requires clause is not broken
241
            DLIB_ASSERT(is_learning_problem(x,y),
242
243
244
245
246
247
248
249
250
                "\t decision_function krr_trainer::train(x,y)"
                << "\n\t invalid inputs were given to this function"
                << "\n\t is_vector(x): " << is_vector(x)
                << "\n\t is_vector(y): " << is_vector(y)
                << "\n\t x.size():     " << x.size() 
                << "\n\t y.size():     " << y.size() 
                );

#ifdef ENABLE_ASSERTS
251
            if (get_lambda() == 0 && will_use_regression_loss_for_loo_cv() == false)
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
            {
                // make sure requires clause is not broken
                DLIB_ASSERT(is_binary_classification_problem(x,y),
                    "\t decision_function krr_trainer::train(x,y)"
                    << "\n\t invalid inputs were given to this function"
                    );
            }
#endif

            // The first thing we do is make sure we have an appropriate ekm ready for use below.
            if (basis_loaded())
            {
                if (ekm_stale)
                {
                    ekm.load(kern, basis);
                    ekm_stale = false;
                }
            }
            else
            {
                linearly_independent_subset_finder<kernel_type> lisf(kern, max_basis_size);
                fill_lisf(lisf, x);
                ekm.load(lisf);
            }

            if (verbose)
            {
279
                std::cout << "\nNumber of basis vectors used: " << ekm.out_vector_size() << std::endl;
280
281
282
283
            }

            typedef matrix<scalar_type,0,1,mem_manager_type> column_matrix_type;

284
285
            running_stats<scalar_type> rs;

286
287
288
289
290
            // Now we project all the x samples into kernel space using our EKM 
            matrix<column_matrix_type,0,1,mem_manager_type > proj_x;
            proj_x.set_size(x.size());
            for (long i = 0; i < proj_x.size(); ++i)
            {
291
                scalar_type err;
292
293
                // Note that we also append a 1 to the end of the vectors because this is
                // a convenient way of dealing with the bias term later on.
294
295
                if (verbose == false)
                {
296
                    proj_x(i) = ekm.project(x(i));
297
298
299
                }
                else
                {
300
                    proj_x(i) = ekm.project(x(i),err);
301
302
303
304
305
306
307
308
                    rs.add(err);
                }
            }

            if (verbose)
            {
                std::cout << "Mean EKM projection error:                  " << rs.mean() << std::endl;
                std::cout << "Standard deviation of EKM projection error: " << rs.stddev() << std::endl;
309
310
311
            }


312
            decision_function<linear_kernel<matrix<scalar_type,0,0,mem_manager_type> > > lin_df;
313

314
315
            if (output_loo_values)
                lin_df = trainer.train(proj_x,y, loo_values, the_lambda);
316
317
            else
                lin_df = trainer.train(proj_x,y);
318

319
            // convert the linear decision function into a kernelized one.
320
            decision_function<kernel_type> df;
321
322
            df = ekm.convert_to_decision_function(lin_df.basis_vectors(0));
            df.b = lin_df.b; 
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340

            // If we used an automatically derived basis then there isn't any point in
            // keeping the ekm around.  So free its memory.
            if (basis_loaded() == false)
            {
                ekm.clear();
            }

            return df;
        }


        /*!
            CONVENTION
                - if (ekm_stale) then
                    - kern or basis have changed since the last time
                      they were loaded into the ekm

341
                - get_lambda() == trainer.get_lambda()
342
343
                - get_kernel() == kern
                - get_max_basis_size() == max_basis_size
344
345
                - will_use_regression_loss_for_loo_cv() == trainer.will_use_regression_loss_for_loo_cv() 
                - get_search_lambdas() == trainer.get_search_lambdas() 
346
347
348
349

                - basis_loaded() == (basis.size() != 0)
        !*/

350
351
        rr_trainer<linear_kernel<matrix<scalar_type,0,0,mem_manager_type> > > trainer;

352
353
354
355
356
357
358
359
360
361
362
363
364
365
        bool verbose;


        kernel_type kern;
        unsigned long max_basis_size;

        matrix<sample_type,0,1,mem_manager_type> basis;
        mutable empirical_kernel_map<kernel_type> ekm;
        mutable bool ekm_stale; 

    }; 

}

366
#endif // DLIB_KRR_TRAInER_Hh_
367
368