Caffe2 - Python API
A deep learning, cross platform ML framework
fc.py
1 # Copyright (c) 2016-present, Facebook, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 ##############################################################################
15 
16 ## @package fc
17 # Module caffe2.python.layers.fc
18 from __future__ import absolute_import
19 from __future__ import division
20 from __future__ import print_function
21 from __future__ import unicode_literals
22 
23 from caffe2.python import schema
24 from caffe2.python.layers.layers import ModelLayer
25 from caffe2.python.layers.sampling_trainable_mixin import SamplingTrainableMixin
26 import math
27 import numpy as np
28 
29 
31 
32  def __init__(self, model, input_record, output_dims, weight_init=None,
33  bias_init=None, weight_optim=None, bias_optim=None, name='fc',
34  weight_reg=None, bias_reg=None, **kwargs):
35  super(FC, self).__init__(model, name, input_record, **kwargs)
36  assert isinstance(input_record, schema.Scalar), (
37  "Incorrect input type {}".format(input_record))
38  assert len(input_record.field_types()[0].shape) > 0, (
39  "FC expects limited dimensions of the input tensor")
40 
41  input_dims = input_record.field_types()[0].shape[0]
42  assert input_dims > 0, (
43  "FC expects input dimensions > 0, got {}".format(input_dims))
44 
45  scale = math.sqrt(1.0 / input_dims)
46  weight_init = weight_init if weight_init else (
47  'UniformFill', {'min': -scale, 'max': scale})
48  bias_init = bias_init if bias_init else (
49  'UniformFill', {'min': -scale, 'max': scale})
50 
51  self.w = self.create_param(param_name='w',
52  shape=[output_dims, input_dims],
53  initializer=weight_init,
54  optimizer=weight_optim,
55  regularizer=weight_reg)
56 
57  self.b = self.create_param(param_name='b',
58  shape=[output_dims, ],
59  initializer=bias_init,
60  optimizer=bias_optim,
61  regularizer=bias_reg)
62 
64  (np.float32, (output_dims, )),
65  self.get_next_blob_reference('output')
66  )
67 
68  def _add_ops(self, net, params):
69  net.FC(self.input_record.field_blobs() + params,
70  self.output_schema.field_blobs(), **self.kwargs)
71 
72  @property
73  def param_blobs(self):
74  return [self.w, self.b]
def get_next_blob_reference(self, name)
Definition: layers.py:352
def create_param(self, param_name, shape, initializer, optimizer, ps_param=None, regularizer=None)
Definition: layers.py:337