Caffe2 - Python API
A deep learning, cross platform ML framework
uniform_sampling.py
1 ## @package uniform_sampling
2 # Module caffe2.python.layers.uniform_sampling
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 import numpy as np
9 
10 from caffe2.python import core, schema
11 from caffe2.python.layers.layers import ModelLayer
12 
13 
15  """
16  Uniform sampling `num_samples - len(input_record)` unique elements from the
17  range [0, num_elements). `samples` is the concatenation of input_record and
18  the samples. input_record is expected to be unique.
19  """
20 
21  def __init__(
22  self,
23  model,
24  input_record,
25  num_samples,
26  num_elements,
27  name='uniform_sampling',
28  **kwargs
29  ):
30  super(UniformSampling, self).__init__(
31  model, name, input_record, **kwargs
32  )
33 
34  assert num_elements > num_samples > 0
35  assert isinstance(input_record, schema.Scalar)
36 
37  self.num_elements = num_elements
38 
39  num_examples_init = ('GivenTensorInt64Fill',
40  {'values': [num_samples]})
41  self.num_samples = self.create_param(param_name='num_examples',
42  shape=(1,),
43  initializer=num_examples_init,
44  optimizer=model.NoOptim)
45 
46  sampling_blob_init = ('ConstantFill',
47  {'value': float(num_samples) / num_elements,
48  'dtype': core.DataType.FLOAT})
49  self.sampling_prob = self.create_param(param_name='prob',
50  shape=(num_samples,),
51  initializer=sampling_blob_init,
52  optimizer=model.NoOptim)
53 
55  (
56  'samples', schema.Scalar(
57  np.int32, self.get_next_blob_reference("samples")
58  )
59  ),
60  ('sampling_prob', schema.Scalar(np.float32, self.sampling_prob)),
61  )
62 
63  def add_ops(self, net):
64  net.StopGradient(self.sampling_prob, self.sampling_prob)
65 
66  shape = net.Shape([self.input_record()], net.NextScopedBlob("shape"))
67  shape = net.Sub([self.num_samples, shape], shape)
68  samples = net.UniqueUniformFill(
69  [shape, self.input_record()],
70  net.NextScopedBlob("samples_before_concat"),
71  min=0,
72  max=self.num_elements - 1,
73  input_as_shape=True
74  )
75 
76  net.Concat(
77  [self.input_record(), samples],
78  [self.output_schema.samples(), net.NextScopedBlob("split_info")],
79  axis=0
80  )
81  net.StopGradient(
82  self.output_schema.samples(), self.output_schema.samples()
83  )
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