loss_abstract.h 66.6 KB
Newer Older
Davis King's avatar
Davis King committed
1
2
3
4
5
6
// Copyright (C) 2015  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#undef DLIB_DNn_LOSS_ABSTRACT_H_
#ifdef DLIB_DNn_LOSS_ABSTRACT_H_

#include "core_abstract.h"
7
#include "../image_processing/full_object_detection_abstract.h"
Davis King's avatar
Davis King committed
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

namespace dlib
{

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

    class EXAMPLE_LOSS_LAYER_
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
                A loss layer is the final layer in a deep neural network.  It computes the
                task loss.  That is, it computes a number that tells us how well the
                network is performing on some task, such as predicting a binary label.  

                You can use one of the loss layers that comes with dlib (defined below).
                But importantly, you are able to define your own loss layers to suit your
                needs.  You do this by creating a class that defines an interface matching
                the one described by this EXAMPLE_LOSS_LAYER_ class.  Note that there is no
                dlib::EXAMPLE_LOSS_LAYER_ type.  It is shown here purely to document the
Davis King's avatar
Davis King committed
27
                interface that a loss layer must implement.
Davis King's avatar
Davis King committed
28
29
30
31
32
33
34
35

                A loss layer can optionally provide a to_label() method that converts the
                output of a network into a user defined type.  If to_label() is not
                provided then the operator() methods of add_loss_layer will not be
                available, but otherwise everything will function as normal.

                Finally, note that there are two broad flavors of loss layer, supervised
                and unsupervised.  The EXAMPLE_LOSS_LAYER_ as shown here is a supervised
36
37
                layer.  To make an unsupervised loss you simply leave out the
                training_label_type typedef and the truth iterator argument to
38
                compute_loss_value_and_gradient().
Davis King's avatar
Davis King committed
39
40
41
42
        !*/

    public:

43
44
45
        // In most cases training_label_type and output_label_type will be the same type.
        typedef whatever_type_you_use_for_training_labels training_label_type;
        typedef whatever_type_you_use_for_outout_labels   output_label_type;
Davis King's avatar
Davis King committed
46

Davis King's avatar
Davis King committed
47
48
49
50
51
52
53
        EXAMPLE_LOSS_LAYER_ (
        );
        /*!
            ensures
                - EXAMPLE_LOSS_LAYER_ objects are default constructable.
        !*/

54
55
56
57
58
        EXAMPLE_LOSS_LAYER_ (
            const EXAMPLE_LOSS_LAYER_& item
        );
        /*!
            ensures
Davis King's avatar
Davis King committed
59
                - EXAMPLE_LOSS_LAYER_ objects are copy constructable.
60
        !*/
Davis King's avatar
Davis King committed
61
62
63
64
65
66
67

        // Implementing to_label() is optional.
        template <
            typename SUB_TYPE,
            typename label_iterator
            >
        void to_label (
68
            const tensor& input_tensor,
Davis King's avatar
Davis King committed
69
70
71
72
73
            const SUB_TYPE& sub,
            label_iterator iter
        ) const;
        /*!
            requires
Davis King's avatar
Davis King committed
74
                - SUBNET implements the SUBNET interface defined at the top of
Davis King's avatar
Davis King committed
75
                  layers_abstract.h.
76
77
78
                - input_tensor was given as input to the network sub and the outputs are
                  now visible in layer<i>(sub).get_output(), for all valid i.
                - input_tensor.num_samples() > 0
79
                - input_tensor.num_samples()%sub.sample_expansion_factor() == 0.
Davis King's avatar
Davis King committed
80
                - iter == an iterator pointing to the beginning of a range of
81
                  input_tensor.num_samples()/sub.sample_expansion_factor() elements.  Moreover,
82
                  they must be output_label_type elements.
Davis King's avatar
Davis King committed
83
            ensures
84
                - Converts the output of the provided network to output_label_type objects and
Davis King's avatar
Davis King committed
85
                  stores the results into the range indicated by iter.  In particular, for
86
                  all valid i, it will be the case that:
87
                    *(iter+i/sub.sample_expansion_factor()) is populated based on the output of
Davis King's avatar
Davis King committed
88
                    sub and corresponds to the ith sample in input_tensor.
Davis King's avatar
Davis King committed
89
90
91
92
        !*/

        template <
            typename const_label_iterator,
Davis King's avatar
Davis King committed
93
            typename SUBNET
Davis King's avatar
Davis King committed
94
            >
95
        double compute_loss_value_and_gradient (
Davis King's avatar
Davis King committed
96
97
            const tensor& input_tensor,
            const_label_iterator truth, 
Davis King's avatar
Davis King committed
98
            SUBNET& sub
Davis King's avatar
Davis King committed
99
100
101
        ) const;
        /*!
            requires
Davis King's avatar
Davis King committed
102
                - SUBNET implements the SUBNET interface defined at the top of
Davis King's avatar
Davis King committed
103
104
105
106
                  layers_abstract.h.
                - input_tensor was given as input to the network sub and the outputs are
                  now visible in layer<i>(sub).get_output(), for all valid i.
                - input_tensor.num_samples() > 0
107
                - input_tensor.num_samples()%sub.sample_expansion_factor() == 0.
Davis King's avatar
Davis King committed
108
                - for all valid i:
Davis King's avatar
Davis King committed
109
110
                    - layer<i>(sub).get_gradient_input() has the same dimensions as
                      layer<i>(sub).get_output().
Davis King's avatar
Davis King committed
111
112
                    - layer<i>(sub).get_gradient_input() contains all zeros (i.e.
                      initially, all input gradients are 0).
Davis King's avatar
Davis King committed
113
                - truth == an iterator pointing to the beginning of a range of
114
                  input_tensor.num_samples()/sub.sample_expansion_factor() elements.  Moreover,
115
                  they must be training_label_type elements.
116
                - for all valid i:
117
                    - *(truth+i/sub.sample_expansion_factor()) is the label of the ith sample in
118
                      input_tensor.
Davis King's avatar
Davis King committed
119
            ensures
Davis King's avatar
Davis King committed
120
                - This function computes a loss function that describes how well the output
Davis King's avatar
Davis King committed
121
122
                  of sub matches the expected labels given by truth.  Let's write the loss
                  function as L(input_tensor, truth, sub).  
123
124
125
126
                - Then compute_loss_value_and_gradient() computes the gradient of L() with
                  respect to the outputs in sub.  Specifically, compute_loss_value_and_gradient() 
                  assigns the gradients into sub by performing the following tensor
                  assignments, for all valid i: 
127
                    - layer<i>(sub).get_gradient_input() = the gradient of
Davis King's avatar
Davis King committed
128
                      L(input_tensor,truth,sub) with respect to layer<i>(sub).get_output().
Davis King's avatar
Davis King committed
129
130
131
                      Note that, since get_gradient_input() is zero initialized, you don't
                      have to write gradient information to layers that have a zero
                      loss gradient.
Davis King's avatar
Davis King committed
132
133
134
135
                - returns L(input_tensor,truth,sub)
        !*/
    };

