homo_lr_gradient_test.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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.feature.instance import Instance
  19. from federatedml.optim.gradient.homo_lr_gradient import LogisticGradient, TaylorLogisticGradient
  20. from federatedml.secureprotol import PaillierEncrypt
  21. class TestHomoLRGradient(unittest.TestCase):
  22. def setUp(self):
  23. self.paillier_encrypt = PaillierEncrypt()
  24. self.paillier_encrypt.generate_key()
  25. self.gradient_operator = LogisticGradient()
  26. self.taylor_operator = TaylorLogisticGradient()
  27. self.X = np.array([[1, 2, 3, 4, 5], [3, 2, 4, 5, 1], [2, 2, 3, 1, 1, ]]) / 10
  28. self.X1 = np.c_[self.X, np.ones(3)]
  29. self.Y = np.array([[1], [1], [-1]])
  30. self.values = []
  31. for idx, x in enumerate(self.X):
  32. inst = Instance(inst_id=idx, features=x, label=self.Y[idx])
  33. self.values.append((idx, inst))
  34. self.values1 = []
  35. for idx, x in enumerate(self.X1):
  36. inst = Instance(inst_id=idx, features=x, label=self.Y[idx])
  37. self.values1.append((idx, inst))
  38. self.coef = np.array([2, 2.3, 3, 4, 2.1]) / 10
  39. self.coef1 = np.append(self.coef, [1])
  40. def test_gradient_length(self):
  41. fit_intercept = False
  42. grad = self.gradient_operator.compute_gradient(self.values, self.coef, 0, fit_intercept)
  43. self.assertEqual(grad.shape[0], self.X.shape[1])
  44. taylor_grad = self.taylor_operator.compute_gradient(self.values, self.coef, 0, fit_intercept)
  45. self.assertEqual(taylor_grad.shape[0], self.X.shape[1])
  46. self.assertTrue(np.sum(grad - taylor_grad) < 0.0001)
  47. fit_intercept = True
  48. grad = self.gradient_operator.compute_gradient(self.values, self.coef, 0, fit_intercept)
  49. self.assertEqual(grad.shape[0], self.X.shape[1] + 1)
  50. taylor_grad = self.taylor_operator.compute_gradient(self.values, self.coef, 0, fit_intercept)
  51. self.assertEqual(taylor_grad.shape[0], self.X.shape[1] + 1)
  52. self.assertTrue(np.sum(grad - taylor_grad) < 0.0001)
  53. if __name__ == '__main__':
  54. unittest.main()