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_metric_factory""" 16import math 17import numpy as np 18 19from mindspore import Tensor 20from mindspore.nn.metrics import get_metric_fn 21from mindspore.nn.metrics.metric import rearrange_inputs 22 23 24def test_classification_accuracy(): 25 x = Tensor(np.array([[0.2, 0.5], [0.3, 0.1], [0.9, 0.6]])) 26 y = Tensor(np.array([1, 0, 1])) 27 metric = get_metric_fn('accuracy', eval_type='classification') 28 metric.clear() 29 metric.update(x, y) 30 accuracy = metric.eval() 31 assert math.isclose(accuracy, 2 / 3) 32 33 34def test_classification_accuracy_by_alias(): 35 x = Tensor(np.array([[0.2, 0.5], [0.3, 0.1], [0.9, 0.6]])) 36 y = Tensor(np.array([1, 0, 1])) 37 metric = get_metric_fn('acc', eval_type='classification') 38 metric.clear() 39 metric.update(x, y) 40 accuracy = metric.eval() 41 assert math.isclose(accuracy, 2 / 3) 42 43 44def test_classification_precision(): 45 x = Tensor(np.array([[0.2, 0.5], [0.3, 0.1], [0.9, 0.6]])) 46 y = Tensor(np.array([1, 0, 1])) 47 metric = get_metric_fn('precision', eval_type='classification') 48 metric.clear() 49 metric.update(x, y) 50 precision = metric.eval() 51 52 assert np.equal(precision, np.array([0.5, 1])).all() 53 54 55class RearrangeInputsDemo: 56 def __init__(self): 57 self._indexes = None 58 59 @property 60 def indexes(self): 61 return getattr(self, '_indexes', None) 62 63 def set_indexes(self, indexes): 64 self._indexes = indexes 65 return self 66 67 @rearrange_inputs 68 def update(self, *inputs): 69 return inputs 70 71 72def test_rearrange_inputs_without_arrange(): 73 mini_decorator = RearrangeInputsDemo() 74 outs = mini_decorator.update(5, 9) 75 assert outs == (5, 9) 76 77 78def test_rearrange_inputs_with_arrange(): 79 mini_decorator = RearrangeInputsDemo().set_indexes([1, 0]) 80 outs = mini_decorator.update(5, 9) 81 assert outs == (9, 5) 82 83 84def test_rearrange_inputs_with_multi_inputs(): 85 mini_decorator = RearrangeInputsDemo().set_indexes([1, 3]) 86 outs = mini_decorator.update(0, 9, 0, 5) 87 assert outs == (9, 5) 88