136
137
138
139
140
    std::ostream& operator<<(std::ostream& out, const EXAMPLE_LOSS_LAYER_& item);
    /*!
        print a string describing this layer.
    !*/

Davis King's avatar
Davis King committed
141
142
143
144
145
146
    void to_xml(const EXAMPLE_LOSS_LAYER_& item, std::ostream& out);
    /*!
        This function is optional, but required if you want to print your networks with
        net_to_xml().  Therefore, to_xml() prints a layer as XML.
    !*/

147
148
149
150
151
152
    void serialize(const EXAMPLE_LOSS_LAYER_& item, std::ostream& out);
    void deserialize(EXAMPLE_LOSS_LAYER_& item, std::istream& in);
    /*!
        provides serialization support  
    !*/

Davis King's avatar
Davis King committed
153
154
155
156
    // For each loss layer you define, always define an add_loss_layer template so that
    // layers can be easily composed.  Moreover, the convention is that the layer class
    // ends with an _ while the add_loss_layer template has the same name but without the
    // trailing _.
Davis King's avatar
Davis King committed
157
158
    template <typename SUBNET>
    using EXAMPLE_LOSS_LAYER = add_loss_layer<EXAMPLE_LOSS_LAYER_, SUBNET>;
Davis King's avatar
Davis King committed
159
160
161
162
163
164
165
166
167

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

    class loss_binary_hinge_ 
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
Davis King's avatar
Davis King committed
168
                This object implements the loss layer interface defined above by
169
170
171
172
173
                EXAMPLE_LOSS_LAYER_.  In particular, it implements the hinge loss, which is
                appropriate for binary classification problems.  Therefore, the possible
                labels when using this loss are +1 and -1.  Moreover, it will cause the
                network to produce outputs > 0 when predicting a member of the +1 class and
                values < 0 otherwise.
Davis King's avatar
Davis King committed
174
175
176
        !*/
    public:

177
178
        typedef float training_label_type;
        typedef float output_label_type;
Davis King's avatar
Davis King committed
179
180
181
182
183
184

        template <
            typename SUB_TYPE,
            typename label_iterator
            >
        void to_label (
185
            const tensor& input_tensor,
Davis King's avatar
Davis King committed
186
187
188
189
190
191
192
193
194
            const SUB_TYPE& sub,
            label_iterator iter
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::to_label() except
            it has the additional calling requirements that: 
                - sub.get_output().nr() == 1
                - sub.get_output().nc() == 1
                - sub.get_output().k() == 1
195
                - sub.get_output().num_samples() == input_tensor.num_samples()
196
                - sub.sample_expansion_factor() == 1
197
198
199
            and the output label is the raw score for each classified object.  If the score
            is > 0 then the classifier is predicting the +1 class, otherwise it is
            predicting the -1 class.
Davis King's avatar
Davis King committed
200
201
202
203
        !*/

        template <
            typename const_label_iterator,
Davis King's avatar
Davis King committed
204
            typename SUBNET
Davis King's avatar
Davis King committed
205
            >
206
        double compute_loss_value_and_gradient (
Davis King's avatar
Davis King committed
207
208
            const tensor& input_tensor,
            const_label_iterator truth, 
Davis King's avatar
Davis King committed
209
            SUBNET& sub
Davis King's avatar
Davis King committed
210
211
        ) const;
        /*!
212
213
            This function has the same interface as EXAMPLE_LOSS_LAYER_::compute_loss_value_and_gradient() 
            except it has the additional calling requirements that: 
Davis King's avatar
Davis King committed
214
215
216
                - sub.get_output().nr() == 1
                - sub.get_output().nc() == 1
                - sub.get_output().k() == 1
217
                - sub.get_output().num_samples() == input_tensor.num_samples()
218
                - sub.sample_expansion_factor() == 1
Davis King's avatar
Davis King committed
219
220
221
222
223
                - all values pointed to by truth are +1 or -1.
        !*/

    };

Davis King's avatar
Davis King committed
224
225
    template <typename SUBNET>
    using loss_binary_hinge = add_loss_layer<loss_binary_hinge_, SUBNET>;
Davis King's avatar
Davis King committed
226

227
228
229
230
231
232
233
234
// ----------------------------------------------------------------------------------------

    class loss_binary_log_ 
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
                This object implements the loss layer interface defined above by
                EXAMPLE_LOSS_LAYER_.  In particular, it implements the log loss, which is
235
236
237
238
239
240
241
242
243
244
                appropriate for binary classification problems.  Therefore, there are two possible
                classes of labels: positive (> 0) and negative (< 0) when using this loss.
                The absolute value of the label represents its weight.  Putting a larger weight
                on a sample increases the importance of getting its prediction correct during 
                training.  A good rule of thumb is to use weights with absolute value 1 unless 
                you have a very unbalanced training dataset, in that case, give larger weight
                to the class with less training examples.
                
                This loss will cause the network to produce outputs > 0 when predicting a
                member of the positive class and values < 0 otherwise.
245
246
247
248
249
250

                To be more specific, this object contains a sigmoid layer followed by a 
                cross-entropy layer.  
        !*/
    public:

251
252
        typedef float training_label_type;
        typedef float output_label_type;
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269

        template <
            typename SUB_TYPE,
            typename label_iterator
            >
        void to_label (
            const tensor& input_tensor,
            const SUB_TYPE& sub,
            label_iterator iter
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::to_label() except
            it has the additional calling requirements that: 
                - sub.get_output().nr() == 1
                - sub.get_output().nc() == 1
                - sub.get_output().k() == 1
                - sub.get_output().num_samples() == input_tensor.num_samples()
270
                - sub.sample_expansion_factor() == 1
271
272
273
274
275
276
277
278
279
            and the output label is the raw score for each classified object.  If the score
            is > 0 then the classifier is predicting the +1 class, otherwise it is
            predicting the -1 class.
        !*/

        template <
            typename const_label_iterator,
            typename SUBNET
            >
280
        double compute_loss_value_and_gradient (
281
282
283
284
285
            const tensor& input_tensor,
            const_label_iterator truth, 
            SUBNET& sub
        ) const;
        /*!
286
287
            This function has the same interface as EXAMPLE_LOSS_LAYER_::compute_loss_value_and_gradient() 
            except it has the additional calling requirements that: 
288
289
290
291
                - sub.get_output().nr() == 1
                - sub.get_output().nc() == 1
                - sub.get_output().k() == 1
                - sub.get_output().num_samples() == input_tensor.num_samples()
292
                - sub.sample_expansion_factor() == 1
293
294
295
296
297
298
299
300
                - all values pointed to by truth are +1 or -1.
        !*/

    };

    template <typename SUBNET>
    using loss_binary_log = add_loss_layer<loss_binary_log_, SUBNET>;

