Search code examples
pythonmachine-learningkerasautoencodertransfer-learning

Using the output of an internal layer to fit Keras model?


I have a model M that have two inputs: x_train1, x_train2. After passing through heavy transformations these inputs are concatenated into one single array x1_x2. Later it is plugged into an autoencoder where output should be x1_x2. But when I try to fit the model I get the following error:

ValueError: When feeding symbolic tensors to a model, we expect thetensors to have a static batch size. Got tensor with shape: (None, 2080)

I know that the problem lays down on how I am specifying my expected output. I was able to run the code using a dummy array such as np.zeros((96, 2080)), but not by setting the output of an internal layer.

I do the following to fit the model:

autoencoder.fit([x_train1, x_train2], 
                autoencoder.layers[-7].output,
                epochs=50,
                batch_size=8,
                shuffle=True,
                validation_split=0.2)

How can I make Keras understand that the expected output should be the output of an internal layer with shape (number_of_input_images, 2080)?


Solution

  • I'd do the following: Import the Model class from Keras and create an additional model.

    from tensorflow.python.keras.models import Model
    
    # model = your existing model
    
    new_model = Model(
      inputs = model.input,
      outputs = model.get_layer(name_of_desired_output_layer).output
    )
    

    That's it, now you can use your new model and train it instead.