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_loss.py 1.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 loss """
  16. import numpy as np
  17. from mindspore import Tensor
  18. from mindspore.ops import operations as P
  19. from mindspore.nn.loss.loss import _Loss
  20. class WeightedLoss(_Loss):
  21. def __init__(self, reduction='mean', weights=1.0):
  22. super(WeightedLoss, self).__init__(reduction, weights)
  23. self.abs = P.Abs()
  24. def construct(self, base, target):
  25. x = self.abs(base - target)
  26. return self.get_loss(x)
  27. def test_WeightedLoss():
  28. loss = WeightedLoss()
  29. input_data = Tensor(np.array([[1, 2, 3], [2, 3, 4]]).astype(np.float32))
  30. target_data = Tensor(np.array([[0, 2, 5], [3, 1, 1]]).astype(np.float32))
  31. output_data = loss(input_data, target_data)
  32. error_range = np.ones(shape=output_data.shape) * 10e-6
  33. loss.weights = 1.0
  34. test_output = loss(input_data, target_data)
  35. diff = test_output - output_data * loss.weights
  36. assert np.all(abs(diff.asnumpy()) < error_range)
  37. loss.weights = 2.0
  38. test_output = loss(input_data, target_data)
  39. diff = test_output - output_data * loss.weights
  40. assert np.all(abs(diff.asnumpy()) < error_range)
  41. loss.weights = 3
  42. test_output = loss(input_data, target_data)
  43. diff = test_output - output_data * loss.weights
  44. assert np.all(abs(diff.asnumpy()) < error_range)