• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_precision"""
16import math
17import numpy as np
18import pytest
19
20from mindspore import Tensor
21from mindspore.nn.metrics import Precision
22
23
24def test_classification_precision():
25    """test_classification_precision"""
26    x = Tensor(np.array([[0.2, 0.5], [0.3, 0.1], [0.9, 0.6]]))
27    y = Tensor(np.array([1, 0, 1]))
28    y2 = Tensor(np.array([[0, 1], [1, 0], [0, 1]]))
29    metric = Precision('classification')
30    metric.clear()
31    metric.update(x, y)
32    precision = metric.eval()
33    precision2 = metric(x, y2)
34
35    assert np.equal(precision, np.array([0.5, 1])).all()
36    assert np.equal(precision2, np.array([0.5, 1])).all()
37
38
39def test_multilabel_precision():
40    x = Tensor(np.array([[0, 1, 0, 1], [1, 0, 1, 1], [0, 0, 0, 1]]))
41    y = Tensor(np.array([[0, 1, 1, 1], [0, 1, 1, 1], [0, 0, 0, 1]]))
42    metric = Precision('multilabel')
43    metric.clear()
44    metric.update(x, y)
45    precision = metric.eval()
46
47    assert np.equal(precision, np.array([1, 2 / 3, 1])).all()
48
49
50def test_average_precision():
51    x = Tensor(np.array([[0, 1, 0, 1], [1, 0, 1, 1], [0, 0, 0, 1]]))
52    y = Tensor(np.array([[0, 1, 1, 1], [0, 1, 1, 1], [0, 0, 0, 1]]))
53    metric = Precision('multilabel')
54    metric.clear()
55    metric.update(x, y)
56    precision = metric.eval(True)
57
58    assert math.isclose(precision, (1 + 2 / 3 + 1) / 3)
59
60
61def test_num_precision():
62    x = Tensor(np.array([[0.2, 0.5, 0.7], [0.3, 0.1, 0.2], [0.9, 0.6, 0.5]]))
63    y = Tensor(np.array([1, 0]))
64    metric = Precision('classification')
65    metric.clear()
66
67    with pytest.raises(ValueError):
68        metric.update(x, y)
69