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 2.3 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. import mindspore.nn as nn
  18. from mindspore import Tensor
  19. from ..ut_filter import non_graph_engine
  20. def test_L1Loss():
  21. loss = nn.L1Loss()
  22. input_data = Tensor(np.array([[1, 2, 3], [2, 3, 4]]).astype(np.float32))
  23. target_data = Tensor(np.array([[0, 2, 5], [3, 1, 1]]).astype(np.float32))
  24. loss(input_data, target_data)
  25. def test_MSELoss():
  26. loss = nn.MSELoss()
  27. input_data = Tensor(np.array([[1, 2, 3], [2, 3, 2]]).astype(np.float32))
  28. target_data = Tensor(np.array([[0, 0, 5], [1, 2, 3]]).astype(np.float32))
  29. loss(input_data, target_data)
  30. @non_graph_engine
  31. def test_SoftmaxCrossEntropyWithLogits():
  32. """ test_SoftmaxCrossEntropyWithLogits """
  33. loss = nn.SoftmaxCrossEntropyWithLogits()
  34. logits = Tensor(np.random.randint(0, 9, [100, 10]).astype(np.float32))
  35. labels = Tensor(np.random.randint(0, 9, [100, 10]).astype(np.float32))
  36. loss.construct(logits, labels)
  37. def test_SoftmaxCrossEntropyWithLogits_reduce():
  38. """ test_SoftmaxCrossEntropyWithLogits """
  39. loss = nn.SoftmaxCrossEntropyWithLogits(reduction="mean")
  40. logits = Tensor(np.random.randint(0, 9, [100, 10]).astype(np.float32))
  41. labels = Tensor(np.random.randint(0, 9, [100, 10]).astype(np.float32))
  42. loss(logits, labels)
  43. def test_cosine_embedding_loss():
  44. """ test CosineEmbeddingLoss """
  45. loss = nn.CosineEmbeddingLoss()
  46. x1 = Tensor(np.array([[0.3, 0.8], [0.4, 0.3]]).astype(np.float32))
  47. x2 = Tensor(np.array([[0.4, 1.2], [-0.4, -0.9]]).astype(np.float32))
  48. label = Tensor(np.array([1, -1]).astype(np.int32))
  49. loss(x1, x2, label)