pipeline-lr-multi.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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 == "vehicle_scale_homo_guest.csv":
  39. guest_data_table = 'vehicle_scale_homo_guest'
  40. host_data_table = 'vehicle_scale_homo_host'
  41. else:
  42. raise ValueError(f"Cannot recognized data_set: {data_set}")
  43. guest_train_data = {"name": guest_data_table, "namespace": f"experiment{namespace}"}
  44. host_train_data = {"name": host_data_table, "namespace": f"experiment{namespace}"}
  45. # initialize pipeline
  46. pipeline = PipeLine()
  47. # set job initiator
  48. pipeline.set_initiator(role='guest', party_id=guest)
  49. # set participants information
  50. pipeline.set_roles(guest=guest, host=host, arbiter=arbiter)
  51. # define Reader components to read in data
  52. reader_0 = Reader(name="reader_0")
  53. # configure Reader for guest
  54. reader_0.get_party_instance(role='guest', party_id=guest).component_param(table=guest_train_data)
  55. # configure Reader for host
  56. reader_0.get_party_instance(role='host', party_id=host).component_param(table=host_train_data)
  57. # define DataTransform components
  58. data_transform_0 = DataTransform(name="data_transform_0") # start component numbering at 0
  59. # get DataTransform party instance of guest
  60. data_transform_0_guest_party_instance = data_transform_0.get_party_instance(role='guest', party_id=guest)
  61. # configure DataTransform for guest
  62. data_transform_0_guest_party_instance.component_param(with_label=True, output_format="dense")
  63. # get and configure DataTransform party instance of host
  64. data_transform_0.get_party_instance(role='host', party_id=host).component_param(with_label=True)
  65. lr_param = {
  66. }
  67. config_param = {
  68. "penalty": param["penalty"],
  69. "max_iter": param["max_iter"],
  70. "alpha": param["alpha"],
  71. "learning_rate": param["learning_rate"],
  72. "optimizer": param.get("optimizer", "sgd"),
  73. "batch_size": param.get("batch_size", -1),
  74. "init_param": {
  75. "init_method": 'random_uniform'
  76. }
  77. }
  78. lr_param.update(config_param)
  79. print(f"lr_param: {lr_param}, data_set: {data_set}")
  80. homo_lr_0 = HomoLR(name='homo_lr_0', **lr_param)
  81. homo_lr_1 = HomoLR(name='homo_lr_1')
  82. evaluation_0 = Evaluation(name='evaluation_0', eval_type="multi")
  83. evaluation_0.get_party_instance(role='host', party_id=host).component_param(need_run=False)
  84. # add components to pipeline, in order of task execution
  85. pipeline.add_component(reader_0)
  86. pipeline.add_component(data_transform_0, data=Data(data=reader_0.output.data))
  87. pipeline.add_component(homo_lr_0, data=Data(train_data=data_transform_0.output.data))
  88. pipeline.add_component(homo_lr_1, data=Data(test_data=data_transform_0.output.data),
  89. model=Model(homo_lr_0.output.model))
  90. pipeline.add_component(evaluation_0, data=Data(data=homo_lr_0.output.data))
  91. # compile pipeline once finished adding modules, this step will form conf and dsl files for running job
  92. pipeline.compile()
  93. # fit model
  94. pipeline.fit()
  95. # query component summary
  96. data_summary = {"train": {"guest": guest_train_data["name"], "host": host_train_data["name"]},
  97. "test": {"guest": guest_train_data["name"], "host": host_train_data["name"]}
  98. }
  99. result_summary = parse_summary_result(pipeline.get_component("evaluation_0").get_summary())
  100. lr_0_data = pipeline.get_component("homo_lr_0").get_output_data()
  101. lr_1_data = pipeline.get_component("homo_lr_1").get_output_data()
  102. lr_0_score_label = extract_data(lr_0_data, "predict_result", keep_id=True)
  103. lr_1_score_label = extract_data(lr_1_data, "predict_result", keep_id=True)
  104. metric_lr = {
  105. "score_diversity_ratio":
  106. classification_metric.Distribution.compute(lr_0_score_label, lr_1_score_label)}
  107. result_summary["distribution_metrics"] = {"homo_lr": metric_lr}
  108. print(result_summary)
  109. return data_summary, result_summary
  110. if __name__ == "__main__":
  111. parser = argparse.ArgumentParser("BENCHMARK-QUALITY PIPELINE JOB")
  112. parser.add_argument("-config", type=str,
  113. help="config file")
  114. parser.add_argument("-param", type=str,
  115. help="config file for params")
  116. args = parser.parse_args()
  117. if args.config is not None:
  118. main(args.config, args.param)
  119. else:
  120. main()