Caffe2 - Python API
A deep learning, cross platform ML framework
build_index.py
1 from __future__ import absolute_import
2 from __future__ import division
3 from __future__ import print_function
4 from __future__ import unicode_literals
5 
6 import numpy as np
7 
8 from caffe2.python import core, schema
9 from caffe2.python.layers.layers import ModelLayer
10 
11 
13  """
14  This layer aims to build a mapping from raw keys to indices within [0, max_index).
15  The mapping is continuously built during training. The mapping will be frozen during
16  evaluation and prediction. Unseen keys will be assigned to index 0.
17  """
18 
19  def __init__(
20  self, model,
21  input_record,
22  max_index,
23  name='map_to_range',
24  **kwargs
25  ):
26  super(MapToRange, self).__init__(model, name, input_record, **kwargs)
27 
28  assert max_index > 0
29  assert isinstance(input_record, schema.Scalar)
30 
31  self.max_index = max_index
32 
33  self.handler = self.create_param(
34  param_name='handler',
35  shape=None,
36  initializer=('LongIndexCreate', {'max_elements': self.max_index}),
37  optimizer=model.NoOptim
38  )
39 
41  ('indices', schema.Scalar(
42  np.int64, self.get_next_blob_reference("indices")
43  )),
44  ('handler', schema.Scalar(
45  np.void, self.handler
46  )),
47  )
48 
49  def add_train_ops(self, net):
50  if self.input_record.field_type().base != np.int64:
51  keys = net.Cast(
52  self.input_record(),
53  net.NextScopedBlob("indices_before_mapping"),
54  to=core.DataType.INT64
55  )
56  else:
57  keys = self.input_record()
58 
59  # Load keys into indices
60  indices = net.IndexGet([self.handler, keys],
61  self.output_schema.indices())
62 
63  net.StopGradient(indices, indices)
64 
65  def add_eval_ops(self, net):
66  net.IndexFreeze(self.handler, self.handler)
67  self.add_train_ops(net)
68 
69  def add_ops(self, net):
70  self.add_eval_ops(net)
def get_next_blob_reference(self, name)
Definition: layers.py:349
def create_param(self, param_name, shape, initializer, optimizer, ps_param=None, regularizer=None)
Definition: layers.py:334