convergence_test.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #
  2. # Copyright 2019 The FATE Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import math
  17. import unittest
  18. from federatedml.optim.convergence import converge_func_factory
  19. class TestConvergeFunction(unittest.TestCase):
  20. def test_diff_converge(self):
  21. loss = 50
  22. eps = 0.00001
  23. # converge_func = DiffConverge(eps=eps)
  24. converge_func = converge_func_factory(early_stop='diff', tol=eps)
  25. iter_num = 0
  26. pre_loss = loss
  27. while iter_num < 500:
  28. loss *= 0.5
  29. converge_flag = converge_func.is_converge(loss)
  30. if converge_flag:
  31. break
  32. iter_num += 1
  33. pre_loss = loss
  34. self.assertTrue(math.fabs(pre_loss - loss) <= eps)
  35. def test_abs_converge(self):
  36. loss = 50
  37. eps = 0.00001
  38. # converge_func = AbsConverge(eps=eps)
  39. converge_func = converge_func_factory(early_stop='abs', tol=eps)
  40. iter_num = 0
  41. while iter_num < 500:
  42. loss *= 0.5
  43. converge_flag = converge_func.is_converge(loss)
  44. if converge_flag:
  45. break
  46. iter_num += 1
  47. self.assertTrue(math.fabs(loss) <= eps)
  48. if __name__ == '__main__':
  49. unittest.main()