301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
// ----------------------------------------------------------------------------------------

    class loss_multiclass_log_ 
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
                This object implements the loss layer interface defined above by
                EXAMPLE_LOSS_LAYER_.  In particular, it implements the multiclass logistic
                regression loss (e.g. negative log-likelihood loss), which is appropriate
                for multiclass classification problems.  This means that the possible
                labels when using this loss are integers >= 0.  
                
                Moreover, if after training you were to replace the loss layer of the
                network with a softmax layer, the network outputs would give the
                probabilities of each class assignment.  That is, if you have K classes
                then the network should output tensors with the tensor::k()'th dimension
                equal to K.  Applying softmax to these K values gives the probabilities of
                each class.  The index into that K dimensional vector with the highest
                probability is the predicted class label.
        !*/

    public:

324
325
        typedef unsigned long training_label_type;
        typedef unsigned long output_label_type;
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341

        template <
            typename SUB_TYPE,
            typename label_iterator
            >
        void to_label (
            const tensor& input_tensor,
            const SUB_TYPE& sub,
            label_iterator iter
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::to_label() except
            it has the additional calling requirements that: 
                - sub.get_output().nr() == 1
                - sub.get_output().nc() == 1
                - sub.get_output().num_samples() == input_tensor.num_samples()
342
                - sub.sample_expansion_factor() == 1
343
            and the output label is the predicted class for each classified object.  The number
Davis King's avatar
Davis King committed
344
            of possible output classes is sub.get_output().k().
345
346
347
348
349
350
        !*/

        template <
            typename const_label_iterator,
            typename SUBNET
            >
351
        double compute_loss_value_and_gradient (
352
353
354
355
356
            const tensor& input_tensor,
            const_label_iterator truth, 
            SUBNET& sub
        ) const;
        /*!
357
358
            This function has the same interface as EXAMPLE_LOSS_LAYER_::compute_loss_value_and_gradient() 
            except it has the additional calling requirements that: 
359
360
361
                - sub.get_output().nr() == 1
                - sub.get_output().nc() == 1
                - sub.get_output().num_samples() == input_tensor.num_samples()
362
                - sub.sample_expansion_factor() == 1
363
364
365
366
367
368
369
370
                - all values pointed to by truth are < sub.get_output().k()
        !*/

    };

    template <typename SUBNET>
    using loss_multiclass_log = add_loss_layer<loss_multiclass_log_, SUBNET>;

