fate-hetero_nn.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. import torch as t
  18. from torch import nn
  19. from pipeline import fate_torch_hook
  20. from pipeline.backend.pipeline import PipeLine
  21. from pipeline.component.nn import DatasetParam
  22. from pipeline.component import DataTransform
  23. from pipeline.component import Evaluation
  24. from pipeline.component import HeteroNN
  25. from pipeline.component import Intersection
  26. from pipeline.component import Reader
  27. from pipeline.interface import Data, Model
  28. from pipeline.utils.tools import load_job_config, JobConfig
  29. from federatedml.evaluation.metrics import classification_metric
  30. from fate_test.utils import extract_data, parse_summary_result
  31. fate_torch_hook(t)
  32. def build(param, shape1, shape2):
  33. guest_bottom = t.nn.Sequential(
  34. nn.Linear(shape1, param["bottom_layer_units"]),
  35. nn.ReLU()
  36. )
  37. host_bottom = t.nn.Sequential(
  38. nn.Linear(shape2, param["bottom_layer_units"]),
  39. nn.ReLU()
  40. )
  41. interactive_layer = t.nn.InteractiveLayer(
  42. guest_dim=param["bottom_layer_units"],
  43. host_dim=param["bottom_layer_units"],
  44. host_num=1,
  45. out_dim=param["interactive_layer_units"])
  46. act = nn.Sigmoid() if param["top_layer_units"] == 1 else nn.Softmax(dim=1)
  47. top_layer = t.nn.Sequential(
  48. t.nn.Linear(
  49. param["interactive_layer_units"],
  50. param["top_layer_units"]),
  51. act)
  52. return guest_bottom, host_bottom, interactive_layer, top_layer
  53. def main(
  54. config="../../config.yaml",
  55. param="./hetero_nn_breast_config.yaml",
  56. namespace=""):
  57. # obtain config
  58. if isinstance(config, str):
  59. config = load_job_config(config)
  60. if isinstance(param, str):
  61. param = JobConfig.load_from_file(param)
  62. parties = config.parties
  63. guest = parties.guest[0]
  64. host = parties.host[0]
  65. guest_train_data = {
  66. "name": param["guest_table_name"],
  67. "namespace": f"experiment{namespace}"}
  68. host_train_data = {
  69. "name": param["host_table_name"],
  70. "namespace": f"experiment{namespace}"}
  71. pipeline = PipeLine().set_initiator(
  72. role='guest', party_id=guest).set_roles(
  73. guest=guest, host=host)
  74. reader_0 = Reader(name="reader_0")
  75. reader_0.get_party_instance(
  76. role='guest',
  77. party_id=guest).component_param(
  78. table=guest_train_data)
  79. reader_0.get_party_instance(
  80. role='host',
  81. party_id=host).component_param(
  82. table=host_train_data)
  83. data_transform_0 = DataTransform(name="data_transform_0")
  84. data_transform_0.get_party_instance(
  85. role='guest',
  86. party_id=guest).component_param(
  87. with_label=True)
  88. data_transform_0.get_party_instance(
  89. role='host', party_id=host).component_param(
  90. with_label=False)
  91. intersection_0 = Intersection(name="intersection_0")
  92. guest_bottom, host_bottom, interactive_layer, top_layer = build(
  93. param, param['shape1'], param['shape2'])
  94. if param["loss"] == "categorical_crossentropy":
  95. loss = t.nn.CrossEntropyLoss()
  96. ds_param = DatasetParam(
  97. dataset_name='table',
  98. flatten_label=True,
  99. label_dtype='long')
  100. else:
  101. loss = t.nn.BCELoss()
  102. ds_param = DatasetParam(dataset_name='table')
  103. hetero_nn_0 = HeteroNN(
  104. name="hetero_nn_0",
  105. epochs=param["epochs"],
  106. interactive_layer_lr=param["learning_rate"],
  107. batch_size=param["batch_size"],
  108. seed=100,
  109. dataset=ds_param)
  110. guest_nn_0 = hetero_nn_0.get_party_instance(role='guest', party_id=guest)
  111. host_nn_0 = hetero_nn_0.get_party_instance(role='host', party_id=host)
  112. guest_nn_0.add_bottom_model(guest_bottom)
  113. guest_nn_0.add_top_model(top_layer)
  114. host_nn_0.add_bottom_model(host_bottom)
  115. hetero_nn_0.set_interactive_layer(interactive_layer)
  116. hetero_nn_0.compile(
  117. optimizer=t.optim.Adam(
  118. lr=param['learning_rate']),
  119. loss=loss)
  120. hetero_nn_1 = HeteroNN(name="hetero_nn_1")
  121. if param["loss"] == "categorical_crossentropy":
  122. eval_type = "multi"
  123. else:
  124. eval_type = "binary"
  125. evaluation_0 = Evaluation(name="evaluation_0", eval_type=eval_type)
  126. pipeline.add_component(reader_0)
  127. pipeline.add_component(
  128. data_transform_0, data=Data(
  129. data=reader_0.output.data))
  130. pipeline.add_component(
  131. intersection_0, data=Data(
  132. data=data_transform_0.output.data))
  133. pipeline.add_component(
  134. hetero_nn_0, data=Data(
  135. train_data=intersection_0.output.data))
  136. pipeline.add_component(
  137. hetero_nn_1, data=Data(
  138. test_data=intersection_0.output.data), model=Model(
  139. hetero_nn_0.output.model))
  140. pipeline.add_component(
  141. evaluation_0, data=Data(
  142. data=hetero_nn_0.output.data))
  143. pipeline.compile()
  144. pipeline.fit()
  145. nn_0_data = pipeline.get_component("hetero_nn_0").get_output_data()
  146. nn_1_data = pipeline.get_component("hetero_nn_1").get_output_data()
  147. nn_0_score = extract_data(nn_0_data, "predict_result")
  148. nn_0_label = extract_data(nn_0_data, "label")
  149. nn_1_score = extract_data(nn_1_data, "predict_result")
  150. nn_1_label = extract_data(nn_1_data, "label")
  151. nn_0_score_label = extract_data(nn_0_data, "predict_result", keep_id=True)
  152. nn_1_score_label = extract_data(nn_1_data, "predict_result", keep_id=True)
  153. metric_summary = parse_summary_result(
  154. pipeline.get_component("evaluation_0").get_summary())
  155. if eval_type == "binary":
  156. metric_nn = {
  157. "score_diversity_ratio": classification_metric.Distribution.compute(
  158. nn_0_score_label,
  159. nn_1_score_label),
  160. "ks_2samp": classification_metric.KSTest.compute(
  161. nn_0_score,
  162. nn_1_score),
  163. "mAP_D_value": classification_metric.AveragePrecisionScore().compute(
  164. nn_0_score,
  165. nn_1_score,
  166. nn_0_label,
  167. nn_1_label)}
  168. metric_summary["distribution_metrics"] = {"hetero_nn": metric_nn}
  169. elif eval_type == "multi":
  170. metric_nn = {
  171. "score_diversity_ratio": classification_metric.Distribution.compute(
  172. nn_0_score_label, nn_1_score_label)}
  173. metric_summary["distribution_metrics"] = {"hetero_nn": metric_nn}
  174. data_summary = {
  175. "train": {
  176. "guest": guest_train_data["name"],
  177. "host": host_train_data["name"]},
  178. "test": {
  179. "guest": guest_train_data["name"],
  180. "host": host_train_data["name"]}}
  181. return data_summary, metric_summary
  182. if __name__ == "__main__":
  183. parser = argparse.ArgumentParser("BENCHMARK-QUALITY PIPELINE JOB")
  184. parser.add_argument("-config", type=str,
  185. help="config file")
  186. parser.add_argument("-param", type=str,
  187. help="config file for params")
  188. args = parser.parse_args()
  189. if args.config is not None:
  190. main(args.config, args.param)
  191. else:
  192. main()