Keras fit_generator() for long signals I want to make an LSTM network and I have quite a long signal that I want to use as my training data


My X_train is a CSV-file which contains 12 signals with a length of 54 837 488
My y_train is an array that contains a One Hot encoded signal (9 categories) with a length of 54 837 488


If I try to upload the CSV-file as a data frame or as an array in Python I exceed the limit of RAM, so my thought is to use fit_generator(). I have used this before when making image models but then I just used some prebuild generators, but I can't really find any prebuild generators for signals so I decided to try to make one myself.

def generate_data_to_model(y_train):
    while True:
        with open("/mypath/myData.csv") as f:
            for line in f:
                x= line.rstrip('\n').split(",")
                x= np.asarray(x)
                x=x[1:]
                x= x.reshape(1,1,12)
                yield (x, y_train[line])


model = Sequential()
model.add(LSTM(32, input_shape=(1, 12)))
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(9, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer="Adam", metrics=['acc'])

model.fit_generator(generate_data_to_model(y_train),
                    steps_per_epoch=1, epochs=2, verbose=1)


When I start training I get this error: 

&lt;ipython-input-29-33b2195fea44&gt; in generate_data_to_model(y_train)
      8                 x= x.reshape(1,1,12)
 ---&gt; 9                 yield (x, y_train[line])



  only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices
I found a solution to this problem with some good help from this article.
What I found really convenient is to make two generators. One for features, or X, and one for labels, or y.

def generate_X():
    while True:
        with open("/mypath/myData.csv") as f:
            for line in f:
                x= line.rstrip('\n').split(",")
                x= np.asarray(x)
                x=x[1:]
                x= x.reshape(1,1,12)
                yield x



def generate_y():
    while True:
        for i in range(len(y_train)):
            y= y_train[i]
            yield y


And then I go ahead and use these two generators as input to my third generator which will make batches of a desired size to the fit_generator()

def batch_generator(batch_size, gen_x,gen_y): 

    batch_features = np.zeros((batch_size,1, 12))
    batch_labels = np.zeros((batch_size,9))

    while True:
        for i in range(batch_size):
            batch_features[i] = next(gen_x)
            batch_labels[i] = next(gen_y)
        yield batch_features, batch_labels


And last, but not least I am now able to use the batch_generator when training my model

model.fit_generator(batch_generator(128, generate_X(), generate_y()),
                    steps_per_epoch=(len(y_train)/128), epochs=2, verbose=1)