【问题标题】:Write custom Data Generator for Keras为 Keras 编写自定义数据生成器
【发布时间】:2019-03-16 04:58:37
【问题描述】:

我将每个数据点存储在一个 .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 数组中,我如何将标签添加到此生成器中?

【问题讨论】:

  • while 循环何时停止在while True:??

标签: python keras generator


【解决方案1】:
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)

【讨论】:

  • 你现在可以使用这个生成器调用 model.fit_generator()
  • 如果我的问题是假的,我很抱歉,因为我不擅长 python,但是我将如何使用它作为它的类,而不是一个函数?谢谢
  • train_gen = mygenerator(x_set, y_set, batch_size) 然后在你的 model.fit_generator 调用中使用这个 train_gen
  • 谢谢。这就是我一直在寻找的 :) 网络上的其他解决方案很复杂,我无法使用它们。
  • keras 函数 fit_generator 如何知道 getitem 函数,进而获取数据来训练模型。或者 getitem 不是必需的,只需要 self.x 和 self.y 就足够了吗?
猜你喜欢
  • 2020-12-10
  • 1970-01-01
  • 2017-05-12
  • 2018-10-23
  • 2019-09-28
  • 2020-09-08
  • 1970-01-01
  • 2019-11-10
相关资源
最近更新 更多