簡體   English   中英

如何保存使用 tf.keras.estimator.model_to_estimator 創建的 tensorflow 估算器?

[英]How do I save a tensorflow estimator created with tf.keras.estimator.model_to_estimator?

如何保存使用 tf.keras.estimator.model_to_estimator 創建的 tensorflow 估算器?

以下是我目前所在的位置。

keras模型:

    def create_model(self):
        model = tf.keras.models.Sequential([
            tf.keras.layers.Reshape((self.num_features,), input_shape=(self.num_features, 1)),
            ...
            tf.keras.layers.Dense(1, activation='sigmoid')
        ])
        model.compile(optimizer='adam',
                      loss="binary_crossentropy",
                      metrics=['accuracy'])
        return model

我從中創建了估算器:

self.model = self.create_model()
self.estimator = tf.keras.estimator.model_to_estimator(keras_model=self.model)
self.serving_input_receiver_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(
tf.feature_column.make_parse_example_spec(
    [tf.feature_column.numeric_column(self.model.input_names[0], shape=self.model.layers[0].input_shape[1:])]
))

然后我訓練模型:

return tf.estimator.train_and_evaluate(
            estimator=self.estimator,
            train_spec=self.train_spec,
            eval_spec=self.test_spec)

最后,我想保存這個模型:

self.estimator.export_saved_model(path, self.serving_input_receiver_fn)

這會引發如下錯誤。 我可以看到創建了test_output/model\\temp-1599746280\\variables\\variables_temp_135e48a636f3441d8d35e49ff7fa2e67/的路徑。

2020-09-10 21:58:01.338876: W tensorflow/core/framework/op_kernel.cc:1767] OP_REQUIRES failed at save_restore_v2_ops.cc:109 : Not found: Failed to create a NewWriteableFile: test_output/model\temp-1599746280\variables\variables_temp_135e48a636f3441d8d35e49ff7fa2e67/part-00000-of-00002.data-00000-of-00001.tempstate13255611844751724719 : The system cannot find the path specified.
; No such process

我會回答我自己的問題,以防其他人為此而苦苦掙扎。 請注意,我還沒有在本地開發環境中使用它,因為tf.estimator在我的本地 Windows 環境中寫入路徑似乎有問題,但它在 SageMaker 中確實有效。

適用於 SageMaker 的代碼如下。

def __init__(..., model_dir)
...
    self.model = self.create_model()
    self.estimator = tf.keras.estimator.model_to_estimator(
        keras_model=self.model, 
        model_dir=model_dir
    )
...

def serving_input_fn(self):
    feature_spec = {
        self.model.input_names[0]: tf.io.FixedLenFeature(
            dtype=tf.float32, 
            shape=[self.num_features]
        )
    }
    logging.debug("feature spec: %s", feature_spec)
    return tf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec)()

...

def save_model(self, path):
    self.estimator.export_saved_model(path, self.serving_input_fn)

注意當在 Windows 本地運行進行測試時,我需要在tf.keras.estimator.model_to_estimator設置model_dir = None並且我無法保存模型,即不調用self.estimator.export_saved_model

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM