导出Keras模型作为TF估算:训练模型无法找到

问题描述 投票:2回答:1

尝试将Keras模型导出为TensorFlow估计与服务模型的目的时,我遇到了以下问题。由于同样的问题也弹出in an answer to this question,我将举例说明一个玩具例子发生了什么和文档目的提供我的解决方法解决方案。与Tensorflow 1.12.0和Keras 2.2.4发生此行为。这种情况与实际Keras以及与tf.keras

尝试导出这是从一个tf.keras.estimator.model_to_estimator模型Keras创建的估计时出现问题。当打电话estimator.export_savedmodel,无论是NotFoundErrorValueError异常。

在下面的代码重新产生此用于玩具的例子。

创建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_estimator的估计,加一个输入接收器功能,并将其导出与Savedmodelestimator.export_savedmodel格式:

# 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.
python tensorflow keras
1个回答
1
投票

我的解决方法解决方法如下。检查./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')

这将使得model_dir目录如下所示:

$ tree ./tf
./tf
├── checkpoint
├── keras_model.ckpt.data-00000-of-00001
├── keras_model.ckpt.index
└── keras_model.ckpt.meta

0 directories, 4 files

model_to_estimatorexport_savedmodel调用之间做这个操作允许的模型所需的输出:

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

INFO:tensorflow:SavedModel写到:./export/temp-b'1549796240'/saved_model.pb

© www.soinside.com 2019 - 2024. All rights reserved.