nn.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #
  2. # Copyright 2021 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 io
  17. import tempfile
  18. import tensorflow
  19. import zipfile
  20. from ..component_converter import ComponentConverterBase
  21. class NNComponentConverter(ComponentConverterBase):
  22. @staticmethod
  23. def get_target_modules():
  24. return ['HomoNN']
  25. def convert(self, model_dict):
  26. param_obj = model_dict["HomoNNModelParam"]
  27. meta_obj = model_dict["HomoNNModelMeta"]
  28. if meta_obj.params.config_type != "nn" and meta_obj.params.config_type != "keras":
  29. raise ValueError("Invalid config type: {}".format(meta_obj.config_type))
  30. with tempfile.TemporaryDirectory() as tmp_path:
  31. with io.BytesIO(param_obj.saved_model_bytes) as bytes_io:
  32. with zipfile.ZipFile(bytes_io, 'r', zipfile.ZIP_DEFLATED) as f:
  33. f.extractall(tmp_path)
  34. try:
  35. model = tensorflow.keras.models.load_model(tmp_path)
  36. except Exception as e:
  37. model = tensorflow.compat.v1.keras.experimental.load_from_saved_model(tmp_path)
  38. return model