Search code examples
pythonmachine-learningkerasneural-networkgenerator

Keras: How to use fit_generator with multiple images input and one output?


Is it possible make that fit_generator?

I'm creating a U-net network and I want to use as input a picture high 500, weight 500, and 5 channels, and on the output high 500, weight 500, and 1 channel

model configuration

if it is not possible - i can create 500x500x5 np.arrays by myself and then I'll need a generator for load numpy objects from HDD

my code now (just for rgb picture)

train_generator=datagen.flow_from_directory('/content/data/',
                                                  target_size=(500,500),
                                                  color_mode='rgb',
                                                  batch_size=32,
                                                  class_mode='categorical', shuffle=False)

Solution

  • You should create your own generator. It is essential to get a while True : structure and yield your data. The code looks like this

    batch_size=16
    step_ep=data_size//batch_size
    
    def generator():
      while True:
        for i in range(step_ep):
           process your images
           X=images
           Y=labels
           yield X,Y
    

    With X of shape (batch_size,height,width,channel) and Yof shape (batch_size,height,width,output_channel)

    You should use model.fit() instead of model.fit_generator because it will be soon deprecated.

    You can also create a generator for your validation data.

    Your model.fit() looks like :

    model.fit(generator(),epochs,steps_per_epoch=step_ep, 
              validation_data=val_generator,validation_steps=val_steps)