1# Copyright 2020 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"""test topk""" 16import math 17import numpy as np 18import pytest 19 20from mindspore import Tensor 21from mindspore.nn.metrics import TopKCategoricalAccuracy, Top1CategoricalAccuracy, Top5CategoricalAccuracy 22 23 24def test_type_topk(): 25 with pytest.raises(TypeError): 26 TopKCategoricalAccuracy(2.1) 27 28 29def test_value_topk(): 30 with pytest.raises(ValueError): 31 TopKCategoricalAccuracy(-1) 32 33 34def test_input_topk(): 35 x = Tensor(np.array([[0.2, 0.5, 0.3, 0.6, 0.2], 36 [0.3, 0.1, 0.5, 0.1, 0.], 37 [0.9, 0.6, 0.2, 0.01, 0.3]])) 38 topk = TopKCategoricalAccuracy(3) 39 topk.clear() 40 with pytest.raises(ValueError): 41 topk.update(x) 42 43 44def test_topk(): 45 """test_topk""" 46 x = Tensor(np.array([[0.2, 0.5, 0.3, 0.6, 0.2], 47 [0.1, 0.35, 0.5, 0.2, 0.], 48 [0.9, 0.6, 0.2, 0.01, 0.3]])) 49 y = Tensor(np.array([2, 0, 1])) 50 y2 = Tensor(np.array([[0, 0, 1, 0, 0], 51 [1, 0, 0, 0, 0], 52 [0, 1, 0, 0, 0]])) 53 topk = TopKCategoricalAccuracy(3) 54 topk.clear() 55 topk.update(x, y) 56 result = topk.eval() 57 result2 = topk(x, y2) 58 assert math.isclose(result, 2 / 3) 59 assert math.isclose(result2, 2 / 3) 60 61 62def test_zero_topk(): 63 topk = TopKCategoricalAccuracy(3) 64 topk.clear() 65 with pytest.raises(RuntimeError): 66 topk.eval() 67 68 69def test_top1(): 70 """test_top1""" 71 x = Tensor(np.array([[0.2, 0.5, 0.2, 0.1, 0.], 72 [0.1, 0.35, 0.25, 0.2, 0.1], 73 [0.9, 0.1, 0, 0., 0]])) 74 y = Tensor(np.array([2, 0, 0])) 75 y2 = Tensor(np.array([[0, 0, 1, 0, 0], 76 [1, 0, 0, 0, 0], 77 [1, 0, 0, 0, 0]])) 78 topk = Top1CategoricalAccuracy() 79 topk.clear() 80 topk.update(x, y) 81 result = topk.eval() 82 result2 = topk(x, y2) 83 assert math.isclose(result, 1 / 3) 84 assert math.isclose(result2, 1 / 3) 85 86 87def test_top5(): 88 """test_top5""" 89 x = Tensor(np.array([[0.15, 0.4, 0.1, 0.05, 0., 0.2, 0.1], 90 [0.1, 0.35, 0.25, 0.2, 0.1, 0., 0.], 91 [0., 0.5, 0.2, 0.1, 0.1, 0.1, 0.]])) 92 y = Tensor(np.array([2, 0, 0])) 93 y2 = Tensor(np.array([[0, 0, 1, 0, 0], 94 [1, 0, 0, 0, 0], 95 [1, 0, 0, 0, 0]])) 96 topk = Top5CategoricalAccuracy() 97 topk.clear() 98 topk.update(x, y) 99 result = topk.eval() 100 result2 = topk(x, y2) 101 assert math.isclose(result, 2 / 3) 102 assert math.isclose(result2, 2 / 3) 103