You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_precision.py 2.2 kB

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