Skip to content Skip to sidebar Skip to footer

Write Custom Data Generator For Keras

I have each datapoint stored in a .npy file, with shape=(1024,7,8). I want to load them to a Keras model by a manner similar to ImageDataGenerator, so I wrote and tried different c

Solution 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)

Post a Comment for "Write Custom Data Generator For Keras"