Davis King's avatar
Davis King committed
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
// ----------------------------------------------------------------------------------------

    class loss_multimulticlass_log_ 
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
                This object implements the loss layer interface defined above by
                EXAMPLE_LOSS_LAYER_.  In particular, it implements a collection of
                multiclass classifiers.  An example will make its use clear.  So suppose,
                for example, that you want to make something that takes a picture of a
                vehicle and answers the following questions:
                    - What type of vehicle is it? A sedan or a truck?
                    - What color is it? red, green, blue, gray, or black?
                You need two separate multi-class classifiers to do this.  One to decide
                the type of vehicle, and another to decide the color.  The
                loss_multimulticlass_log_ allows you to pack these two classifiers into one
                neural network.  This means that when you use the network to process an
                image it will output 2 labels for each image, the type label and the color
                label.  

                To create a loss_multimulticlass_log_ for the above case you would
                construct it as follows:
                    std::map<std::string,std::vector<std::string>> labels;
                    labels["type"] = {"sedan", "truck"};
                    labels["color"] = {"red", "green", "blue", "gray", "black"};
                    loss_multimulticlass_log_ myloss(labels);
                Then you could use myloss with a network object and train it to do this
                task.  More generally, you can use any number of classifiers and labels
                when using this object.  Finally, each of the classifiers uses a standard
                multi-class logistic regression loss.
        !*/

    public:

        loss_multimulticlass_log_(
        ); 
        /*!
            ensures
                - #number_of_labels() == 0
                - #get_labels().size() == 0
        !*/

        loss_multimulticlass_log_ (
            const std::map<std::string,std::vector<std::string>>& labels
        );
        /*!
            requires
                - Each vector in labels must contain at least 2 strings.  I.e. each
                  classifier must have at least two possible labels.
            ensures
                - #number_of_labels() == the total number of strings in all the
                  std::vectors in labels.
                - #number_of_classifiers() == labels.size()
                - #get_labels() == labels
        !*/

        unsigned long number_of_labels(
        ) const; 
        /*!
            ensures
                - returns the total number of labels known to this loss.  This is the count of 
                  all the labels in each classifier.
        !*/

        unsigned long number_of_classifiers(
        ) const; 
        /*!
            ensures
                - returns the number of classifiers defined by this loss.
        !*/

        std::map<std::string,std::vector<std::string>> get_labels ( 
        ) const;
        /*!
            ensures
                - returns the names of the classifiers and labels used by this loss.  In
                  particular, if the returned object is L then:
                    - L[CLASS] == the set of labels used by the classifier CLASS.
                    - L.size() == number_of_classifiers()
                    - The count of strings in the vectors in L == number_of_labels()
        !*/

        class classifier_output
        {
            /*!
                WHAT THIS OBJECT REPRESENTS
                    This object stores the predictions from one of the classifiers in
                    loss_multimulticlass_log_.  It allows you to find out the most likely
                    string label predicted by that classifier, as well as get the class
                    conditional probability of any of the classes in the classifier.
            !*/

        public:

            classifier_output(
            );
            /*!
                ensures
                    - #num_classes() == 0
            !*/

            size_t num_classes(
            ) const; 
            /*!
                ensures
                    - returns the number of possible classes output by this classifier.
            !*/

            double probability_of_class (
                size_t i
            ) const;
            /*!
                requires
                    - i < num_classes()
                ensures
                    - returns the probability that the true class has a label of label(i).
                    - The sum of probability_of_class(j) for j in the range [0, num_classes()) is always 1.
            !*/

            const std::string& label(
                size_t i
            ) const;
            /*!
                requires
                    - i < num_classes()
                ensures
                    - returns the string label for the ith class.
            !*/

            operator std::string(
            ) const;
            /*!
                requires
                    - num_classes() != 0
                ensures
                    - returns the string label for the most probable class.
            !*/

            friend std::ostream& operator<< (std::ostream& out, const classifier_output& item);
            /*!
                requires
                    - num_classes() != 0
                ensures
                    - prints the most probable class label to out.
            !*/

        };

        // Both training_label_type and output_label_type should always have sizes equal to
        // number_of_classifiers().  That is, the std::map should have an entry for every
        // classifier known to this loss.
        typedef std::map<std::string,std::string> training_label_type;
        typedef std::map<std::string,classifier_output> output_label_type;


        template <
            typename SUB_TYPE,
            typename label_iterator
            >
        void to_label (
            const tensor& input_tensor,
            const SUB_TYPE& sub,
            label_iterator iter
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::to_label() except
            it has the additional calling requirements that: 
                - number_of_labels() != 0
                - sub.get_output().k() == number_of_labels()
                - sub.get_output().nr() == 1
                - sub.get_output().nc() == 1
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
        !*/

        template <
            typename const_label_iterator,
            typename SUBNET
            >
        double compute_loss_value_and_gradient (
            const tensor& input_tensor,
            const_label_iterator truth, 
            SUBNET& sub
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::compute_loss_value_and_gradient() 
            except it has the additional calling requirements that: 
                - number_of_labels() != 0
                - sub.get_output().k() == number_of_labels()
                    It should be noted that the last layer in your network should usually
                    be an fc layer.  If so, you can satisfy this requirement of k() being
                    number_of_labels() by calling set_num_outputs() prior to training your
                    network like so:
                    your_network.subnet().layer_details().set_num_outputs(your_network.loss_details().number_of_labels());
                - sub.get_output().nr() == 1
                - sub.get_output().nc() == 1
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
                - All the std::maps pointed to by truth contain entries for all the
                  classifiers known to this loss.  That is, it must be valid to call
                  truth[i][classifier] for any of the classifiers known to this loss.  To
                  say this another way, all the training samples must contain labels for
                  each of the classifiers defined by this loss.

                  To really belabor this, this also means that truth[i].size() ==
                  get_labels().size() and that both truth[i] and get_labels() have the same
                  set of key strings.  It also means that the value strings in truth[i]
                  must be strings known to the loss, i.e. they are valid labels according
                  to get_labels().
        !*/
    };

    template <typename SUBNET>
    using loss_multimulticlass_log = add_loss_layer<loss_multimulticlass_log_, SUBNET>;

    // Allow comparison between classifier_outputs and std::string to check if the
    // predicted class is a particular string.
    inline bool operator== (const std::string& lhs, const loss_multimulticlass_log_::classifier_output& rhs)
    { return lhs == static_cast<const std::string&>(rhs); }
    inline bool operator== (const loss_multimulticlass_log_::classifier_output& lhs, const std::string& rhs)
    { return rhs == static_cast<const std::string&>(lhs); }

593
594
595
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

596
597
598
599
600
601
    enum class use_image_pyramid : uint8_t
    {
        no,
        yes
    };

602
603
604
605
    struct mmod_options
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
606
                This object contains all the parameters that control the behavior of loss_mmod_.
607
608
609
610
        !*/

    public:

611
        struct detector_window_details
612
        {
613
614
615
            detector_window_details() = default; 
            detector_window_details(unsigned long w, unsigned long h) : width(w), height(h) {}
            detector_window_details(unsigned long w, unsigned long h, const std::string& l) : width(w), height(h), label(l) {}
616
617
618

            unsigned long width = 0;
            unsigned long height = 0;
619
            std::string label;
620

621
622
            friend inline void serialize(const detector_window_details& item, std::ostream& out);
            friend inline void deserialize(detector_window_details& item, std::istream& in);
623
624
        };

625
626
        mmod_options() = default;

627
628
        // This kind of object detector is a sliding window detector.  The detector_windows
        // field determines how many sliding windows we will use and what the shape of each
629
630
631
632
633
        // window is.  It also determines the output label applied to each detection
        // identified by each window.  Since you will usually use the MMOD loss with an
        // image pyramid, the detector sizes also determine the size of the smallest object
        // you can detect.
        std::vector<detector_window_details> detector_windows;
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656

        // These parameters control how we penalize different kinds of mistakes.  See 
        // Max-Margin Object Detection by Davis E. King (http://arxiv.org/abs/1502.00046)
        // for further details.
        double loss_per_false_alarm = 1;
        double loss_per_missed_target = 1;

        // A detection must have an intersection-over-union value greater than this for us
        // to consider it a match against a ground truth box.
        double truth_match_iou_threshold = 0.5;

        // When doing non-max suppression, we use overlaps_nms to decide if a box overlaps
        // an already output detection and should therefore be thrown out.
        test_box_overlap overlaps_nms = test_box_overlap(0.4);

        // Any mmod_rect in the training data that has its ignore field set to true defines
        // an "ignore zone" in an image.  Any detection from that area is totally ignored
        // by the optimizer.  Therefore, this overlaps_ignore field defines how we decide
        // if a box falls into an ignore zone.  You use these ignore zones if there are
        // objects in your dataset that you are unsure if you want to detect or otherwise
        // don't care if the detector gets them or not.  
        test_box_overlap overlaps_ignore;

657
658
659
660
        // Usually the detector would be scale-invariant, and used with an image pyramid.
        // However, sometimes scale-invariance may not be desired.
        use_image_pyramid assume_image_pyramid = use_image_pyramid::yes;

661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
        // By default, the mmod loss doesn't train any bounding box regression model.  But
        // if you set use_bounding_box_regression == true then it expects the network to
        // output a tensor with detector_windows.size()*5 channels rather than just
        // detector_windows.size() channels.  The 4 extra channels per window are trained
        // to give a bounding box regression output that improves the positioning of the
        // output detection box.
        bool use_bounding_box_regression = false; 
        // When using bounding box regression, bbr_lambda determines how much you care
        // about getting the bounding box shape correct vs just getting the detector to
        // find objects.  That is, the objective function being optimized is
        // basic_mmod_loss + bbr_lambda*bounding_box_regression_loss.  So setting
        // bbr_lambda to a larger value will cause the overall loss to care more about
        // getting the bounding box shape correct.
        double bbr_lambda = 100; 

676
677
        mmod_options (
            const std::vector<std::vector<mmod_rect>>& boxes,
678
679
680
            const unsigned long target_size,      
            const unsigned long min_target_size,   
            const double min_detector_window_overlap_iou = 0.75
681
682
        );
        /*!
683
684
685
            requires
                - 0 < min_target_size <= target_size
                - 0.5 < min_detector_window_overlap_iou < 1
686
            ensures
687
688
689
                - use_image_pyramid_ == use_image_pyramid::yes
                - This function should be used when scale-invariance is desired, and
                  input_rgb_image_pyramid is therefore used as the input layer.
690
691
692
693
694
695
696
697
698
699
700
701
                - This function tries to automatically set the MMOD options to reasonable
                  values, assuming you have a training dataset of boxes.size() images, where
                  the ith image contains objects boxes[i] you want to detect.
                - The most important thing this function does is decide what detector
                  windows should be used.  This is done by finding a set of detector
                  windows that are sized such that:
                    - When slid over an image pyramid, each box in boxes will have an
                      intersection-over-union with one of the detector windows of at least
                      min_detector_window_overlap_iou.  That is, we will make sure that
                      each box in boxes could potentially be detected by one of the
                      detector windows.  This essentially comes down to picking detector
                      windows with aspect ratios similar to the aspect ratios in boxes.
702
703
704
705
                      Note that we also make sure that each box can be detected by a window
                      with the same label.  For example, if all the boxes had the same
                      aspect ratio but there were 4 different labels used in boxes then
                      there would be 4 resulting detector windows, one for each label.
706
707
708
709
710
                    - The longest edge of each detector window is target_size pixels in
                      length, unless the window's shortest side would be less than
                      min_target_size pixels in length.  In this case the shortest side
                      will be set to min_target_size length, and the other side sized to
                      preserve the aspect ratio of the window.  
Davis King's avatar
Davis King committed
711
                  This means that target_size and min_target_size control the size of the
712
713
714
715
716
                  detector windows, while the aspect ratios of the detector windows are
                  automatically determined by the contents of boxes.  It should also be
                  emphasized that the detector isn't going to be able to detect objects
                  smaller than any of the detector windows.  So consider that when setting
                  these sizes.
717
718
719
                - This function will also set the overlaps_nms tester to the most
                  restrictive tester that doesn't reject anything in boxes.
        !*/
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744

        mmod_options (
            use_image_pyramid use_image_pyramid,
            const std::vector<std::vector<mmod_rect>>& boxes,
            const double min_detector_window_overlap_iou = 0.75
        );
        /*!
            requires
                - use_image_pyramid == use_image_pyramid::no
                - 0.5 < min_detector_window_overlap_iou < 1
            ensures
                - This function should be used when scale-invariance is not desired, and
                  there is no intention to apply an image pyramid.
                - This function tries to automatically set the MMOD options to reasonable
                  values, assuming you have a training dataset of boxes.size() images, where
                  the ith image contains objects boxes[i] you want to detect.
                - The most important thing this function does is decide what detector
                  windows should be used.  This is done by finding a set of detector
                  windows that are sized such that:
                    - When slid over an image, each box in boxes will have an
                      intersection-over-union with one of the detector windows of at least
                      min_detector_window_overlap_iou.  That is, we will make sure that
                      each box in boxes could potentially be detected by one of the
                      detector windows.
                - This function will also set the overlaps_nms tester to the most
745
746
747
748
749
750
751
752
753
                  restrictive tester that doesn't reject anything in boxes.
        !*/
    };

    void serialize(const mmod_options& item, std::ostream& out);
    void deserialize(mmod_options& item, std::istream& in);

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

