"vscode:/vscode.git/clone" did not exist on "69cdea908d19a02baa6d252329f3639b5dc20473"
svm_multiclass_linear_trainer.h 13.5 KB
Newer Older
1
2
3
4
5
6
// Copyright (C) 2011  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#ifndef DLIB_SVm_MULTICLASS_LINEAR_TRAINER_H__ 
#define DLIB_SVm_MULTICLASS_LINEAR_TRAINER_H__

#include "svm_multiclass_linear_trainer_abstract.h"
7
#include "structural_svm_problem_threaded.h"
8
9
10
11
#include <vector>
#include "../optimization/optimization_oca.h"
#include "../matrix.h"
#include "sparse_vector.h"
12
#include "function.h"
13
#include <algorithm>
14
15
16
17
18
19
20
21
22
23
24

namespace dlib
{

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

    template <
        typename matrix_type,
        typename sample_type,
        typename label_type
        >
25
    class multiclass_svm_problem : public structural_svm_problem_threaded<matrix_type,
26
27
                                                                 std::vector<std::pair<unsigned long,typename matrix_type::type> > > 
    {
28
29
30
31
        /*!
            WHAT THIS OBJECT REPRESENTS
                This object defines the optimization problem for the multiclass SVM trainer
                object at the bottom of this file.  
Davis King's avatar
Davis King committed
32
33
34
35
36
37
38
39
40

                The joint feature vectors used by this object, the PSI(x,y) vectors, are
                defined as follows:
                    PSI(x,0) = [x,0,0,0,0, ...,0]
                    PSI(x,1) = [0,x,0,0,0, ...,0]
                    PSI(x,2) = [0,0,x,0,0, ...,0]
                That is, if there are N labels then the joint feature vector has a
                dimension that is N times the dimension of a single x sample.  Also,
                note that we append a -1 value onto each x to account for the bias term.
41
42
        !*/

43
44
45
46
47
48
    public:
        typedef typename matrix_type::type scalar_type;
        typedef std::vector<std::pair<unsigned long,scalar_type> > feature_vector_type;

        multiclass_svm_problem (
            const std::vector<sample_type>& samples_,
49
            const std::vector<label_type>& labels_,
50
51
            const std::vector<label_type>& distinct_labels_,
            const unsigned long dims_,
52
            const unsigned long num_threads
53
        ) :
54
            structural_svm_problem_threaded<matrix_type, std::vector<std::pair<unsigned long,typename matrix_type::type> > >(num_threads),
55
56
            samples(samples_),
            labels(labels_),
57
58
            distinct_labels(distinct_labels_),
            dims(dims_+1) // +1 for the bias
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
        {}

        virtual long get_num_dimensions (
        ) const
        {
            return dims*distinct_labels.size();
        }

        virtual long get_num_samples (
        ) const 
        {
            return static_cast<long>(samples.size());
        }

        virtual void get_truth_joint_feature_vector (
            long idx,
            feature_vector_type& psi
        ) const 
        {
78
            assign(psi, samples[idx]);
79
            // Add a constant -1 to account for the bias term.
80
            psi.push_back(std::make_pair(dims-1,static_cast<scalar_type>(-1)));
81
82

            // Find which distinct label goes with this psi.
83
84
85
86
87
88
89
90
91
            long label_idx = 0;
            for (unsigned long i = 0; i < distinct_labels.size(); ++i)
            {
                if (distinct_labels[i] == labels[idx])
                {
                    label_idx = i;
                    break;
                }
            }
92
93
94
95
96
97
98
99
100
101
102
103
104
105

            offset_feature_vector(psi, dims*label_idx);
        }

        virtual void separation_oracle (
            const long idx,
            const matrix_type& current_solution,
            scalar_type& loss,
            feature_vector_type& psi
        ) const 
        {
            scalar_type best_val = -std::numeric_limits<scalar_type>::infinity();
            unsigned long best_idx = 0;

Davis King's avatar
Davis King committed
106
107
            // Figure out which label is the best.  That is, what label maximizes
            // LOSS(idx,y) + F(x,y).  Note that y in this case is given by distinct_labels[i].
108
109
            for (unsigned long i = 0; i < distinct_labels.size(); ++i)
            {
Davis King's avatar
Davis King committed
110
                // Compute the F(x,y) part:
111
                // perform: temp == dot(relevant part of current solution, samples[idx]) - current_bias
112
                scalar_type temp = dot(mat(&current_solution(i*dims),dims-1), samples[idx]) - current_solution((i+1)*dims-1);
113

Davis King's avatar
Davis King committed
114
                // Add the LOSS(idx,y) part:
115
116
117
                if (labels[idx] != distinct_labels[i])
                    temp += 1;

Davis King's avatar
Davis King committed
118
                // Now temp == LOSS(idx,y) + F(x,y).  Check if it is the biggest we have seen.
119
120
121
122
123
124
125
                if (temp > best_val)
                {
                    best_val = temp;
                    best_idx = i;
                }
            }

126
            assign(psi, samples[idx]);
127
            // add a constant -1 to account for the bias term
128
            psi.push_back(std::make_pair(dims-1,static_cast<scalar_type>(-1)));
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

            offset_feature_vector(psi, dims*best_idx);

            if (distinct_labels[best_idx] == labels[idx])
                loss = 0;
            else
                loss = 1;
        }

    private:

        void offset_feature_vector (
            feature_vector_type& sample,
            const unsigned long val
        ) const
        {
            if (val != 0)
            {
                for (typename feature_vector_type::iterator i = sample.begin(); i != sample.end(); ++i)
                {
                    i->first += val;
                }
            }
        }


        const std::vector<sample_type>& samples;
        const std::vector<label_type>& labels;
157
        const std::vector<label_type>& distinct_labels;
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
        const long dims;
    };


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

