KFold_test.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 fate_arch.session import computing_session as session
  19. from federatedml.feature.instance import Instance
  20. from federatedml.model_selection import KFold
  21. from federatedml.param.cross_validation_param import CrossValidationParam
  22. class TestKFlod(unittest.TestCase):
  23. def setUp(self):
  24. session.init("123")
  25. self.data_num = 1000
  26. self.feature_num = 200
  27. final_result = []
  28. for i in range(self.data_num):
  29. tmp = i * np.ones(self.feature_num)
  30. inst = Instance(inst_id=i, features=tmp, label=0)
  31. tmp = (str(i), inst)
  32. final_result.append(tmp)
  33. table = session.parallelize(final_result,
  34. include_key=True,
  35. partition=3)
  36. self.table = table
  37. def test_split(self):
  38. kfold_obj = KFold()
  39. kfold_obj.n_splits = 10
  40. kfold_obj.random_seed = 32
  41. # print(self.table, self.table.count())
  42. data_generator = kfold_obj.split(self.table)
  43. expect_test_data_num = self.data_num / 10
  44. expect_train_data_num = self.data_num - expect_test_data_num
  45. key_list = []
  46. for train_data, test_data in data_generator:
  47. train_num = train_data.count()
  48. test_num = test_data.count()
  49. # print("train_num: {}, test_num: {}".format(train_num, test_num))
  50. self.assertTrue(0.9 * expect_train_data_num < train_num < 1.1 * expect_train_data_num)
  51. self.assertTrue(0.9 * expect_test_data_num < test_num < 1.1 * expect_test_data_num)
  52. first_key = train_data.first()[0]
  53. key_list.append(first_key)
  54. # Test random seed work
  55. kfold_obj2 = KFold()
  56. kfold_obj2.n_splits = 10
  57. kfold_obj2.random_seed = 32
  58. data_generator = kfold_obj.split(self.table)
  59. n = 0
  60. for train_data, test_data in data_generator:
  61. second_key = train_data.first()[0]
  62. first_key = key_list[n]
  63. self.assertTrue(first_key == second_key)
  64. n += 1
  65. if __name__ == '__main__':
  66. unittest.main()