Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / mo / ops / activation.py
1 """
2  Copyright (c) 2018-2019 Intel Corporation
3
4  Licensed under the Apache License, Version 2.0 (the "License");
5  you may not use this file except in compliance with the License.
6  You may obtain a copy of the License at
7
8       http://www.apache.org/licenses/LICENSE-2.0
9
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15 """
16
17 import numpy as np
18
19 from mo.front.common.partial_infer.eltwise import eltwise_infer
20 from mo.graph.graph import Node, Graph
21 from mo.ops.op import Op
22
23
24 class Activation(Op):
25     op = 'Activation'
26
27     @staticmethod
28     def elu(values, alpha):
29         values = values.astype(float)
30         for index, x in np.ndenumerate(values):
31             if x < 0:
32                 values[index] = alpha * (np.exp(x) - 1)
33         return values
34
35     operations = {
36         'tanh': lambda x: np.tanh(x),
37         'elu': lambda x, alpha: Activation.elu(x, alpha),
38         'sigmoid': lambda x: 1 / (1 + np.exp(-x)),
39         'relu6': lambda x: np.maximum(0, np.minimum(x, 6)),
40         'exp': lambda x: np.exp(x),
41     }
42
43     def __init__(self, graph: Graph, attrs: dict):
44         super().__init__(graph, {
45             'type': __class__.op,
46             'op': __class__.op,
47             'infer': Activation.infer,
48             'in_ports_count': 1,
49             'out_ports_count': 1,
50         }, attrs)
51
52     @classmethod
53     def infer(cls, node: Node):
54         if node.operation == 'elu':
55             # Set default value for alpha in case when it is not specified
56             node['alpha'] = node.alpha if node.has_valid('alpha') else 1.0
57             return eltwise_infer(node, cls.operations[node.operation], alpha=node.alpha)
58         return eltwise_infer(node, cls.operations[node.operation])
59
60     def supported_attrs(self):
61         return ['operation']
62
63     def backend_attrs(self):
64         return [('type', 'operation'), 'alpha']  # operation --> type