pipeline-sshe-lr-binary.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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 argparse
  17. from pipeline.backend.pipeline import PipeLine
  18. from pipeline.component import DataTransform
  19. from pipeline.component import Evaluation
  20. from pipeline.component import HeteroSSHELR
  21. from pipeline.component import Intersection
  22. from pipeline.component import Reader
  23. from pipeline.interface import Data, Model
  24. from pipeline.utils.tools import load_job_config, JobConfig
  25. from fate_test.utils import extract_data, parse_summary_result
  26. from federatedml.evaluation.metrics import classification_metric
  27. def main(config="../../config.yaml", param="./lr_config.yaml", namespace=""):
  28. # obtain config
  29. if isinstance(config, str):
  30. config = load_job_config(config)
  31. parties = config.parties
  32. guest = parties.guest[0]
  33. host = parties.host[0]
  34. arbiter = parties.arbiter[0]
  35. if isinstance(param, str):
  36. param = JobConfig.load_from_file(param)
  37. assert isinstance(param, dict)
  38. data_set = param.get("data_guest").split('/')[-1]
  39. if data_set == "default_credit_hetero_guest.csv":
  40. guest_data_table = 'default_credit_hetero_guest'
  41. host_data_table = 'default_credit_hetero_host'
  42. elif data_set == 'breast_hetero_guest.csv':
  43. guest_data_table = 'breast_hetero_guest'
  44. host_data_table = 'breast_hetero_host'
  45. elif data_set == 'give_credit_hetero_guest.csv':
  46. guest_data_table = 'give_credit_hetero_guest'
  47. host_data_table = 'give_credit_hetero_host'
  48. elif data_set == 'epsilon_5k_hetero_guest.csv':
  49. guest_data_table = 'epsilon_5k_hetero_guest'
  50. host_data_table = 'epsilon_5k_hetero_host'
  51. else:
  52. raise ValueError(f"Cannot recognized data_set: {data_set}")
  53. guest_train_data = {"name": guest_data_table, "namespace": f"experiment{namespace}"}
  54. host_train_data = {"name": host_data_table, "namespace": f"experiment{namespace}"}
  55. # initialize pipeline
  56. pipeline = PipeLine()
  57. # set job initiator
  58. pipeline.set_initiator(role='guest', party_id=guest)
  59. # set participants information
  60. pipeline.set_roles(guest=guest, host=host, arbiter=arbiter)
  61. # define Reader components to read in data
  62. reader_0 = Reader(name="reader_0")
  63. # configure Reader for guest
  64. reader_0.get_party_instance(role='guest', party_id=guest).component_param(table=guest_train_data)
  65. # configure Reader for host
  66. reader_0.get_party_instance(role='host', party_id=host).component_param(table=host_train_data)
  67. # define DataTransform components
  68. data_transform_0 = DataTransform(name="data_transform_0") # start component numbering at 0
  69. # get DataTransform party instance of guest
  70. data_transform_0_guest_party_instance = data_transform_0.get_party_instance(role='guest', party_id=guest)
  71. # configure DataTransform for guest
  72. data_transform_0_guest_party_instance.component_param(with_label=True, output_format="dense")
  73. # get and configure DataTransform party instance of host
  74. data_transform_0.get_party_instance(role='host', party_id=host).component_param(with_label=False)
  75. # define Intersection component
  76. intersection_0 = Intersection(name="intersection_0")
  77. lr_param = {
  78. }
  79. config_param = {
  80. "penalty": param["penalty"],
  81. "max_iter": param["max_iter"],
  82. "alpha": param["alpha"],
  83. "learning_rate": param["learning_rate"],
  84. "optimizer": param["optimizer"], # use sgd
  85. "batch_size": param["batch_size"],
  86. "early_stop": "diff",
  87. "tol": 1e-4,
  88. "init_param": {
  89. "init_method": param.get("init_method", 'random_uniform'),
  90. "random_seed": param.get("random_seed", 103),
  91. "fit_intercept": True
  92. },
  93. "reveal_strategy": param.get("reveal_strategy", "respectively"),
  94. "reveal_every_iter": True
  95. }
  96. lr_param.update(config_param)
  97. print(f"lr_param: {lr_param}, data_set: {data_set}")
  98. hetero_sshe_lr_0 = HeteroSSHELR(name='hetero_sshe_lr_0', **lr_param)
  99. hetero_sshe_lr_1 = HeteroSSHELR(name='hetero_sshe_lr_1')
  100. evaluation_0 = Evaluation(name='evaluation_0', eval_type="binary")
  101. # add components to pipeline, in order of task execution
  102. pipeline.add_component(reader_0)
  103. pipeline.add_component(data_transform_0, data=Data(data=reader_0.output.data))
  104. pipeline.add_component(intersection_0, data=Data(data=data_transform_0.output.data))
  105. pipeline.add_component(hetero_sshe_lr_0, data=Data(train_data=intersection_0.output.data))
  106. pipeline.add_component(hetero_sshe_lr_1, data=Data(test_data=intersection_0.output.data),
  107. model=Model(hetero_sshe_lr_0.output.model))
  108. pipeline.add_component(evaluation_0, data=Data(data=hetero_sshe_lr_0.output.data))
  109. # compile pipeline once finished adding modules, this step will form conf and dsl files for running job
  110. pipeline.compile()
  111. # fit model
  112. pipeline.fit()
  113. lr_0_data = pipeline.get_component("hetero_sshe_lr_0").get_output_data()
  114. lr_1_data = pipeline.get_component("hetero_sshe_lr_1").get_output_data()
  115. lr_0_score = extract_data(lr_0_data, "predict_result")
  116. lr_0_label = extract_data(lr_0_data, "label")
  117. lr_1_score = extract_data(lr_1_data, "predict_result")
  118. lr_1_label = extract_data(lr_1_data, "label")
  119. lr_0_score_label = extract_data(lr_0_data, "predict_result", keep_id=True)
  120. lr_1_score_label = extract_data(lr_1_data, "predict_result", keep_id=True)
  121. result_summary = parse_summary_result(pipeline.get_component("evaluation_0").get_summary())
  122. metric_lr = {
  123. "score_diversity_ratio": classification_metric.Distribution.compute(lr_0_score_label, lr_1_score_label),
  124. "ks_2samp": classification_metric.KSTest.compute(lr_0_score, lr_1_score),
  125. "mAP_D_value": classification_metric.AveragePrecisionScore().compute(lr_0_score, lr_1_score, lr_0_label,
  126. lr_1_label)}
  127. result_summary["distribution_metrics"] = {"hetero_lr": metric_lr}
  128. data_summary = {"train": {"guest": guest_train_data["name"], "host": host_train_data["name"]},
  129. "test": {"guest": guest_train_data["name"], "host": host_train_data["name"]}
  130. }
  131. print(f"result_summary: {result_summary}; data_summary: {data_summary}")
  132. return data_summary, result_summary
  133. if __name__ == "__main__":
  134. parser = argparse.ArgumentParser("BENCHMARK-QUALITY PIPELINE JOB")
  135. parser.add_argument("-c", "--config", type=str,
  136. help="config file", default="../../config.yaml")
  137. parser.add_argument("-p", "--param", type=str,
  138. help="config file for params", default="./breast_config.yaml")
  139. args = parser.parse_args()
  140. main(args.config, args.param)