首页 > 解决方案 > Tensorflow Keras 预处理层

问题描述

目前我将所有预处理应用于数据集。但我看到我可以将预处理作为模型的一部分。我读到层预处理在测试时处于非活动状态,但是调整层是什么?例如:

model = Sequential([
  layers.experimental.preprocessing.Resizing(180, 180),
  layers.experimental.preprocessing.Rescaling(1./255),
  layers.Conv2D(16, 3, padding='same', activation='relu'),
  ...

如果我现在使用 model.predict(img) 会发生什么,img 会自动调整大小还是在预测之前我仍然需要调整 img 的大小?

先感谢您!

标签: tensorflowkeras

解决方案


只有以 开头的预处理层Random在评估/测试时被禁用。

在您的情况下,层ResizingRescaling将在每种情况下启用。

您可以在源代码中检查您感兴趣的层是否training在其方法中采用布尔参数call,并在control_flow_util.smart_cond.

例如,该层Resizing不:

class Resizing(PreprocessingLayer):

    def call(self, inputs):
        outputs = image_ops.resize_images_v2(
        images=inputs,
        size=[self.target_height, self.target_width],
        method=self._interpolation_method)
    return outputs

虽然图层RandomFlip确实:

class RandomFlip(PreprocessingLayer):

  def call(self, inputs, training=True):
    if training is None:
      training = K.learning_phase()

    def random_flipped_inputs():
      flipped_outputs = inputs
      if self.horizontal:
        flipped_outputs = image_ops.random_flip_left_right(flipped_outputs,
                                                           self.seed)
      if self.vertical:
        flipped_outputs = image_ops.random_flip_up_down(
            flipped_outputs, self.seed)
      return flipped_outputs

    output = control_flow_util.smart_cond(training, random_flipped_inputs,
                                          lambda: inputs)
    output.set_shape(inputs.shape)
    return output

推荐阅读