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_roc""" 16 17import numpy as np 18import pytest 19from mindspore import Tensor 20from mindspore.nn.metrics import ROC 21 22 23def test_roc(): 24 """test_roc_binary""" 25 x = Tensor(np.array([[3, 0, 1], [1, 3, 0], [1, 0, 2]])) 26 y = Tensor(np.array([[0, 2, 1], [1, 2, 1], [0, 0, 1]])) 27 metric = ROC(pos_label=1) 28 metric.clear() 29 metric.update(x, y) 30 fpr, tpr, thresholds = metric.eval() 31 32 assert np.equal(fpr, np.array([0, 0.4, 0.4, 0.6, 1])).all() 33 assert np.equal(tpr, np.array([0, 0, 0.25, 0.75, 1])).all() 34 assert np.equal(thresholds, np.array([4, 3, 2, 1, 0])).all() 35 36 37def test_roc2(): 38 """test_roc_multiclass""" 39 x = Tensor(np.array([[0.28, 0.55, 0.15, 0.05], [0.10, 0.20, 0.05, 0.05], [0.20, 0.05, 0.15, 0.05], 40 [0.05, 0.05, 0.05, 0.75]])) 41 y = Tensor(np.array([0, 1, 2, 3])) 42 metric = ROC(class_num=4) 43 metric.clear() 44 metric.update(x, y) 45 fpr, tpr, thresholds = metric.eval() 46 list1 = [np.array([0., 0., 0.33333333, 0.66666667, 1.]), np.array([0., 0.33333333, 0.33333333, 1.]), 47 np.array([0., 0.33333333, 1.]), np.array([0., 0., 1.])] 48 list2 = [np.array([0., 1., 1., 1., 1.]), np.array([0., 0., 1., 1.]), 49 np.array([0., 1., 1.]), np.array([0., 1., 1.])] 50 list3 = [np.array([1.28, 0.28, 0.2, 0.1, 0.05]), np.array([1.55, 0.55, 0.2, 0.05]), 51 np.array([1.15, 0.15, 0.05]), np.array([1.75, 0.75, 0.05])] 52 53 assert fpr[0].shape == list1[0].shape 54 assert np.equal(tpr[1], list2[1]).all() 55 assert np.equal(thresholds[2], list3[2]).all() 56 57 58def test_roc_update1(): 59 x = Tensor(np.array([[0.2, 0.5, 0.7], [0.3, 0.1, 0.2], [0.9, 0.6, 0.5]])) 60 metric = ROC() 61 metric.clear() 62 63 with pytest.raises(ValueError): 64 metric.update(x) 65 66 67def test_roc_update2(): 68 x = Tensor(np.array([[0.2, 0.5, 0.7], [0.3, 0.1, 0.2], [0.9, 0.6, 0.5]])) 69 y = Tensor(np.array([1, 0])) 70 metric = ROC() 71 metric.clear() 72 73 with pytest.raises(ValueError): 74 metric.update(x, y) 75 76 77def test_roc_init1(): 78 with pytest.raises(TypeError): 79 ROC(pos_label=1.2) 80 81 82def test_roc_init2(): 83 with pytest.raises(TypeError): 84 ROC(class_num="class_num") 85 86 87def test_roc_runtime(): 88 metric = ROC() 89 metric.clear() 90 91 with pytest.raises(RuntimeError): 92 metric.eval() 93