【问题标题】:how to save tensorflow model with tf.estimator如何使用 tf.estimator 保存张量流模型
【发布时间】:2019-03-13 00:02:30
【问题描述】:

我有以下示例代码来使用 tensorflow 的 estimator api 训练和评估一个 cnn mnist 模型:

 def model_fn(features, labels, mode):
        images = tf.reshape(features, [-1, 28, 28, 1])
        model = Model()
        logits = model(images)

        predicted_logit = tf.argmax(input=logits, axis=1, output_type=tf.int32)

        if mode == tf.estimator.ModeKeys.PREDICT:
            probabilities = tf.nn.softmax(logits)

            predictions = {
                'predicted_logit': predicted_logit,
                'probabilities': probabilities
            }
            return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

        else:
            ...

    def mnist_train_and_eval(_):
        train_data, train_labels, eval_data, eval_labels, val_data, val_labels = get_mnist_data()

        # Create a input function to train
        train_input_fn = tf.estimator.inputs.numpy_input_fn(
            x= train_data,
            y=train_labels,
            batch_size=_BATCH_SIZE,
            num_epochs=1,
            shuffle=True)

        # Create a input function to eval
        eval_input_fn = tf.estimator.inputs.numpy_input_fn(
            x= eval_data,
            y=eval_labels,
            batch_size=_BATCH_SIZE,
            num_epochs=1,
            shuffle=False)

        # Create a estimator with model_fn
        image_classifier = tf.estimator.Estimator(model_fn=model_fn, model_dir=_MODEL_DIR)

        # Finally, train and evaluate the model after each epoch
        for _ in range(_NUM_EPOCHS):
            image_classifier.train(input_fn=train_input_fn)
            metrics = image_classifier.evaluate(input_fn=eval_input_fn)

我如何使用 estimator.export_savedmodel 来保存经过训练的模型以供以后推断? serving_input_receiver_fn 应该怎么写?

非常感谢您的帮助!

【问题讨论】:

    标签: tensorflow mnist


    【解决方案1】:

    您创建一个带有输入特征字典的函数。占位符应与图像的形状相匹配,第一个维度为 batch_size。

    def serving_input_receiver_fn():
      x = tf.placeholder(tf.float32, [None, Shape])
      inputs = {'x': x}
      return tf.estimator.export.ServingInputReceiver(features=inputs, receiver_tensors=inputs)
    

    或者你可以使用不需要字典映射的TensorServingInputReceiver

    inputs = tf.placeholder(tf.float32, [None, 32*32*3])
    tf.estimator.export.TensorServingInputReceiver(inputs, inputs)
    

    这个函数返回ServingInputReceiver的新实例,它被传递给export_savedmodeltf.estimator.FinalExporter

    ...
    image_classifier.export_savedmodel(saved_dir, serving_input_receiver_fn)
    

    【讨论】:

    • 嗨@Sharky,我输入了您建议的代码,但是使用 input_feature='img',但是当我运行代码时,出现以下错误:TypeError: Expected binary or unicode string, got {'img': }
    • 正确答案
    猜你喜欢
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    相关资源
    最近更新 更多