    template <
        typename K,
        typename label_type_ = typename K::scalar_type 
        >
    class svm_multiclass_linear_trainer
    {
    public:
        typedef label_type_ label_type;
        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 multiclass_linear_decision_function<kernel_type, label_type> trained_function_type;


180
181
182
183
184
185
186
187
        // You are getting a compiler error on this line because you supplied a non-linear kernel
        // to the svm_c_linear_trainer object.  You have to use one of the linear kernels with this
        // trainer.
        COMPILE_TIME_ASSERT((is_same_type<K, linear_kernel<sample_type> >::value ||
                             is_same_type<K, sparse_linear_kernel<sample_type> >::value ));

        svm_multiclass_linear_trainer (
        ) :
188
            num_threads(4),
189
190
            C(1),
            eps(0.001),
191
192
            verbose(false),
            learn_nonnegative_weights(false)
193
194
195
        {
        }

196
197
198
199
200
201
202
203
204
205
206
207
208
        void set_num_threads (
            unsigned long num
        )
        {
            num_threads = num;
        }

        unsigned long get_num_threads (
        ) const
        {
            return num_threads;
        }

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
        void set_epsilon (
            scalar_type eps_
        )
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(eps_ > 0,
                "\t void svm_multiclass_linear_trainer::set_epsilon()"
                << "\n\t eps_ must be greater than 0"
                << "\n\t eps_: " << eps_ 
                << "\n\t this: " << this
                );

            eps = eps_;
        }

        const scalar_type get_epsilon (
        ) const { return eps; }

        void be_verbose (
        )
        {
            verbose = true;
        }

        void be_quiet (
        )
        {
            verbose = false;
        }

        void set_oca (
            const oca& item
        )
        {
            solver = item;
        }

        const oca get_oca (
        ) const
        {
            return solver;
        }

        const kernel_type get_kernel (
        ) const
        {
            return kernel_type();
        }

258
259
260
261
262
263
264
265
        bool learns_nonnegative_weights (
        ) const { return learn_nonnegative_weights; }
       
        void set_learns_nonnegative_weights (
            bool value
        )
        {
            learn_nonnegative_weights = value;
266
            prior = trained_function_type(); 
267
268
        }

269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
        void set_c (
            scalar_type C_
        )
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(C_ > 0,
                "\t void svm_multiclass_linear_trainer::set_c()"
                << "\n\t C must be greater than 0"
                << "\n\t C_:   " << C_ 
                << "\n\t this: " << this
                );

            C = C_;
        }

        const scalar_type get_c (
        ) const
        {
            return C;
        }

