将VGGFace ResNet导出到Tensorflow Serving:ValueError:应该定义`Dense`的输入的最后一个维度。发现`None`

2024-04-24 14:47:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码来加载VGGFace预训练ResNet模型并将其导出为tensorflow服务格式。该代码段在不是VGGFace ResNet的类似模型上也起过作用。你知道吗

import tensorflow as tf
import keras
from keras_vggface.vggface import VGGFace

tf.keras.backend.set_learning_phase(0) 
CHANNELS = 3

model = VGGFace(model='resnet50')
model.compile(
    loss=keras.losses.categorical_crossentropy,
    optimizer='adam',
    metrics=['accuracy'])
model.save('models/VGGFaceResnet50_celebrity_classifier.h5')

def serving_input_receiver_fn():

    def decode_and_resize(image_str_tensor):
        """Decodes jpeg string, resizes it and raeturns a uint8 tensor."""
        image = tf.image.decode_jpeg(image_str_tensor, channels=CHANNELS)
        image = tf.cast(image, dtype=tf.uint8)
        return image

    # Optional; currently necessary for batch prediction.
    key_input = tf.placeholder(tf.string, shape=[None]) 
    key_output = tf.identity(key_input)

    input_ph = tf.placeholder(tf.string, shape=[None], name='image_binary')
    images_tensor = tf.map_fn(
            decode_and_resize, input_ph, back_prop=False, dtype=tf.uint8)
    images_tensor = tf.image.convert_image_dtype(images_tensor, dtype=tf.float32) 

    return tf.estimator.export.ServingInputReceiver(
         {'input_1': images_tensor},
         {'bytes': input_ph})


KERAS_MODEL_PATH='models/VGGFaceResnet50_celebrity_classifier.h5'
EXPORT_PATH='serving_model'

# If you are invoking this from your training code, use `keras_model=model` instead.
estimator = tf.keras.estimator.model_to_estimator(
    keras_model_path=KERAS_MODEL_PATH)
estimator.export_savedmodel(
    EXPORT_PATH,
    serving_input_receiver_fn=serving_input_receiver_fn
) 

但是,我得到以下错误:

ValueError                  Traceback (most recent call last)
<ipython-input-1-edfbc77c298a> in <module>
     44 estimator.export_savedmodel(
     45     EXPORT_PATH,
---> 46     serving_input_receiver_fn=serving_input_receiver_fn
     47 ) 
...
ValueError: The last dimension of the inputs to `Dense` should be defined. Found `None`.

我检查了模型摘要,在最后一个维度中没有看到任何None。为什么会出错?你知道吗


Tags: pathimagenoneinputmodeltfkerasfn
1条回答
网友
1楼 · 发布于 2024-04-24 14:47:21

VGGFace的构造函数定义为:def VGGFace(include_top=True, model='vgg16', weights='vggface', input_tensor=None, input_shape=None, pooling=None, classes=None)。最后一个维度的大小是基于input_shape计算的,即如果是None,最后一个维度的大小也将是None。你知道吗

相关问题 更多 >