Caffe2 - Python API
A deep learning, cross platform ML framework
margin_rank_loss.py
1 ## @package random_neg_rank_loss
2 # Module caffe2.python.layers.random_neg_rank_loss
3 from __future__ import absolute_import
4 from __future__ import division
5 from __future__ import print_function
6 from __future__ import unicode_literals
7 
8 from caffe2.python import schema, core
9 from caffe2.python.layers.layers import (
10  ModelLayer,
11 )
12 from caffe2.python.layers.tags import (
13  Tags
14 )
15 import numpy as np
16 
17 
18 class MarginRankLoss(ModelLayer):
19 
20  def __init__(self, model, input_record, name='margin_rank_loss',
21  margin=0.1, average_loss=False, **kwargs):
22  super(MarginRankLoss, self).__init__(model, name, input_record, **kwargs)
23  assert margin >= 0, ('For hinge loss, margin should be no less than 0')
24  self._margin = margin
25  self._average_loss = average_loss
26  assert schema.is_schema_subset(
28  ('pos_prediction', schema.Scalar()),
29  ('neg_prediction', schema.List(np.float32)),
30  ),
31  input_record
32  )
33  self.tags.update([Tags.EXCLUDE_FROM_PREDICTION])
35  np.float32,
36  self.get_next_blob_reference('output'))
37 
38  def add_ops(self, net):
39  neg_score = self.input_record.neg_prediction['values']()
40 
41  pos_score = net.LengthsTile(
42  [
43  self.input_record.pos_prediction(),
44  self.input_record.neg_prediction['lengths']()
45  ],
46  net.NextScopedBlob('pos_score_repeated')
47  )
48  const_1 = net.ConstantFill(
49  neg_score,
50  net.NextScopedBlob('const_1'),
51  value=1,
52  dtype=core.DataType.INT32
53  )
54  rank_loss = net.MarginRankingCriterion(
55  [pos_score, neg_score, const_1],
56  net.NextScopedBlob('rank_loss'),
57  margin=self._margin,
58  )
59  if self._average_loss:
60  net.AveragedLoss(rank_loss, self.output_schema.field_blobs())
61  else:
62  net.ReduceFrontSum(rank_loss, self.output_schema.field_blobs())