Keras ImageDataGenerator 设置均值和标准差

ali*_*adi 5 python machine-learning keras

我有一个预训练的 keras 模型,我想在新数据集上使用它。我有来自预训练模型的权重、均值和 std 文件,我想使用 Image Data Generator 中的 flow_from_directory 加载新数据集。问题是如何显式设置用于标准化的均值和标准文件?

谢谢

jkj*_*g13 6

我认为您可以使用 ImageDataGenerator 的“featurewise_center”和“featurewise_std_normalization”来处理它。参考:https : //keras.io/preprocessing/image/#imagedatagenerator-class

假设您的预训练数据集的均值 [R, G, B] 值为 [123.68, 116.779, 103.939],标准值为 64.0。然后您可以使用下面的示例代码:(使用带有 TF 后端的 Keras 2,image_data_format='channels_last')

from keras.preprocessing import image

datagen = image.ImageDataGenerator(featurewise_center=True,
                                   featurewise_std_normalization=True)
datagen.mean = np.array([123.68, 116.779, 103.939], dtype=np.float32).reshape((1,1,3)) # ordering: [R, G, B]
datagen.std = 64.
batches = datagen.flow_from_directory(DATASET_PATH + '/train',
                                      target_size=(224,224),
                                      color_mode='rgb',
                                      class_mode='categorical',
                                      shuffle=True,
                                      batch_size=BATCH_SIZE)
Run Code Online (Sandbox Code Playgroud)


S.M*_* sh 2

我认为实现这一目标的最佳方法是编写自己的方法来处理flow_from_directory. 它可能是这样的:

def custom_normilze_generator(directory, mean):
    for img in flow_from_directory(directory):
        yield (img - mean)
Run Code Online (Sandbox Code Playgroud)