python - 为 Keras 编写自定义数据生成器

标签 python keras generator

我将每个数据点存储在一个 .npy 文件中,shape=(1024,7,8)。我想通过类似于 ImageDataGenerator 的方式将它们加载到 Keras 模型中,所以我编写并尝试了不同的自定义生成器,但它们都不起作用,这是我改编自 this 的一个

def find(dirpath, prefix=None, suffix=None, recursive=True):
    """Function to find recursively all files with specific prefix and suffix in a directory
    Return a list of paths
    """
    l = []
    if not prefix:
        prefix = ''
    if not suffix:
        suffix = ''
    for (folders, subfolders, files) in os.walk(dirpath):
        for filename in [f for f in files if f.startswith(prefix) and f.endswith(suffix)]:
            l.append(os.path.join(folders, filename))
        if not recursive:
            break
    l
    return l

def generate_data(directory, batch_size):
    i = 0
    file_list = find(directory)
    while True:
        array_batch = []
        for b in range(batch_size):
            if i == len(file_list):
                i = 0
                random.shuffle(file_list)
            sample = file_list[i]
            i += 1

            array = np.load(sample)
            array_batch.append(array)

        yield array_batch

我发现它缺少标签,所以它不会适合使用 fit_generator 的模型。如果我可以将标签存储在一个 numpy 数组中,我该如何将标签添加到此生成器中?

最佳答案

from tensorflow.python.keras.utils import Sequence
import numpy as np   

class Mygenerator(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 int(np.ceil(len(self.x) / float(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]

        # read your data here using the batch lists, batch_x and batch_y
        x = [my_readfunction(filename) for filename in batch_x] 
        y = [my_readfunction(filename) for filename in batch_y]
        return np.array(x), np.array(y)

关于python - 为 Keras 编写自定义数据生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52754492/

相关文章:

javascript - 网络 worker sleep

python - 如何使用生成器表达式创建多个集合的并集?

python - 通过python程序插入数据库(mysql)

python - 如何使用 Sphinx 只构建一个文件

python - 在没有自定义对象的情况下保存完整的 tf.keras 模型?

python - 创建 Estimator 后更改 Keras 有状态 RNN 模型、层和方法的状态

python - Dash - 间隔不调用回调

python - 只从字符串 python 3 中删除一个字符一次

amazon-web-services - Sagemaker 模型训练中设备上没有剩余空间

python - C++ 中的递归生成器