TensorFlow 文档有以下示例,可以说明当训练集太大而无法放入内存时,如何创建批量生成器以将训练集批量提供给模型:
from skimage.io import imread
from skimage.transform import resize
import tensorflow as tf
import numpy as np
import math
# Here, `x_set` is list of path to the images
# and `y_set` are the associated classes.
class CIFAR10Sequence(tf.keras.utils.Sequence):
def __init__(self, x_set, y_set, batch_size):
self.x, self.y = x_set, y_set
self.batch_size = batch_size
def __len__(self):
return math.ceil(len(self.x) / self.batch_size)
def __getitem__(self, idx):
batch_x = self.x[idx * self.batch_size:(idx + 1) *
self.batch_size]
batch_y = self.y[idx * self.batch_size:(idx + 1) *
self.batch_size]
return np.array([
resize(imread(file_name), (200, 200))
for file_name in batch_x]), np.array(batch_y)
我的目的是通过将每个图像旋转 3 倍 90° 来进一步增加训练集的多样性。在训练过程的每个 Epoch 中,模型将首先输入“0° 训练集”,然后分别输入 90°、180° 和 270° 旋转集。
如何修改前面的代码以在CIFAR10Sequence()数据生成器中执行此操作?
请不要使用tf.keras.preprocessing.image.ImageDataGenerator(),以免答案失去对其他类型不同性质的类似问题的普遍性。
注意:这个想法是在模型被输入时“实时”创建新数据,而不是(提前)创建并在磁盘上存储一个比稍后使用的原始训练集更大的新的增强训练集(也在批次)在模型的训练过程中。
米脂
相关分类