pipeline-lr-binary.py 7.1 KB

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