criterion_test.py 2.0 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 unittest
  17. import numpy as np
  18. from federatedml.ensemble import XgboostCriterion
  19. from federatedml.util import consts
  20. class TestXgboostCriterion(unittest.TestCase):
  21. def setUp(self):
  22. self.reg_lambda = 0.3
  23. self.criterion = XgboostCriterion(reg_lambda=self.reg_lambda)
  24. def test_init(self):
  25. self.assertTrue(np.fabs(self.criterion.reg_lambda - self.reg_lambda) < consts.FLOAT_ZERO)
  26. def test_split_gain(self):
  27. node = [0.5, 0.6]
  28. left = [0.1, 0.2]
  29. right = [0.4, 0.4]
  30. gain_all = node[0] * node[0] / (node[1] + self.reg_lambda)
  31. gain_left = left[0] * left[0] / (left[1] + self.reg_lambda)
  32. gain_right = right[0] * right[0] / (right[1] + self.reg_lambda)
  33. split_gain = gain_left + gain_right - gain_all
  34. self.assertTrue(np.fabs(self.criterion.split_gain(node, left, right) - split_gain) < consts.FLOAT_ZERO)
  35. def test_node_gain(self):
  36. grad = 0.5
  37. hess = 6
  38. gain = grad * grad / (hess + self.reg_lambda)
  39. self.assertTrue(np.fabs(self.criterion.node_gain(grad, hess) - gain) < consts.FLOAT_ZERO)
  40. def test_node_weight(self):
  41. grad = 0.5
  42. hess = 6
  43. weight = -grad / (hess + self.reg_lambda)
  44. self.assertTrue(np.fabs(self.criterion.node_weight(grad, hess) - weight) < consts.FLOAT_ZERO)
  45. if __name__ == '__main__':
  46. unittest.main()