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, **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  assert schema.is_schema_subset(
27  ('pos_prediction', schema.Scalar()),
28  ('neg_prediction', schema.List(np.float32)),
29  ),
30  input_record
31  )
32  self.tags.update([Tags.EXCLUDE_FROM_PREDICTION])
34  np.float32,
35  self.get_next_blob_reference('output'))
36 
37  def add_ops(self, net):
38  neg_score = self.input_record.neg_prediction['values']()
39 
40  pos_score = net.LengthsTile(
41  [
42  self.input_record.pos_prediction(),
43  self.input_record.neg_prediction['lengths']()
44  ],
45  net.NextScopedBlob('pos_score_repeated')
46  )
47  const_1 = net.ConstantFill(
48  neg_score,
49  net.NextScopedBlob('const_1'),
50  value=1,
51  dtype=core.DataType.INT32
52  )
53  rank_loss = net.MarginRankingCriterion(
54  [pos_score, neg_score, const_1],
55  net.NextScopedBlob('rank_loss'),
56  margin=self._margin,
57  )
58  net.SumElements(rank_loss, self.output_schema.field_blobs())