Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / ops / argmax.py
1 """
2  Copyright (c) 2017-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 logging as log
18 import numpy as np
19
20 from mo.front.caffe.extractors.utils import get_canonical_axis_index
21 from mo.graph.graph import Node, Graph
22 from mo.ops.op import Op, PermuteAttrs
23
24
25 class ArgMaxOp(Op):
26     op = 'ArgMax'
27
28     def __init__(self, graph: Graph, attrs: dict):
29         mandatory_props = {
30             'type': __class__.op,
31             'op': __class__.op,
32             'infer': ArgMaxOp.argmax_infer,
33             'in_ports_count': 2,
34             'out_ports_count': 1,
35         }
36         super().__init__(graph, mandatory_props, attrs)
37
38     def supported_attrs(self):
39         return [
40             'out_max_val',
41             'top_k',
42             'axis',
43         ]
44
45     @staticmethod
46     def argmax_infer(node: Node):
47         shape = node.in_node(0).shape
48         if shape is None:
49             return
50
51         # there are two inputs in TensorFlow. The second input is the axis for ArgMax
52         if len(node.in_nodes()) == 2:
53             if node.in_node(1).value is None:
54                 log.debug('The second argument to ArgMax is None')
55                 return
56             node.axis = node.in_node(1).value.item()
57             # remove the unnecessary input
58             node.graph.remove_edge(node.in_node(1).id, node.id)
59
60         num_top_axes = shape.size
61         if num_top_axes < 3:
62             num_top_axes = 3
63
64         out_shape = np.ones(num_top_axes, dtype=int)
65
66         if node.has_valid('axis'):
67             axis = get_canonical_axis_index(shape, node.axis)
68             node.axis = axis
69             out_shape = np.array(shape)
70             out_shape[axis] = node.top_k
71             PermuteAttrs.create_permute_attrs(node, attrs=[('axis', 'input:0')])
72         else:
73             out_shape[0] = shape[0]
74             out_shape[2] = node.top_k
75             if node.out_max_val:
76                 out_shape[1] = 2
77
78         node.out_node().shape = out_shape