代码之家  ›  专栏  ›  技术社区  ›  sdcbr

将keras模型导出为tf估计量:找不到经过训练的模型

  •  1
  • sdcbr  · 技术社区  · 7 年前

    我在尝试将Keras模型导出为TensorFlow估计量以服务于该模型时遇到以下问题。因为同样的问题也出现了 in an answer to this question ,我将说明在一个玩具示例上发生的事情,并为文档目的提供我的解决方案。这种行为发生在TensorFlow 1.12.0和Keras 2.2.4中。这发生在实际的角膜以及 tf.keras .

    当尝试导出从带有 tf.keras.estimator.model_to_estimator . 打电话时 estimator.export_savedmodel ,或者 NotFoundError 或A ValueError 被扔掉。

    下面的代码为一个玩具示例复制了这个代码。

    创建Keras模型并保存:

    import keras
    model = keras.Sequential()
    model.add(keras.layers.Dense(units=1,
                                    activation='sigmoid',
                                    input_shape=(10, )))
    model.compile(loss='binary_crossentropy', optimizer='sgd')
    model.save('./model.h5')
    

    接下来,将模型转换为估计量 tf.keras.estimator.model-to-u估计量 ,添加一个输入接收器函数并将其导出到 Savedmodel 格式与 estimator.export保存模型 :

    # Convert keras model to TF estimator
    tf_files_path = './tf'
    estimator =\
        tf.keras.estimator.model_to_estimator(keras_model=model,
                                              model_dir=tf_files_path)
    def serving_input_receiver_fn():
        return tf.estimator.export.build_raw_serving_input_receiver_fn(
            {model.input_names[0]: tf.placeholder(tf.float32, shape=[None, 10])})
    
    # Export the estimator
    export_path = './export'
    estimator.export_savedmodel(
        export_path,
        serving_input_receiver_fn=serving_input_receiver_fn())
    

    这将导致:

    ValueError: Couldn't find trained model at ./tf.
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   sdcbr    7 年前

    我的解决方案如下。检查 ./tf 文件夹明确表示调用 model_to_estimator 将必需的文件存储在 keras 子文件夹,而 export_model 希望这些文件位于 /TF 直接文件夹,因为这是我们为 model_dir 论点:

    $ tree ./tf
    ./tf
    └── keras
        ├── checkpoint
        ├── keras_model.ckpt.data-00000-of-00001
        ├── keras_model.ckpt.index
        └── keras_model.ckpt.meta
    
    1 directory, 4 files
    

    简单的解决方法是将这些文件向上移动一个文件夹。这可以通过python实现:

    import os
    import shutil
    from pathlib import Path
    
    def up_one_dir(path):
        """Move all files in path up one folder, and delete the empty folder
        """
        parent_dir = str(Path(path).parents[0])
        for f in os.listdir(path):
            shutil.move(os.path.join(path, f), parent_dir)
        shutil.rmtree(path)
    
    up_one_dir('./tf/keras')
    

    这将使 模特儿迪尔 目录如下:

    $ tree ./tf
    ./tf
    ├── checkpoint
    ├── keras_model.ckpt.data-00000-of-00001
    ├── keras_model.ckpt.index
    └── keras_model.ckpt.meta
    
    0 directories, 4 files
    

    模型-对-估计量 以及 export_savedmodel 调用允许根据需要导出模型:

    export_path = './export'
    estimator.export_savedmodel(
        export_path,
        serving_input_receiver_fn=serving_input_receiver_fn())
    

    信息:tensorflow:savedmodel写入: /export/temp-b'1549796240'/保存的\u model.pb