• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2019 Huawei Technologies Co., Ltd
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
16import random
17from functools import reduce
18import numpy as np
19import pytest
20
21import mindspore.context as context
22import mindspore.nn as nn
23from mindspore import Tensor
24from mindspore.common import dtype as mstype
25import mindspore.ops as ops
26
27context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
28
29
30class NetArgmax(nn.Cell):
31    def __init__(self, axis=0):
32        super(NetArgmax, self).__init__()
33        self.argmax = ops.Argmax(axis=axis, output_type=mstype.int32)
34
35    def construct(self, x):
36        return self.argmax(x)
37
38
39@pytest.mark.level0
40@pytest.mark.platform_x86_cpu
41@pytest.mark.env_onecard
42def test_argmax_1d():
43    x = Tensor(np.array([1., 20., 5.]).astype(np.float32))
44    Argmax = NetArgmax(axis=0)
45    output = Argmax(x)
46    expect = np.array([1]).astype(np.float32)
47    assert (output.asnumpy() == expect).all()
48
49
50@pytest.mark.level0
51@pytest.mark.platform_x86_cpu
52@pytest.mark.env_onecard
53def test_argmax_2d():
54    x = Tensor(np.array([[1., 20., 5.],
55                         [67., 8., 9.],
56                         [130., 24., 15.]]).astype(np.float32))
57    Argmax_axis_0 = NetArgmax(axis=0)
58    output = Argmax_axis_0(x)
59    expect = np.array([2, 2, 2]).astype(np.float32)
60    assert (output.asnumpy() == expect).all()
61    Argmax_axis_1 = NetArgmax(axis=1)
62    output = Argmax_axis_1(x)
63    expect = np.array([1, 0, 0]).astype(np.float32)
64    assert (output.asnumpy() == expect).all()
65
66
67@pytest.mark.level0
68@pytest.mark.platform_x86_cpu
69@pytest.mark.env_onecard
70def test_argmax_high_dims():
71    for dim in range(3, 10):
72        shape = np.random.randint(1, 10, size=dim)
73        x = np.random.randn(reduce(lambda x, y: x * y, shape)).astype(np.float32)
74        x = x.reshape(shape)
75
76        rnd_axis = random.randint(-dim + 1, dim - 1)
77        Argmax = NetArgmax(axis=rnd_axis)
78        ms_output = Argmax(Tensor(x))
79        np_output = np.argmax(x, axis=rnd_axis)
80        assert (ms_output.asnumpy() == np_output).all()
81