290
291
292
293
294
295
296
297
298
299
300
301
302
303
        void set_prior (
            const trained_function_type& prior_
        )
        {
            prior = prior_;
            learn_nonnegative_weights = false;
        }

        bool has_prior (
        ) const
        {
            return prior.labels.size() != 0;
        }

304
305
306
307
308
        trained_function_type train (
            const std::vector<sample_type>& all_samples,
            const std::vector<label_type>& all_labels
        ) const
        {
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
            scalar_type svm_objective = 0;
            return train(all_samples, all_labels, svm_objective);
        }

        trained_function_type train (
            const std::vector<sample_type>& all_samples,
            const std::vector<label_type>& all_labels,
            scalar_type& svm_objective
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(is_learning_problem(all_samples,all_labels),
                "\t trained_function_type svm_multiclass_linear_trainer::train(all_samples,all_labels)"
                << "\n\t invalid inputs were given to this function"
                << "\n\t all_samples.size():     " << all_samples.size() 
                << "\n\t all_labels.size():      " << all_labels.size() 
                );

327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
            trained_function_type df;
            df.labels = select_all_distinct_labels(all_labels);
            if (has_prior())
            {
                df.labels.insert(df.labels.end(), prior.labels.begin(), prior.labels.end());
                df.labels = select_all_distinct_labels(df.labels);
            }
            const long input_sample_dimensionality = max_index_plus_one(all_samples);
            // If the samples are sparse then the right thing to do is to take the max
            // dimensionality between the prior and the new samples.  But if the samples
            // are dense vectors then they definitely all have to have exactly the same
            // dimensionality.
            const long dims = std::max(df.weights.nc(),input_sample_dimensionality);
            if (is_matrix<sample_type>::value && has_prior())
            {
                DLIB_ASSERT(input_sample_dimensionality == prior.weights.nc(), 
                    "\t trained_function_type svm_multiclass_linear_trainer::train(all_samples,all_labels)"
                    << "\n\t The training samples given to this function are not the same kind of training "
                    << "\n\t samples used to create the prior."
                    << "\n\t input_sample_dimensionality: " << input_sample_dimensionality 
                    << "\n\t prior.weights.nc():          " << prior.weights.nc() 
                );
            }

351
352
            typedef matrix<scalar_type,0,1> w_type;
            w_type weights;
353
            multiclass_svm_problem<w_type, sample_type, label_type> problem(all_samples, all_labels, df.labels, dims, num_threads);
354
355
356
            if (verbose)
                problem.be_verbose();

357
            problem.set_max_cache_size(0);
358
359
            problem.set_c(C);
            problem.set_epsilon(eps);
360

361
362
363
364
365
366
            unsigned long num_nonnegative = 0;
            if (learn_nonnegative_weights)
            {
                num_nonnegative = problem.get_num_dimensions();
            }

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
            if (!has_prior())
            {
                svm_objective = solver(problem, weights, num_nonnegative);
            }
            else
            {
                matrix<scalar_type> temp(df.labels.size(),dims);
                w_type b(df.labels.size());
                temp = 0;
                b = 0;

                // Copy the prior into the temp and b matrices.  We have to do this row
                // by row copy because the new training data might have new labels we
                // haven't seen before and therefore the sizes of these matrices could be
                // different.
                for (unsigned long i = 0; i < prior.labels.size(); ++i)
                {
                    const long r = std::find(df.labels.begin(), df.labels.end(), prior.labels[i])-df.labels.begin();
                    set_rowm(temp,r) = rowm(prior.weights,i);
                    b(r) = prior.b(i);
                }

                const w_type prior_vect = reshape_to_column_vector(join_rows(temp,b));
                svm_objective = solver(problem, weights, prior_vect);
            }
392
393
394
395
396
397


            df.weights = colm(reshape(weights, df.labels.size(), dims+1), range(0,dims-1));
            df.b       = colm(reshape(weights, df.labels.size(), dims+1), dims);
            return df;
        }
398
399

    private:
400
401

        unsigned long num_threads;
402
403
404
405
        scalar_type C;
        scalar_type eps;
        bool verbose;
        oca solver;
406
        bool learn_nonnegative_weights;
407
408

        trained_function_type prior;
409
410
411
412
413
414
415
416
417
    };

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

}


#endif // DLIB_SVm_MULTICLASS_LINEAR_TRAINER_H__