754
    class loss_mmod_ 
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
                This object implements the loss layer interface defined above by
                EXAMPLE_LOSS_LAYER_.  In particular, it implements the Max Margin Object
                Detection loss defined in the paper:
                    Max-Margin Object Detection by Davis E. King (http://arxiv.org/abs/1502.00046).
               
                This means you use this loss if you want to detect the locations of objects
                in images.

                It should also be noted that this loss layer requires an input layer that
                defines the following functions:
                    - image_contained_point()
                    - tensor_space_to_image_space()
                    - image_space_to_tensor_space()
                A reference implementation of them and their definitions can be found in
                the input_rgb_image_pyramid object, which is the recommended input layer to
773
                be used with loss_mmod_.
774
775
776
777
        !*/

    public:

778
779
        typedef std::vector<mmod_rect> training_label_type;
        typedef std::vector<mmod_rect> output_label_type;
780

781
        loss_mmod_(
782
783
784
785
786
787
        );
        /*!
            ensures
                - #get_options() == mmod_options()
        !*/

788
        loss_mmod_(
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
            mmod_options options_
        );
        /*!
            ensures
                - #get_options() == options_
        !*/

        const mmod_options& get_options (
        ) const;
        /*!
            ensures
                - returns the options object that defines the general behavior of this loss layer.
        !*/

        template <
            typename SUB_TYPE,
            typename label_iterator
            >
        void to_label (
            const tensor& input_tensor,
            const SUB_TYPE& sub,
            label_iterator iter,
            double adjust_threshold = 0
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::to_label() except
            it has the additional calling requirements that: 
                - sub.get_output().k() == 1
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
            Also, the output labels are std::vectors of mmod_rects where, for each mmod_rect R,
            we have the following interpretations:
                - R.rect == the location of an object in the image.
                - R.detection_confidence the score for the object, the bigger the score the
                  more confident the detector is that an object is really there.  Only
                  objects with a detection_confidence > adjust_threshold are output.  So if
                  you want to output more objects (that are also of less confidence) you
                  can call to_label() with a smaller value of adjust_threshold.
                - R.ignore == false (this value is unused by to_label()).
        !*/

        template <
            typename const_label_iterator,
            typename SUBNET
            >
        double compute_loss_value_and_gradient (
            const tensor& input_tensor,
            const_label_iterator truth, 
            SUBNET& sub
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::compute_loss_value_and_gradient() 
            except it has the additional calling requirements that: 
                - sub.get_output().k() == 1
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
            Also, the loss value returned is roughly equal to the average number of
            mistakes made per image.  This is the sum of false alarms and missed
            detections, weighted by the loss weights for these types of mistakes specified
            in the mmod_options.
        !*/
    };

    template <typename SUBNET>
853
    using loss_mmod = add_loss_layer<loss_mmod_, SUBNET>;
854

855
856
857
858
859
860
861
862
863
// ----------------------------------------------------------------------------------------

    class loss_metric_ 
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
                This object implements the loss layer interface defined above by
                EXAMPLE_LOSS_LAYER_.  In particular, it allows you to learn to map objects
                into a vector space where objects sharing the same class label are close to
Davis King's avatar
Davis King committed
864
                each other, while objects with different labels are far apart.   
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882

                To be specific, it optimizes the following loss function which considers
                all pairs of objects in a mini-batch and computes a different loss depending 
                on their respective class labels.  So if objects A1 and A2 in a mini-batch
                share the same class label then their contribution to the loss is:
                    max(0, length(A1-A2)-get_distance_threshold() + get_margin())

                While if A1 and B1 have different class labels then their contribution to
                the loss function is:
                    max(0, get_distance_threshold()-length(A1-B1) + get_margin())

                Therefore, this loss layer optimizes a version of the hinge loss.
                Moreover, the loss is trying to make sure that all objects with the same
                label are within get_distance_threshold() distance of each other.
                Conversely, if two objects have different labels then they should be more
                than get_distance_threshold() distance from each other in the learned
                embedding.  So this loss function gives you a natural decision boundary for
                deciding if two objects are from the same class.
Davis King's avatar
Davis King committed
883
884
885
886
887
888
889
890

                Finally, the loss balances the number of negative pairs relative to the
                number of positive pairs.  Therefore, if there are N pairs that share the
                same identity in a mini-batch then the algorithm will only include the N
                worst non-matching pairs in the loss.  That is, the algorithm performs hard
                negative mining on the non-matching pairs.  This is important since there
                are in general way more non-matching pairs than matching pairs.  So to
                avoid imbalance in the loss this kind of hard negative mining is useful.
891
892
893
894
895
896
        !*/
    public:

        typedef unsigned long training_label_type;
        typedef matrix<float,0,1> output_label_type;

897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
        loss_metric_(
        );
        /*!
            ensures
                - #get_margin() == 0.04
                - #get_distance_threshold() == 0.6
        !*/

        loss_metric_(
            float margin,
            float dist_thresh
        );
        /*!
            requires
                - margin > 0
                - dist_thresh > 0
            ensures
                - #get_margin() == margin
                - #get_distance_threshold() == dist_thresh
        !*/

918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
        template <
            typename SUB_TYPE,
            typename label_iterator
            >
        void to_label (
            const tensor& input_tensor,
            const SUB_TYPE& sub,
            label_iterator iter
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::to_label() except
            it has the additional calling requirements that: 
                - sub.get_output().nr() == 1
                - sub.get_output().nc() == 1
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
            This loss expects the network to produce a single vector (per sample) as
            output.  This vector is the learned embedding.  Therefore, to_label() just
            copies these output vectors from the network into the output label_iterators
            given to this function, one for each sample in the input_tensor.
        !*/

940
        float get_margin() const; 
941
942
943
944
945
946
        /*!
            ensures
                - returns the margin value used by the loss function.  See the discussion
                  in WHAT THIS OBJECT REPRESENTS for details.
        !*/

947
        float get_distance_threshold() const; 
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
        /*!
            ensures
                - returns the distance threshold value used by the loss function.  See the discussion
                  in WHAT THIS OBJECT REPRESENTS for details.
        !*/

        template <
            typename const_label_iterator,
            typename SUBNET
            >
        double compute_loss_value_and_gradient (
            const tensor& input_tensor,
            const_label_iterator truth, 
            SUBNET& sub
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::compute_loss_value_and_gradient() 
            except it has the additional calling requirements that: 
                - sub.get_output().nr() == 1
                - sub.get_output().nc() == 1
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
        !*/

    };

    template <typename SUBNET>
    using loss_metric = add_loss_layer<loss_metric_, SUBNET>;

Davis King's avatar
Davis King committed
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
// ----------------------------------------------------------------------------------------

    class loss_ranking_
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
                This object implements the loss layer interface defined above by
                EXAMPLE_LOSS_LAYER_.  In particular, it implements the pairwise ranking
                loss described in the paper:
                    Optimizing Search Engines using Clickthrough Data by Thorsten Joachims

                This is the same loss function used by the dlib::svm_rank_trainer object.
                Therefore, it is generally appropriate when you have a two class problem
                and you want to learn a function that ranks one class before the other.  

                So for example, suppose you have two classes of data.  Objects of type A
                and objects of type B.  Moreover, suppose that you want to sort the objects
                so that A objects always come before B objects.  This loss will help you
                learn a function that assigns a real number to each object such that A
                objects get a larger number assigned to them than B objects.  This lets you
                then sort the objects according to the output of the neural network and
                obtain the desired result of having A objects come before B objects.

                The training labels should be positive values for objects you want to get
                high scores and negative for objects that should get small scores.  So
                relative to our A/B example, you would give A objects labels of +1 and B
                objects labels of -1.  This should cause the learned network to give A
                objects large positive values and B objects negative values.


                Finally, the specific loss function is:
                    For all pairs of positive vs negative training examples A_i and B_j respectively:
                      sum_ij:  max(0, B_i - A_j + margin_ij)
                where margin_ij = the label for A_j minus the label for B_i.  If you
                always use +1 and -1 labels then the margin is always 2.  However, this
                formulation allows you to give certain training samples different weight by
                adjusting the training labels appropriately.  
        !*/

    public:

        typedef float training_label_type;
        typedef float output_label_type;

        template <
            typename SUB_TYPE,
            typename label_iterator
            >
        void to_label (
            const tensor& input_tensor,
            const SUB_TYPE& sub,
            label_iterator iter
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::to_label() except
            it has the additional calling requirements that:
                - sub.get_output().nr() == 1
                - sub.get_output().nc() == 1
                - sub.get_output().k() == 1
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
            and the output label is the predicted ranking score.
        !*/

        template <
            typename const_label_iterator,
            typename SUBNET
            >
        double compute_loss_value_and_gradient (
            const tensor& input_tensor,
            const_label_iterator truth,
            SUBNET& sub
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::compute_loss_value_and_gradient()
            except it has the additional calling requirements that:
                - sub.get_output().nr() == 1
                - sub.get_output().nc() == 1
                - sub.get_output().k() == 1
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
        !*/

    };

    template <typename SUBNET>
    using loss_ranking = add_loss_layer<loss_ranking_, SUBNET>;

1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
// ----------------------------------------------------------------------------------------

    class loss_epsilon_insensitive_
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
                This object implements the loss layer interface defined above by
                EXAMPLE_LOSS_LAYER_.  In particular, it implements the epsilon insensitive
                loss, which is appropriate for regression problems.  In particular, this
                loss function is;
                    loss(y1,y2) = abs(y1-y2)<epsilon ? 0 : abs(y1-y2)-epsilon

                Therefore, the loss is basically just the abs() loss except there is a dead
                zone around zero, causing the loss to not care about mistakes of magnitude
                smaller than epsilon.
        !*/
    public:

        typedef float training_label_type;
        typedef float output_label_type;

        loss_epsilon_insensitive_(
        ) = default;
        /*!
            ensures
                - #get_epsilon() == 1
        !*/

        loss_epsilon_insensitive_(
            double eps
        );
        /*!
            requires
                - eps >= 0
            ensures
                - #get_epsilon() == eps
        !*/

        double get_epsilon (
        ) const;
        /*!
            ensures
                - returns the epsilon value used in the loss function.  Mistakes in the
                  regressor smaller than get_epsilon() are ignored by the loss function.
        !*/

        void set_epsilon(
            double eps
        );
        /*!
            requires
                - eps >= 0
            ensures
                - #get_epsilon() == eps
        !*/

        template <
            typename SUB_TYPE,
            typename label_iterator
            >
        void to_label (
            const tensor& input_tensor,
            const SUB_TYPE& sub,
            label_iterator iter
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::to_label() except
            it has the additional calling requirements that:
                - sub.get_output().nr() == 1
                - sub.get_output().nc() == 1
                - sub.get_output().k() == 1
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
            and the output label is the predicted continuous variable.
        !*/

        template <
            typename const_label_iterator,
            typename SUBNET
            >
        double compute_loss_value_and_gradient (
            const tensor& input_tensor,
            const_label_iterator truth,
            SUBNET& sub
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::compute_loss_value_and_gradient()
            except it has the additional calling requirements that:
                - sub.get_output().nr() == 1
                - sub.get_output().nc() == 1
                - sub.get_output().k() == 1
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
        !*/

    };

    template <typename SUBNET>
    using loss_epsilon_insensitive = add_loss_layer<loss_epsilon_insensitive_, SUBNET>;

Davis King's avatar
Davis King committed
1165
1166
// ----------------------------------------------------------------------------------------

1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
    class loss_mean_squared_
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
                This object implements the loss layer interface defined above by
                EXAMPLE_LOSS_LAYER_.  In particular, it implements the mean squared loss, which is
                appropriate for regression problems.
        !*/
    public:

        typedef float training_label_type;
        typedef float output_label_type;

        template <
            typename SUB_TYPE,
            typename label_iterator
            >
        void to_label (
            const tensor& input_tensor,
            const SUB_TYPE& sub,
            label_iterator iter
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::to_label() except
            it has the additional calling requirements that:
                - sub.get_output().nr() == 1
                - sub.get_output().nc() == 1
                - sub.get_output().k() == 1
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
            and the output label is the predicted continuous variable.
        !*/

        template <
            typename const_label_iterator,
            typename SUBNET
            >
        double compute_loss_value_and_gradient (
            const tensor& input_tensor,
            const_label_iterator truth,
            SUBNET& sub
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::compute_loss_value_and_gradient()
            except it has the additional calling requirements that:
                - sub.get_output().nr() == 1
                - sub.get_output().nc() == 1
                - sub.get_output().k() == 1
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
        !*/

    };

    template <typename SUBNET>
    using loss_mean_squared = add_loss_layer<loss_mean_squared_, SUBNET>;

1224
1225
1226
1227
1228
1229
1230
// ----------------------------------------------------------------------------------------

    class loss_mean_squared_multioutput_
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
                This object implements the loss layer interface defined above by
Davis King's avatar
Davis King committed
1231
1232
1233
1234
                EXAMPLE_LOSS_LAYER_.  In particular, it implements the mean squared loss,
                which is appropriate for regression problems.  It is basically just like
                loss_mean_squared_ except that it lets you define multiple outputs instead
                of just 1.
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
        !*/
    public:

        typedef matrix<float> training_label_type;
        typedef matrix<float> output_label_type;

        template <
            typename SUB_TYPE,
            typename label_iterator
            >
        void to_label (
            const tensor& input_tensor,
            const SUB_TYPE& sub,
            label_iterator iter
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::to_label() except
            it has the additional calling requirements that:
                - sub.get_output().nr() == 1
                - sub.get_output().nc() == 1
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
            and the output label is the predicted continuous variable.
        !*/

        template <
            typename const_label_iterator,
            typename SUBNET
            >
        double compute_loss_value_and_gradient (
            const tensor& input_tensor,
            const_label_iterator truth,
            SUBNET& sub
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::compute_loss_value_and_gradient()
            except it has the additional calling requirements that:
                - sub.get_output().nr() == 1
                - sub.get_output().nc() == 1
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
                - (*(truth + idx)).nc() == 1 for all idx such that 0 <= idx < sub.get_output().num_samples()
                - (*(truth + idx)).nr() == sub.get_output().k() for all idx such that 0 <= idx < sub.get_output().num_samples()
        !*/

    };

    template <typename SUBNET>
    using loss_mean_squared_multioutput = add_loss_layer<loss_mean_squared_multioutput_, SUBNET>;

1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
// ----------------------------------------------------------------------------------------

    class loss_multiclass_log_per_pixel_
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
                This object implements the loss layer interface defined above by
                EXAMPLE_LOSS_LAYER_.  In particular, it implements the multiclass logistic
                regression loss (e.g. negative log-likelihood loss), which is appropriate
                for multiclass classification problems.  It is basically just like
1295
1296
1297
                loss_multiclass_log_ except that it lets you define matrix outputs instead
                of scalar outputs.  It should be useful, for example, in semantic
                segmentation where we want to classify each pixel of an image.
1298
1299
1300
        !*/
    public:

1301
1302
1303
1304
1305
        // In semantic segmentation, if you don't know the ground-truth of some pixel,
        // set the label of that pixel to this value. When you do so, the pixel will be
        // ignored when computing gradients.
        static const uint16_t label_to_ignore = std::numeric_limits<uint16_t>::max();

1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
        // In semantic segmentation, 65535 classes ought to be enough for anybody.
        typedef matrix<uint16_t> training_label_type;
        typedef matrix<uint16_t> output_label_type;

        template <
            typename SUB_TYPE,
            typename label_iterator
            >
        void to_label (
            const tensor& input_tensor,
            const SUB_TYPE& sub,
            label_iterator iter
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::to_label() except
            it has the additional calling requirements that:
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
            and the output label is the predicted class for each classified element.  The number
            of possible output classes is sub.get_output().k().
        !*/

        template <
            typename const_label_iterator,
            typename SUBNET
            >
        double compute_loss_value_and_gradient (
            const tensor& input_tensor,
            const_label_iterator truth,
            SUBNET& sub
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::compute_loss_value_and_gradient()
            except it has the additional calling requirements that:
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
1342
                - all values pointed to by truth are < sub.get_output().k() or are equal to label_to_ignore.
1343
1344
1345
1346
1347
1348
1349
        !*/

    };

    template <typename SUBNET>
    using loss_multiclass_log_per_pixel = add_loss_layer<loss_multiclass_log_per_pixel_, SUBNET>;

1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
// ----------------------------------------------------------------------------------------

    class loss_multiclass_log_per_pixel_weighted_
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
                This object implements the loss layer interface defined above by
                EXAMPLE_LOSS_LAYER_.  In particular, it implements the multiclass logistic
                regression loss (e.g. negative log-likelihood loss), which is appropriate
                for multiclass classification problems.  It is basically just like
                loss_multiclass_log_per_pixel_ except that it lets you define per-pixel
                weights, which may be useful e.g. if you want to emphasize rare classes
                while training.  (If the classification problem is difficult, a flat weight
                structure may lead the network to always predict the most common label, in
                particular if the degree of imbalance is high.  To emphasize a certain
                class or classes, simply increase the weights of the corresponding pixels,
                relative to the weights of the other pixels.)

                Note that if you set the weight to 0 whenever a pixel's label is equal to
                loss_multiclass_log_per_pixel_::label_to_ignore, and to 1 otherwise, then
                you essentially get loss_multiclass_log_per_pixel_ as a special case.
        !*/
    public:

        struct weighted_label
        {
            /*!
                WHAT THIS OBJECT REPRESENTS
                    This object represents the truth label of a single pixel, together with
                    an associated weight (the higher the weight, the more emphasis the
                    corresponding pixel is given during the training).
            !*/

            weighted_label();
            weighted_label(uint16_t label, float weight = 1.f);

            // The ground-truth label. In semantic segmentation, 65536 classes ought to be
            // enough for anybody.
            uint16_t label = 0;

            // The weight of the corresponding pixel.
            float weight = 1.f;
        };

        typedef matrix<weighted_label> training_label_type;
        typedef matrix<uint16_t> output_label_type;

        template <
            typename SUB_TYPE,
            typename label_iterator
            >
        void to_label (
            const tensor& input_tensor,
            const SUB_TYPE& sub,
            label_iterator iter
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::to_label() except
            it has the additional calling requirements that:
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
            and the output label is the predicted class for each classified element.  The number
            of possible output classes is sub.get_output().k().
        !*/

        template <
            typename const_label_iterator,
            typename SUBNET
            >
        double compute_loss_value_and_gradient (
            const tensor& input_tensor,
            const_label_iterator truth,
            SUBNET& sub
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::compute_loss_value_and_gradient()
            except it has the additional calling requirements that:
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
                - all labels pointed to by truth are < sub.get_output().k(), or the corresponding weight
                  is zero.
        !*/

    };

    template <typename SUBNET>
    using loss_multiclass_log_per_pixel_weighted = add_loss_layer<loss_multiclass_log_per_pixel_weighted_, SUBNET>;

1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
// ----------------------------------------------------------------------------------------

    class loss_mean_squared_per_pixel_
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
                This object implements the loss layer interface defined above by
                EXAMPLE_LOSS_LAYER_.  In particular, it implements the mean squared loss,
                which is appropriate for regression problems.  It is basically just like
                loss_mean_squared_multioutput_ except that it lets you define matrix or
                image outputs, instead of vector.
        !*/
    public:

        typedef matrix<float> training_label_type;
        typedef matrix<float> output_label_type;

        template <
            typename SUB_TYPE,
            typename label_iterator
            >
        void to_label (
            const tensor& input_tensor,
            const SUB_TYPE& sub,
            label_iterator iter
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::to_label() except
            it has the additional calling requirements that:
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
            and the output labels are the predicted continuous variables.
        !*/

        template <
            typename const_label_iterator,
            typename SUBNET
            >
        double compute_loss_value_and_gradient (
            const tensor& input_tensor,
            const_label_iterator truth,
            SUBNET& sub
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::compute_loss_value_and_gradient()
            except it has the additional calling requirements that:
                - sub.get_output().k() == 1
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
                - for all idx such that 0 <= idx < sub.get_output().num_samples():
                    - sub.get_output().nr() == (*(truth + idx)).nr()
                    - sub.get_output().nc() == (*(truth + idx)).nc()
        !*/
    };

    template <typename SUBNET>
    using loss_mean_squared_per_pixel = add_loss_layer<loss_mean_squared_per_pixel_, SUBNET>;

Davis King's avatar
Davis King committed
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
// ----------------------------------------------------------------------------------------

    class loss_dot_ 
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
                This object implements the loss layer interface defined above by
                EXAMPLE_LOSS_LAYER_.  In particular, selecting this loss means you want
                maximize the dot product between the output of a network and a set of
                training vectors.  The loss is therefore the negative dot product.  To be
                very specific, if X is the output vector of a network and Y is a training
                label (also a vector), then the loss for this training sample is: -dot(X,Y)
        !*/

    public:

        typedef matrix<float,0,1> training_label_type;
        typedef matrix<float,0,1> output_label_type;

        template <
            typename SUB_TYPE,
            typename label_iterator
            >
        void to_label (
            const tensor& input_tensor,
            const SUB_TYPE& sub,
            label_iterator iter
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::to_label() except
            it has the additional calling requirements that:
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
            and the output labels are simply the final network outputs stuffed into a
            vector.  To be very specific, the output is the following for all valid i:
                *(iter+i) == trans(rowm(mat(sub.get_output()),i))
        !*/


        template <
            typename const_label_iterator,
            typename SUBNET
            >
        double compute_loss_value_and_gradient (
            const tensor& input_tensor,
            const_label_iterator truth, 
            SUBNET& sub
        ) const;
        /*!
            This function has the same interface as EXAMPLE_LOSS_LAYER_::compute_loss_value_and_gradient()
            except it has the additional calling requirements that:
                - sub.get_output().num_samples() == input_tensor.num_samples()
                - sub.sample_expansion_factor() == 1
                - Let NETWORK_OUTPUT_DIMS == sub.get_output().size()/sub.get_output().num_samples()
                - for all idx such that 0 <= idx < sub.get_output().num_samples():
                    - NETWORK_OUTPUT_DIMS == (*(truth + idx)).size()
        !*/
    };

    template <typename SUBNET>
    using loss_dot = add_loss_layer<loss_dot_, SUBNET>;

1558
1559
// ----------------------------------------------------------------------------------------

Davis King's avatar
Davis King committed
1560
1561
1562
1563
}

#endif // DLIB_DNn_LOSS_ABSTRACT_H_