将 PyTorch transforms.compose 方法转换为 Keras

Converting PyTorch transforms.compose method into Keras

我了解到我们使用 transforms.compose 通过 torch.transforms 转换图像。我想在 Keras 中做同样的事情,并在互联网上花费数小时,但我不知道如何在 keras 中编写可以做同样事情的方法。以下是 Torch 方式:

# preprocessing
data_transform = transforms.Compose([
   transforms.ToTensor(),
   transforms.Normalize(mean=[.5], std=[.5])
])

谁能给我指出正确的方向。

在 Tensorflow 中有点琐碎。 Tensorflow 建议使用 pre-processing/augmentation 作为模型本身的一部分。

我没有你的完整代码,但我假设你会使用 tf.data.Dataset API 来创建你的数据集。这是在 Tensorflow 中构建数据集的推荐方式。

话虽如此,您可以在模型中预先添加增强层。

# Following is the pre-processing pipeline for e.g
# Step 1: Image resizing.
# Step 2: Image rescaling.
# Step 3: Image normalization

# Having Data Augmentation as part of the input pipeline.
# Step 1: Random flip.
# Step 2: Random Rotate.

pre_processing_pipeline = tf.keras.Sequential([
  layers.Resizing(IMG_SIZE, IMG_SIZE),
  layers.Rescaling(1./255),
  layers.Normalization(mean=[.5], variance=[.5]),
])

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

# Then add it to your model.
# This would be different in your case as you might be using a pre-trained model.

model = tf.keras.Sequential([
  # Add the preprocessing layers you created earlier.
  resize_and_rescale,
  data_augmentation,
  layers.Conv2D(16, 3, padding='same', activation='relu'),
  layers.MaxPooling2D(),
  # Rest of your model.
])

要查看完整的图层列表,请查看此 link. The above-given code can be found on the website here