【问题标题】:How to save a TensorFlow Hub model in SavedModels format?如何以 SavedModels 格式保存 TensorFlow Hub 模型?
【发布时间】:2020-05-15 22:53:12
【问题描述】:

我想从 TensorFlow Hub 加载模型并将其保存到磁盘。我试过了:

import tensorflow as tf
import tensorflow_hub as hub

def save_module(url, save_path):
  with tf.Graph().as_default():
    module = hub.load(url)
    tf.saved_model.save(module, save_path)

save_module("https://tfhub.dev/google/universal-sentence-encoder/4", "./saved-module")

但这失败了:

Traceback (most recent call last):
  File "C:\project\python-env\lib\site-packages\tensorflow\python\client\session.py", line 1365, in _do_call
    return fn(*args)
  File "C:\project\python-env\lib\site-packages\tensorflow\python\client\session.py", line 1349, in _run_fn
    return self._call_tf_sessionrun(options, feed_dict, fetch_list,
  File "C:\project\python-env\lib\site-packages\tensorflow\python\client\session.py", line 1441, in _call_tf_sessionrun
    return tf_session.TF_SessionRun_wrapper(self._session, options, feed_dict,
tensorflow.python.framework.errors_impl.FailedPreconditionError: 2 root error(s) found.
  (0) Failed precondition: Error while reading resource variable EncoderDNN/DNN/ResidualHidden_2/dense/kernel/part_27 from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/EncoderDNN/DNN/ResidualHidden_2/dense/kernel/part_27)
     [[{{node EncoderDNN/DNN/ResidualHidden_2/dense/kernel/part_27/Read/ReadVariableOp}}]]
     [[EncoderDNN/DNN/ResidualHidden_3/dense/kernel/part_22/Read/ReadVariableOp/_287]]
  (1) Failed precondition: Error while reading resource variable EncoderDNN/DNN/ResidualHidden_2/dense/kernel/part_27 from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/EncoderDNN/DNN/ResidualHidden_2/dense/kernel/part_27)
     [[{{node EncoderDNN/DNN/ResidualHidden_2/dense/kernel/part_27/Read/ReadVariableOp}}]]
0 successful operations.
0 derived errors ignored.

答案必须使用 TensorFlow 2 API。理想情况下,我想在没有 Keras 的情况下完成此任务,但我也会接受使用它的答案。有什么想法吗?

【问题讨论】:

    标签: tensorflow2.0


    【解决方案1】:

    如果没有 Keras,我无法完成这项工作,但无论如何它都有效:

    import tensorflow as tf
    import tensorflow_hub as hub
    
    
    def save_module(url, save_path):
      module = hub.KerasLayer(url)
      model = tf.keras.Sequential(module)
      tf.saved_model.save(model, save_path)
    
    
    save_module("https://tfhub.dev/google/universal-sentence-encoder/4", "./saved-module")
    

    【讨论】:

      猜你喜欢
      • 2021-09-10
      • 2019-08-28
      • 2021-08-14
      • 2020-02-08
      • 1970-01-01
      • 2021-03-03
      • 1970-01-01
      • 2021-05-06
      • 2021-05-20
      相关资源
      最近更新 更多