在估算器 model_fn 中使用 keras 模型 API 时出现无效参数错误

Invalid Argument error while using keras model API inside an estimator model_fn

我构建的自定义估算器model_fn如下所示,

def _model_fn(features, labels, mode):
      """
        Mask RCNN Model function
      """
      self.keras_model = self.build_graph(mode, config)

      outputs = self.keras_model(features) # ERROR STATEMENT
      # outputs = self.keras_model(list(features.values())) # Same ERROR with this statement

      # Predictions
      if mode == tf.estimator.ModeKeys.PREDICT:
        ... # Defining Prediction Spec

      # Training
      if mode == tf.estimator.ModeKeys.TRAIN:
        # Defining Loss and Training Spec
        ...

      # Evaluation
      ...

_model_fn()tf.data 接收参数 featureslabels,格式为:

features = {
'a' : (batch_size, h, w, 3) # dtype: float
'b' : (batch_size, n) # # dtype: float
}
# And
labels = []

self.keras_model 是使用 tensorflow.keras.models.Model API 构建的,输入占位符(使用层 tensorflow.keras.layers.Input() 定义)名称 'a''b' 各自的形状。

在 运行 之后,使用 train_and_evaluate() 的估算器 _model_fn 运行 很好。该图已初始化,但当训练开始时,我面临以下问题:

tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'a' with dtype float and shape [?,128,128,3] [[{{node a}}]]

我之前使用过自定义估算器,这是第一次在 _model_fn 中使用 tensorflow.keras.models.Model API 来计算图形。

这个问题只发生在这个特定的模型(Mask-RCNN)上。要克服这个问题,可以对方法 self.build_graph(mode, config) 进行如下轻微修改:

def build_graph(mode, config):
    # For Input placeholder definition
    a = KL.Input(tensor=features['a'])
    # Earlier
    # a = KL.Input(shape=[batch_size, h, w, 3], name='a')

    b = KL.Input(tensor=features['b'])
    # Earlier
    # b = KL.Input(shape=[batch_size, n], name='b')
    ...
    ...

这些修改将特征张量直接包装到 tensorflow.keras.layers.Input() 中。稍后可以在使用 tensorflow.keras.models.Model.

定义模型时用于定义输入参数