从 tf.keras.applications 导入后 Tensorflow 增强层不起作用

Tensorflow augmentation layers not working after importing from tf.keras.applications

我目前正在使用 tf.keras.applications 的模型进行训练。还有一个数据增强层。奇怪的是,在我从应用程序导入模型后,增强层不起作用。增强层在我导入之前确实有效。这是怎么回事?

另外,最近TF 2.8.0新版本发布后才开始出现这种情况。之前一切正常。

增强层的代码是

data_augmentation = tf.keras.Sequential([
  tf.keras.layers.RandomFlip("horizontal_and_vertical"),
  tf.keras.layers.RandomRotation(0.5),
])

我正在使用

导入模型
base_model = tf.keras.applications.MobileNetV3Small(
                 input_shape=(75, 50, 3), alpha=1.0, 
                 weights='imagenet', pooling='avg', include_top=False,
                 dropout_rate=0.1, include_preprocessing=False)

请帮助我了解发生了什么。您可以在此笔记本上重现此处的代码 https://colab.research.google.com/drive/13Jd3l2CxbvIWQv3Y7CtryOdrv2IdKNxD?usp=sharing

您无法从单个输出中看到增强的效果。请设置一个范围,看看增强的效果。

data_augmentation = tf.keras.Sequential([
  tf.keras.layers.RandomFlip("horizontal_and_vertical",seed=5),
  tf.keras.layers.RandomRotation(0.5),
])
for i in range(4):
  aug = data_augmentation(image)
  plt.imshow(aug.numpy().astype('uint8'))
  plt.show()

我注意到 tf 2.8 也有同样的问题。可以通过添加 training =True 来解决,当你 test 增强层时:

aug = data_augmentation(image,training=True)

原因是增强层在训练和预测(推理)中的行为不同,即它会在训练中进行增强但在预测中不做任何事情。理想情况下,该层应根据情况巧妙地设置 training= 参数。显然,它在上面的代码中并不聪明:它不知道你的意图是测试层。

但我认为您在构建完整模型时仍应将训练参数保留为默认值,让增强层完成这项工作。