Tensorflow:ValueError:应该定义“密集”输入的最后一个维度。发现“无”

bcl*_*man 6 python keras tensorflow

我已经创建了一个带有 tensorflow 后端的 keras 模型,但是我很难导出我的模型以在 ML Engine 上使用(作为saved_model.pb)。这是我在做什么:

dataset = tf.data.Dataset.from_tensor_slices((data_train, labels_train))
dataset = dataset.map(lambda x, y: ({'reviews': x}, y))
val_dataset = tf.data.Dataset.from_tensor_slices((data_test, labels_test))
val_dataset = val_dataset.map(lambda x, y: ({'reviews': x}, y))
dataset = dataset.batch(self.batch_size).repeat()  # repeat infinitely
val_dataset = val_dataset.batch(self.batch_size).repeat()
Run Code Online (Sandbox Code Playgroud)

然后我对我的Dataset对象执行一些预处理:

dataset = dataset.map(lambda x, y: preprocess_text_and_y(x,y))
val_dataset = val_dataset.map(lambda x, y: preprocess_text_and_y(x,y))
Run Code Online (Sandbox Code Playgroud)

我构建了我的 keras 模型并调用了.fit(...). 这一切都有效。

然后我尝试导出我的模型,如下所示:

def export(data_vocab):

    estimator = tf.keras.estimator.model_to_estimator(model)

    def serving():
        data_table = tf.contrib.lookup.index_table_from_tensor(tf.constant(self.data_vocab),
                                                                    default_value=0)
        inputs = {
            'reviews': tf.placeholder(shape=[1], dtype=tf.string)
        }
        preproc = inputs.copy()
        preproc = preprocess_text(preproc, data_table)
        return tf.estimator.export.ServingInputReceiver(preproc, inputs)

    estimator.export_savedmodel('./test_export', serving)
Run Code Online (Sandbox Code Playgroud)

不幸的是,我回来了:

ValueError: The last dimension of the inputs to `Dense` should be defined. Found `None`.
Run Code Online (Sandbox Code Playgroud)

我搜索了一下,发现了这个:

如何结合密集层使用 TensorFlow Dataset API

上面说我需要打电话tf.set_shape(...)。我正在将字符串预处理为长度为 100 的整数数组。我尝试添加x['reviews'].set_shape([100])我的preprocess_text函数

但是,这打破了训练:

ValueError: Shapes must be equal rank, but are 2 and 1
Run Code Online (Sandbox Code Playgroud)

关于如何修复的任何想法?

谢谢!

xdu*_*ch0 8

如果在批处理后设置形状,则需要将其设置[None, 100]为包含批处理轴:

x['reviews'].set_shape([None, 100])
Run Code Online (Sandbox Code Playgroud)