1# Copyright 2021 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_confusion_matrix""" 16import numpy as np 17import pytest 18from mindspore import Tensor 19from mindspore.nn.metrics import ConfusionMatrix 20 21 22def test_confusion_matrix(): 23 """test_confusion_matrix""" 24 x = Tensor(np.array([1, 0, 1, 0])) 25 y = Tensor(np.array([1, 0, 0, 1])) 26 metric = ConfusionMatrix(num_classes=2) 27 metric.clear() 28 metric.update(x, y) 29 output = metric.eval() 30 31 assert np.allclose(output, np.array([[1, 1], [1, 1]])) 32 33 34def test_confusion_matrix_update_len(): 35 x = Tensor(np.array([[0.2, 0.5, 0.7], [0.3, 0.1, 0.2], [0.9, 0.6, 0.5]])) 36 metric = ConfusionMatrix(num_classes=2) 37 metric.clear() 38 39 with pytest.raises(ValueError): 40 metric.update(x) 41 42 43def test_confusion_matrix_update_dim(): 44 x = Tensor(np.array([[0.2, 0.5, 0.7], [0.3, 0.1, 0.2], [0.9, 0.6, 0.5]])) 45 y = Tensor(np.array([1, 0])) 46 metric = ConfusionMatrix(num_classes=2) 47 metric.clear() 48 49 with pytest.raises(ValueError): 50 metric.update(x, y) 51 52 53def test_confusion_matrix_init_num_classes(): 54 with pytest.raises(TypeError): 55 ConfusionMatrix(num_classes='1') 56 57 58def test_confusion_matrix_init_normalize_value(): 59 with pytest.raises(ValueError): 60 ConfusionMatrix(num_classes=2, normalize="wwe") 61 62 63def test_confusion_matrix_init_threshold(): 64 with pytest.raises(TypeError): 65 ConfusionMatrix(num_classes=2, normalize='no_norm', threshold=1) 66 67 68def test_confusion_matrix_runtime(): 69 metric = ConfusionMatrix(num_classes=2) 70 metric.clear() 71 72 with pytest.raises(RuntimeError): 73 metric.eval() 74