使用图像预处理功能进行序列而不是图像数据生成器

问题描述

我想做的是使用预处理函数,因为它通常用于图像数据生成器,但是在我按照 tensorflow 文档实现的序列类中(我使用序列的主要动机是因为您可以更改每个时期用于训练的数据,我还没有找到如何在不使用奇怪调整的情况下使用图像数据生成器进行训练)。

这是我使用的代码

import numpy as np
import random
from sklearn.utils import shuffle
from tensorflow.keras.utils import Sequence
from cv2 import imread
# Here,`filenames` is list of path to the images
# and `labels` are the associated labels.

class Fpath2Sequence(Sequence):
    #preprocess function : normalize/scale to [0,1] ... on the batch data only,not the whole data_set (use datagen if you want the preprocess to be more accurate over whole dataset)
    def __init__(self,filenames,labels,batch_size,parent_class,doshuffle=True,do_epochEnd_callback=False,preprocess_function=None):
        self.filenames,self.labels = filenames,labels
        self.batch_size = batch_size
        self.shuffle = shuffle
        if(doshuffle):
            self.filenames,self.labels = shuffle(self.filenames,self.labels)
        self.parent_class = parent_class
        self.do_epochEnd_callback=do_epochEnd_callback
        self.preprocess_function = preprocess_function

    #function to implement for model.fit and predict
    def __len__(self):
        return int(np.ceil(len(self.filenames) / float(self.batch_size)))

    #shuffle data
    def shuffle_data(self):
        self.filenames,self.labels)

    #call parent class to change data in the sequence 
    #(a smaller amount of data might have been use than what is available to avoid class imbalance,so we randomize it further by changing data every epoch)
    def on_epoch_end(self):
        if(self.do_epochEnd_callback):
            self.parent_class.change_sequence_data()
            print("Data changed in epoch_end callback")
        return

    #function to implement for model.fit and predict
    def __getitem__(self,idx):
        batch_x = self.filenames[idx * self.batch_size:(idx + 1) * self.batch_size]
        batch_y = self.labels[idx * self.batch_size:(idx + 1) * self.batch_size]
        x,y = np.array([
            imread(filename)
               for filename in batch_x]),np.array(batch_y)

        if(not(self.preprocess_function is None)):
            x = self.preprocess_function(x)
        return x,y

我的问题是我的预处理函数仅适用于当前使用的批处理,而不适用于整个数据,这适用于 std 计算和标准化,我猜这不是一个好主意对不同的标准化进行不同的标准化每个批次的差异。 当与 imageDataGenerator 一起使用时,它是整个数据集的迭代器,它可以很好地使用预处理函数,我想对我的序列类做同样的事情。

以下是如何将其用于 imageDataGenerator 的示例:

train_batches_o = ImageDataGenerator(preprocessing_function=tf.keras.applications.vgg16.preprocess_input) \
    .flow_from_directory(directory=train_path,target_size=(15,15),classes=['crops_mix','crops_nosky','crops_sky'],batch_size=300)

我现在会继续搜索文档,但如果你们遇到过我的情况,我很想听听。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)