pipeline-lr-binary.py 6.7 KB

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